-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_intel_server.py
More file actions
348 lines (297 loc) · 11.1 KB
/
code_intel_server.py
File metadata and controls
348 lines (297 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
Code Intelligence MCP Server — Hybrid ctags + clangd for C/C++ projects.
Tier 1 (ctags): find_definition, find_references, list_symbols, search_symbol, rebuild_index
Tier 2 (clangd): hover_info, class_hierarchy, call_hierarchy
"""
import atexit
import os
import sys
from dataclasses import asdict
from pathlib import Path
# Force UTF-8 for stdio — MCP clients expect UTF-8, but Windows defaults to cp1252
if sys.platform == "win32":
sys.stdin.reconfigure(encoding="utf-8")
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
from fastmcp import FastMCP
from ctags_index import CtagsIndex, Symbol
from clangd_client import ClangdClient
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
PROJECT_ROOT = os.environ.get("PROJECT_ROOT", ".")
COMPILE_COMMANDS_DIR = os.environ.get(
"COMPILE_COMMANDS_DIR", "./build"
)
CLANGD_PATH = os.environ.get("CLANGD_PATH", "clangd")
CTAGS_PATH = os.environ.get("CTAGS_PATH", "ctags")
SOURCE_DIR = os.environ.get("SOURCE_DIR", "src")
# ---------------------------------------------------------------------------
# Globals
# ---------------------------------------------------------------------------
index: CtagsIndex | None = None
clangd: ClangdClient | None = None
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _sym_to_dict(sym: Symbol) -> dict:
"""Convert a Symbol to a clean dict for MCP response."""
d = asdict(sym)
# Remove empty optional fields for cleaner output
return {k: v for k, v in d.items() if v or k in ("name", "kind", "file", "line")}
def _ensure_index() -> CtagsIndex:
"""Get the ctags index, raising if unavailable."""
if index is None:
raise RuntimeError("Ctags index not available. Install Universal Ctags and restart.")
return index
def _check_staleness() -> str | None:
"""Return a staleness warning if cache is outdated."""
if index and index.is_cache_stale():
return "Warning: Index may be stale — source files changed since last rebuild. Run rebuild_index for fresh results."
return None
# ---------------------------------------------------------------------------
# MCP Server
# ---------------------------------------------------------------------------
mcp = FastMCP(
"code-intel",
instructions=(
"Code intelligence server for C/C++ projects. "
"Provides symbol lookup (ctags, instant) and precision type/call info (clangd, slower). "
"All file paths are relative to the project root unless absolute."
),
)
# ---------------------------------------------------------------------------
# Tier 1 Tools — ctags (instant)
# ---------------------------------------------------------------------------
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Find where a symbol is defined. Returns file, line, kind, scope, and signature. "
"Use qualified names like 'MyNamespace::MyClass' for precision. "
"Optional kind filter: class, struct, function, member, enum, macro, etc."
),
)
def find_definition(
symbol: str,
kind: str | None = None,
scope: str | None = None,
) -> dict:
"""Find definition(s) of a symbol."""
idx = _ensure_index()
results = idx.find_definition(symbol, kind=kind, scope=scope)
stale = _check_staleness()
return {
"matches": [_sym_to_dict(s) for s in results],
"count": len(results),
**({"warning": stale} if stale else {}),
}
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Find all declaration and definition sites of a symbol. "
"Includes prototypes, forward declarations, and definitions. "
"Optional kind filter."
),
)
def find_references(
symbol: str,
kind: str | None = None,
) -> dict:
"""Find all occurrences of a symbol."""
idx = _ensure_index()
results = idx.find_references(symbol, kind=kind)
stale = _check_staleness()
return {
"matches": [_sym_to_dict(s) for s in results],
"count": len(results),
**({"warning": stale} if stale else {}),
}
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"List all symbols defined in a file. Returns classes, functions, members, etc. "
"Path can be relative to project root (e.g., 'src/server/game/RolePlay/RolePlay.h'). "
"Optional kind filter."
),
)
def list_symbols(
file: str,
kind: str | None = None,
) -> dict:
"""List all symbols in a file."""
idx = _ensure_index()
results = idx.list_symbols(file, kind=kind)
stale = _check_staleness()
return {
"symbols": [_sym_to_dict(s) for s in results],
"count": len(results),
"file": file,
**({"warning": stale} if stale else {}),
}
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Search for symbols by name pattern across the entire project. "
"Supports glob patterns (e.g., '*Handler', 'Add*Script') and substring matches. "
"Optional kind filter. Default limit 50."
),
)
def search_symbol(
pattern: str,
kind: str | None = None,
limit: int = 50,
) -> dict:
"""Search symbols by pattern."""
idx = _ensure_index()
results = idx.search_symbol(pattern, kind=kind, limit=limit)
stale = _check_staleness()
return {
"matches": [_sym_to_dict(s) for s in results],
"count": len(results),
"pattern": pattern,
**({"warning": stale} if stale else {}),
}
@mcp.tool(
description=(
"Rebuild the ctags symbol index. Use scope='fast' (default) for incremental, "
"or scope='full' to force a complete rebuild. Takes ~2-3 seconds."
),
)
def rebuild_index(scope: str = "fast") -> dict:
"""Regenerate the ctags index."""
if scope not in ("fast", "full"):
return {"error": f"Invalid scope '{scope}'. Must be 'fast' or 'full'."}
idx = _ensure_index()
if scope == "full":
idx.clear_cache()
count = idx.build()
idx.save_cache()
return {
"status": "ok",
"symbols": count,
"files": idx.file_count,
"build_time": f"{idx.build_time:.1f}s",
}
# ---------------------------------------------------------------------------
# Tier 2 Tools — clangd (precise, lazy-started)
# ---------------------------------------------------------------------------
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Get type information, documentation, and declaration for a symbol at a specific "
"file location. Uses clangd for precision AST analysis. "
"Line and column are 1-based. First call may take a few seconds to start clangd."
),
)
def hover_info(file: str, line: int, column: int) -> dict:
"""Get hover/type info at a location via clangd."""
if clangd is None or not clangd.available:
return {"error": "clangd is not available. Install LLVM/clangd to enable Tier 2 tools."}
try:
result = clangd.hover(file, line, column)
except FileNotFoundError as e:
return {"error": str(e)}
if result is None:
return {"error": f"No hover info at {file}:{line}:{column}. clangd may still be indexing."}
return {
"file": file,
"line": line,
"column": column,
"hover": result,
}
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Get the class/type inheritance hierarchy (parents and children) for a type at a "
"specific file location. Uses clangd. Line and column are 1-based."
),
)
def class_hierarchy(
file: str,
line: int,
column: int,
) -> dict:
"""Get type hierarchy (supertypes + subtypes) via clangd."""
if clangd is None or not clangd.available:
return {"error": "clangd is not available. Install LLVM/clangd to enable Tier 2 tools."}
try:
result = clangd.get_type_hierarchy(file, line, column)
except FileNotFoundError as e:
return {"error": str(e)}
if result is None:
return {"error": f"No type hierarchy at {file}:{line}:{column}. Ensure cursor is on a class/struct name."}
return result
@mcp.tool(
annotations={"readOnlyHint": True},
description=(
"Get incoming (who calls this) or outgoing (what does this call) call hierarchy for "
"a function at a specific file location. Uses clangd. Line and column are 1-based. "
"direction: 'incoming' (default) or 'outgoing'."
),
)
def call_hierarchy(
file: str,
line: int,
column: int,
direction: str = "incoming",
) -> dict:
"""Get call hierarchy via clangd."""
if clangd is None or not clangd.available:
return {"error": "clangd is not available. Install LLVM/clangd to enable Tier 2 tools."}
try:
result = clangd.get_call_hierarchy(file, line, column, direction)
except FileNotFoundError as e:
return {"error": str(e)}
except ValueError as e:
return {"error": str(e)}
if result is None:
return {"error": f"No call hierarchy at {file}:{line}:{column}. Ensure cursor is on a function/method."}
return {
"file": file,
"line": line,
"column": column,
"direction": direction,
"calls": result,
}
# ---------------------------------------------------------------------------
# Entrypoint
# ---------------------------------------------------------------------------
def _shutdown_clangd():
"""atexit handler to clean up clangd process."""
if clangd:
clangd.shutdown()
def main():
global index, clangd
# --- Tier 1: ctags index ---
ctags_available = True
try:
index = CtagsIndex(PROJECT_ROOT, ctags_path=CTAGS_PATH, source_dir=SOURCE_DIR)
count = index.build_or_load()
print(f"[code-intel] Tier 1 ready: {count} symbols indexed", file=sys.stderr)
except FileNotFoundError:
print("[code-intel] WARNING: ctags not found — Tier 1 tools disabled", file=sys.stderr)
print("[code-intel] Install: https://github.com/universal-ctags/ctags", file=sys.stderr)
ctags_available = False
index = None
except Exception as e:
print(f"[code-intel] WARNING: ctags index failed: {e}", file=sys.stderr)
ctags_available = False
index = None
# --- Tier 2: clangd client (lazy — not started until first use) ---
clangd = ClangdClient(
clangd_path=CLANGD_PATH,
compile_commands_dir=COMPILE_COMMANDS_DIR,
project_root=PROJECT_ROOT,
)
atexit.register(_shutdown_clangd)
if clangd.available:
print("[code-intel] Tier 2 available: clangd will start on first use", file=sys.stderr)
else:
print("[code-intel] WARNING: clangd not found — Tier 2 tools disabled", file=sys.stderr)
# Summary
tier1 = "5 tools" if ctags_available else "DISABLED"
tier2 = "3 tools (lazy)" if clangd.available else "DISABLED"
print(f"[code-intel] Server ready — Tier 1: {tier1}, Tier 2: {tier2}", file=sys.stderr)
mcp.run(transport="stdio")
if __name__ == "__main__":
main()