Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
471 lines (444 loc) · 17.8 KB
/
Copy pathserver.py
File metadata and controls
471 lines (444 loc) · 17.8 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
"""
server.py
---------
CodeMap MCP Server — entry point.
Registers all six MCP tools and starts the server.
Usage:
python server.py
# or via MCP client config pointing to this file
Environment variables:
ANTHROPIC_API_KEY — required for generate_roadmap LLM output
(structural output works without it)
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Any
# ---------------------------------------------------------------------------
# MCP SDK import
# ---------------------------------------------------------------------------
try:
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp import types
HAS_MCP = True
except ImportError:
HAS_MCP = False
print(
"ERROR: mcp package not installed.\n"
"Install with: pip install mcp\n",
file=sys.stderr,
)
sys.exit(1)
# ---------------------------------------------------------------------------
# CodeMap internal imports
# ---------------------------------------------------------------------------
from config import load_config, describe_config
from tools.discover import discover_structure
from tools.read_file import read_file
from tools.search_symbol import search_symbol
from tools.generate_roadmap import generate_roadmap
from tools.explain_error import explain_error
from tools.explain_pr import explain_pr
# ---------------------------------------------------------------------------
# Server setup
# ---------------------------------------------------------------------------
server = Server("codemap-mcp")
# ---------------------------------------------------------------------------
# Tool: discover_structure
# ---------------------------------------------------------------------------
@server.list_tools()
async def list_tools() -> list[types.Tool]:
return [
types.Tool(
name="discover_structure",
description=(
"Walk the target repository or folder and return a structured map "
"of all Python files, packages, and top-level directories. "
"Read-only — uses os.walk and pathlib only."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"target": {
"type": "string",
"description": (
"Optional subfolder or feature name to narrow the scan. "
"Leave empty to scan the whole repository."
),
},
},
"required": ["repo_path"],
},
),
types.Tool(
name="read_file",
description=(
"Return the raw content of a single Python file so the LLM can "
"inspect it in detail. Read-only — uses pathlib.read_text() only. "
"Validates that the path stays within the repository root."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"file_path": {
"type": "string",
"description": "Path to file relative to repo_path.",
},
},
"required": ["repo_path", "file_path"],
},
),
types.Tool(
name="search_symbol",
description=(
"Search for a class name, function name, or import pattern across "
"all Python files in scope. Uses ast.parse() — no code execution. "
"Returns file path, line number, and symbol type for each match."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"query": {
"type": "string",
"description": "Name or pattern to find (case-insensitive substring match).",
},
"scope": {
"type": "string",
"description": "Optional subfolder to limit search.",
},
},
"required": ["repo_path", "query"],
},
),
types.Tool(
name="generate_roadmap",
description=(
"Use the discovered structure and symbol graph to generate a "
"human-readable roadmap. Produces prose flow explanation, key files "
"table, and a Mermaid graph with conditional edge labels. "
"Requires ANTHROPIC_API_KEY for LLM prose; structural output available without it."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"scope": {
"type": "string",
"description": (
"Folder path or feature name to explain "
"(e.g. 'payments', 'payments/', 'app/services')."
),
},
"question": {
"type": "string",
"description": (
"Optional specific aspect to explain "
"(e.g. 'how is process_payment triggered?')."
),
},
"max_depth": {
"type": "integer",
"description": "Maximum call chain nodes to trace (default 15, range 1-20).",
"minimum": 1,
"maximum": 20,
"default": 15,
},
"use_llm": {
"type": "boolean",
"description": (
"Set to false to skip LLM and return structural output only. "
"Default: true."
),
"default": True,
},
},
"required": ["repo_path", "scope"],
},
),
types.Tool(
name="explain_error",
description=(
"Parse a Python stacktrace/traceback and explain the issue with local "
"source code context. Uses static search (read-only)."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"stacktrace": {
"type": "string",
"description": "The pasted stacktrace/traceback string.",
},
"use_llm": {
"type": "boolean",
"description": "Set to false to skip LLM and return structural context only. Default: true.",
"default": True,
},
},
"required": ["repo_path", "stacktrace"],
},
),
types.Tool(
name="explain_pr",
description=(
"Analyse the impact of a pull request or git diff without pushing data "
"to any external service. Returns changed files, changed symbols, blast "
"radius, and affected HTTP routes as Markdown. Read-only — uses "
"git diff + static call graph only."
),
inputSchema={
"type": "object",
"properties": {
"repo_path": {
"type": "string",
"description": "Absolute path to the repository root.",
},
"base_ref": {
"type": "string",
"description": "Git ref (branch or commit SHA) to diff against (default: 'main').",
"default": "main",
},
"head_ref": {
"type": "string",
"description": "Git ref for the PR head (default: 'HEAD').",
"default": "HEAD",
},
"diff_text": {
"type": "string",
"description": (
"Optional: paste a raw unified diff or list of changed files here. "
"When provided, skips running git and uses this text directly."
),
},
"use_llm": {
"type": "boolean",
"description": (
"Set to false to skip the AI impact summary and return "
"structural analysis only. Default: true."
),
"default": True,
},
},
"required": ["repo_path"],
},
),
]
# ---------------------------------------------------------------------------
# Tool call dispatcher
# ---------------------------------------------------------------------------
async def _run_tool_handler(
name: str,
arguments: dict[str, Any],
) -> list[types.TextContent]:
"""
Dispatch MCP tool calls to the appropriate handler.
Always returns a list of TextContent — never writes to disk.
"""
repo_path = arguments.get("repo_path", "")
# Load config for this repo (cached per call for simplicity)
config = {}
if repo_path:
try:
config = load_config(repo_path)
except Exception:
config = {}
# -----------------------------------------------------------------------
# discover_structure
# -----------------------------------------------------------------------
if name == "discover_structure":
result = discover_structure(
repo_path=repo_path,
target=arguments.get("target"),
config=config,
)
if result["success"]:
output = result["tree_text"]
stats = result["file_info"].get("stats", {})
output += (
f"\n\nStats: {stats.get('total_py_files', 0)} Python files, "
f"{stats.get('total_packages', 0)} packages, "
f"{stats.get('skipped', 0)} skipped."
)
else:
output = f"Error: {result['error']}"
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# read_file
# -----------------------------------------------------------------------
elif name == "read_file":
result = read_file(
repo_path=repo_path,
file_path=arguments.get("file_path", ""),
)
if result["success"]:
output = (
f"File: {result['path']} ({result['lines']} lines, {result['size_kb']} KB)\n"
f"{'=' * 60}\n"
f"{result['content']}"
)
else:
output = f"Error: {result['error']}"
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# search_symbol
# -----------------------------------------------------------------------
elif name == "search_symbol":
result = search_symbol(
repo_path=repo_path,
query=arguments.get("query", ""),
scope=arguments.get("scope"),
config=config,
)
if result["success"]:
matches = result["matches"]
if not matches:
output = f"No symbols matching '{arguments.get('query')}' found."
else:
lines = [
f"Found {result['total_matches']} match(es) "
f"across {result['files_scanned']} files:\n"
]
for m in matches:
parent = f" (in {m['parent']})" if m.get("parent") else ""
doc = f"\n {m['docstring']}" if m.get("docstring") else ""
lines.append(
f" [{m['kind']}] {m['name']}{parent}\n"
f" {m['file']}:{m['line']}{doc}"
)
if result["parse_errors"]:
lines.append(
f"\n⚠️ {len(result['parse_errors'])} file(s) had parse errors and were skipped."
)
output = "\n".join(lines)
else:
output = f"Error: {result['error']}"
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# generate_roadmap
# -----------------------------------------------------------------------
elif name == "generate_roadmap":
max_depth = arguments.get("max_depth", 15)
# Clamp to valid range
max_depth = max(1, min(20, int(max_depth)))
result = generate_roadmap(
repo_path=repo_path,
scope=arguments.get("scope", ""),
question=arguments.get("question", ""),
max_depth=max_depth,
config=config,
use_llm=arguments.get("use_llm", True),
)
if result["success"]:
output_parts = [result["roadmap"]]
if result["routes_found"]:
output_parts.append(
f"\n_HTTP routes found: {result['routes_found']}_"
)
else:
output_parts = [f"Error generating roadmap: {result['error']}"]
output = "\n".join(output_parts)
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# explain_error
# -----------------------------------------------------------------------
elif name == "explain_error":
result = explain_error(
repo_path=repo_path,
stacktrace=arguments.get("stacktrace", ""),
use_llm=arguments.get("use_llm", True),
)
if result["success"]:
output = result["explanation"]
else:
output = f"Error explaining stacktrace: {result['error']}"
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# explain_pr
# -----------------------------------------------------------------------
elif name == "explain_pr":
result = explain_pr(
repo_path=repo_path,
base_ref=arguments.get("base_ref", "main"),
head_ref=arguments.get("head_ref", "HEAD"),
diff_text=arguments.get("diff_text", ""),
use_llm=arguments.get("use_llm", True),
config=config,
)
if result["success"]:
output = result["summary_md"]
else:
output = f"Error analysing PR diff: {result['error']}"
return [types.TextContent(type="text", text=output)]
# -----------------------------------------------------------------------
# Unknown tool
# -----------------------------------------------------------------------
else:
return [
types.TextContent(
type="text",
text=f"Unknown tool: '{name}'. Available tools: "
"discover_structure, read_file, search_symbol, "
"generate_roadmap, explain_error, explain_pr",
)
]
@server.call_tool()
async def call_tool(
name: str,
arguments: dict[str, Any],
) -> list[types.TextContent]:
"""
Dispatch MCP tool calls to the appropriate handler.
Supports local paths and remote Git URLs (automatically clones and cleans up).
"""
repo_path = arguments.get("repo_path", "")
is_remote = repo_path.startswith(("http://", "https://", "git@", "git://"))
if is_remote:
from analysis.remote_repo import clone_remote_repo
cwd = Path(".").resolve()
try:
with clone_remote_repo(repo_path, cwd) as temp_local_path:
local_args = dict(arguments)
local_args["repo_path"] = str(temp_local_path)
return await _run_tool_handler(name, local_args)
except Exception as e:
return [
types.TextContent(
type="text",
text=f"Error executing tool '{name}' on remote repository: {e}"
)
]
else:
return await _run_tool_handler(name, arguments)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
async def main():
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
server.create_initialization_options(),
)
if __name__ == "__main__":
import asyncio
asyncio.run(main())