blastdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,589 @@
1
+ """JSON-RPC 2.0 Model Context Protocol (MCP) stdio server for BlastDiff."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from typing import Any
8
+
9
+ from blastdiff import __version__
10
+ from blastdiff.engine import (
11
+ analyze_repository,
12
+ analyze_symbol_impact_in_repo,
13
+ compute_file_hashes,
14
+ resolve_session_base_ref,
15
+ )
16
+ from blastdiff.export import render_agent_repair_prompt
17
+ from blastdiff.git_adapter import GitAdapter, GitError
18
+ from blastdiff.store import ReviewStore
19
+
20
+ DEFAULT_PROTOCOL_VERSION = "2024-11-05"
21
+
22
+ TOOL_DEFINITIONS: list[dict[str, Any]] = [
23
+ {
24
+ "name": "blastdiff_analyze",
25
+ "description": (
26
+ "Run deterministic review analysis on the local Git repository and "
27
+ "return a concise JSON summary of story buckets, hazards, blast "
28
+ "radius, coverage proof, and open threads."
29
+ ),
30
+ "inputSchema": {
31
+ "type": "object",
32
+ "properties": {
33
+ "base_ref": {
34
+ "type": "string",
35
+ "description": "Optional Git base ref (for example 'main').",
36
+ },
37
+ "staged": {
38
+ "type": "boolean",
39
+ "description": "Analyze staged index changes only.",
40
+ "default": False,
41
+ },
42
+ "coverage_path": {
43
+ "type": "string",
44
+ "description": "Optional path to coverage.xml or lcov.info.",
45
+ },
46
+ "record_round": {
47
+ "type": "boolean",
48
+ "description": "Record a review round snapshot if the diff changed.",
49
+ "default": True,
50
+ },
51
+ },
52
+ "additionalProperties": False,
53
+ },
54
+ },
55
+ {
56
+ "name": "blastdiff_list_threads",
57
+ "description": (
58
+ "List review threads anchored to files, lines, and symbols in the "
59
+ "current review session."
60
+ ),
61
+ "inputSchema": {
62
+ "type": "object",
63
+ "properties": {
64
+ "status": {
65
+ "type": "string",
66
+ "enum": ["open", "resolved", "outdated"],
67
+ "description": "Optional status filter.",
68
+ },
69
+ "base_ref": {
70
+ "type": "string",
71
+ "description": "Optional Git base ref matching the review session.",
72
+ },
73
+ "staged": {
74
+ "type": "boolean",
75
+ "description": "Target the staged review session.",
76
+ "default": False,
77
+ },
78
+ },
79
+ "additionalProperties": False,
80
+ },
81
+ },
82
+ {
83
+ "name": "blastdiff_resolve_thread",
84
+ "description": "Mark a review thread as resolved after fixing the issue.",
85
+ "inputSchema": {
86
+ "type": "object",
87
+ "properties": {
88
+ "thread_id": {
89
+ "type": "string",
90
+ "description": "ID of the review thread to resolve.",
91
+ },
92
+ "status": {
93
+ "type": "string",
94
+ "enum": ["resolved", "open", "outdated"],
95
+ "default": "resolved",
96
+ "description": "New status for the thread.",
97
+ },
98
+ "base_ref": {
99
+ "type": "string",
100
+ "description": "Optional Git base ref matching the review session.",
101
+ },
102
+ "staged": {
103
+ "type": "boolean",
104
+ "description": "Target the staged review session.",
105
+ "default": False,
106
+ },
107
+ },
108
+ "required": ["thread_id"],
109
+ "additionalProperties": False,
110
+ },
111
+ },
112
+ {
113
+ "name": "blastdiff_get_blast_radius",
114
+ "description": (
115
+ "Return modified or removed AST symbols and their untouched "
116
+ "external callers across the repository."
117
+ ),
118
+ "inputSchema": {
119
+ "type": "object",
120
+ "properties": {
121
+ "base_ref": {
122
+ "type": "string",
123
+ "description": "Optional Git base ref.",
124
+ },
125
+ "staged": {
126
+ "type": "boolean",
127
+ "description": "Analyze staged changes only.",
128
+ "default": False,
129
+ },
130
+ },
131
+ "additionalProperties": False,
132
+ },
133
+ },
134
+ {
135
+ "name": "blastdiff_export_prompt",
136
+ "description": (
137
+ "Return the Markdown Agent Repair Brief containing open review "
138
+ "threads and high-priority structural hazards."
139
+ ),
140
+ "inputSchema": {
141
+ "type": "object",
142
+ "properties": {
143
+ "include_hazards": {
144
+ "type": "boolean",
145
+ "description": "Include critical and high structural hazards.",
146
+ "default": True,
147
+ },
148
+ "base_ref": {
149
+ "type": "string",
150
+ "description": "Optional Git base ref.",
151
+ },
152
+ "staged": {
153
+ "type": "boolean",
154
+ "description": "Analyze staged changes only.",
155
+ "default": False,
156
+ },
157
+ },
158
+ "additionalProperties": False,
159
+ },
160
+ },
161
+ {
162
+ "name": "blastdiff_get_round_delta",
163
+ "description": (
164
+ "Return files added, changed, removed, or unchanged since a "
165
+ "previous review round."
166
+ ),
167
+ "inputSchema": {
168
+ "type": "object",
169
+ "properties": {
170
+ "from_round": {
171
+ "type": "integer",
172
+ "description": "Optional round number to compare against.",
173
+ },
174
+ "base_ref": {
175
+ "type": "string",
176
+ "description": "Optional Git base ref.",
177
+ },
178
+ "staged": {
179
+ "type": "boolean",
180
+ "description": "Analyze staged changes only.",
181
+ "default": False,
182
+ },
183
+ },
184
+ "additionalProperties": False,
185
+ },
186
+ },
187
+ {
188
+ "name": "blastdiff_get_symbol_impact",
189
+ "description": (
190
+ "Trace diff-aware bidirectional impact (upstream dependencies/writes "
191
+ "and downstream untouched/in-diff/test references) for a function, "
192
+ "method, class, or variable at a specific file and line."
193
+ ),
194
+ "inputSchema": {
195
+ "type": "object",
196
+ "properties": {
197
+ "file_path": {
198
+ "type": "string",
199
+ "description": "Repository-relative path containing the symbol.",
200
+ },
201
+ "line": {
202
+ "type": "integer",
203
+ "description": "1-based line number of the symbol.",
204
+ "default": 1,
205
+ },
206
+ "symbol": {
207
+ "type": "string",
208
+ "description": "Identifier name (function, method, class, or variable).",
209
+ },
210
+ "base_ref": {
211
+ "type": "string",
212
+ "description": "Optional Git base ref.",
213
+ },
214
+ "staged": {
215
+ "type": "boolean",
216
+ "description": "Analyze staged changes only.",
217
+ "default": False,
218
+ },
219
+ },
220
+ "required": ["file_path", "symbol"],
221
+ "additionalProperties": False,
222
+ },
223
+ },
224
+ ]
225
+
226
+ _TOOL_NAMES = frozenset(tool["name"] for tool in TOOL_DEFINITIONS)
227
+
228
+
229
+ def _jsonrpc_result(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
230
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
231
+
232
+
233
+ def _jsonrpc_error(req_id: Any, code: int, message: str) -> dict[str, Any]:
234
+ return {
235
+ "jsonrpc": "2.0",
236
+ "id": req_id,
237
+ "error": {"code": code, "message": message},
238
+ }
239
+
240
+
241
+ def _tool_text_result(text: str, is_error: bool = False) -> dict[str, Any]:
242
+ return {
243
+ "content": [{"type": "text", "text": text}],
244
+ "isError": is_error,
245
+ }
246
+
247
+
248
+ def _tool_json_result(payload: Any, is_error: bool = False) -> dict[str, Any]:
249
+ return _tool_text_result(
250
+ json.dumps(payload, indent=2, ensure_ascii=False), is_error=is_error
251
+ )
252
+
253
+
254
+ def _call_blastdiff_analyze(
255
+ repo_path: str, args: dict[str, Any]
256
+ ) -> dict[str, Any]:
257
+ analysis = analyze_repository(
258
+ repo_path=repo_path,
259
+ base_ref=args.get("base_ref"),
260
+ staged=bool(args.get("staged", False)),
261
+ coverage_path=args.get("coverage_path"),
262
+ record_round=bool(args.get("record_round", True)),
263
+ )
264
+ open_threads = [t for t in analysis.threads if t.status == "open"]
265
+ summary = {
266
+ "repo_name": analysis.repo_name,
267
+ "branch": analysis.branch,
268
+ "base_ref": analysis.base_ref,
269
+ "target_label": analysis.target_label,
270
+ "current_round": analysis.current_round,
271
+ "analysis_ms": analysis.analysis_ms,
272
+ "story_counts": analysis.story_counts,
273
+ "open_threads_count": len(open_threads),
274
+ "blast_radius": {
275
+ "total_symbol_changes": analysis.blast_radius.total_symbol_changes,
276
+ "signature_breaks": analysis.blast_radius.signature_breaks,
277
+ "removed_symbols": analysis.blast_radius.removed_symbols,
278
+ "unmodified_callers_total": analysis.blast_radius.unmodified_callers_total,
279
+ },
280
+ "proof": analysis.proof.model_dump(mode="json"),
281
+ "hazards": [h.model_dump(mode="json") for h in analysis.hazards],
282
+ "files": [
283
+ {
284
+ "path": f.path,
285
+ "status": f.status,
286
+ "story_bucket": f.story_bucket.value,
287
+ "risk_score": f.risk_score,
288
+ "additions": f.additions,
289
+ "deletions": f.deletions,
290
+ "proof_status": f.proof_status.value,
291
+ "hazards_count": len(f.hazards),
292
+ "symbol_changes_count": len(f.symbol_changes),
293
+ }
294
+ for f in analysis.files
295
+ ],
296
+ }
297
+ return _tool_json_result(summary)
298
+
299
+
300
+ def _call_blastdiff_list_threads(
301
+ repo_path: str, args: dict[str, Any]
302
+ ) -> dict[str, Any]:
303
+ adapter = GitAdapter(repo_path)
304
+ repo_info = adapter.info()
305
+ store = ReviewStore(repo_info.git_dir)
306
+ session_base = resolve_session_base_ref(
307
+ base_ref=args.get("base_ref"), staged=bool(args.get("staged", False))
308
+ )
309
+ session_id = store.get_or_create_session(
310
+ branch=repo_info.branch, base_ref=session_base
311
+ )
312
+ threads = store.list_threads(session_id=session_id, status=args.get("status"))
313
+ return _tool_json_result(
314
+ {
315
+ "session_id": session_id,
316
+ "count": len(threads),
317
+ "threads": [t.model_dump(mode="json") for t in threads],
318
+ }
319
+ )
320
+
321
+
322
+ def _call_blastdiff_resolve_thread(
323
+ repo_path: str, args: dict[str, Any]
324
+ ) -> dict[str, Any]:
325
+ thread_id = args.get("thread_id")
326
+ if not isinstance(thread_id, str) or not thread_id.strip():
327
+ return _tool_text_result("Missing required argument: thread_id", is_error=True)
328
+
329
+ new_status = str(args.get("status", "resolved"))
330
+ adapter = GitAdapter(repo_path)
331
+ repo_info = adapter.info()
332
+ store = ReviewStore(repo_info.git_dir)
333
+ session_base = resolve_session_base_ref(
334
+ base_ref=args.get("base_ref"), staged=bool(args.get("staged", False))
335
+ )
336
+ session_id = store.get_or_create_session(
337
+ branch=repo_info.branch, base_ref=session_base
338
+ )
339
+ rounds = store.list_rounds(session_id)
340
+ current_round = rounds[-1].round_number if rounds else 1
341
+
342
+ updated = store.update_thread_status(
343
+ thread_id=thread_id.strip(),
344
+ status=new_status,
345
+ round_resolved=current_round if new_status == "resolved" else None,
346
+ )
347
+ if updated is None:
348
+ return _tool_text_result(
349
+ f"Review thread not found: {thread_id}", is_error=True
350
+ )
351
+ return _tool_json_result({"thread": updated.model_dump(mode="json")})
352
+
353
+
354
+ def _call_blastdiff_get_blast_radius(
355
+ repo_path: str, args: dict[str, Any]
356
+ ) -> dict[str, Any]:
357
+ analysis = analyze_repository(
358
+ repo_path=repo_path,
359
+ base_ref=args.get("base_ref"),
360
+ staged=bool(args.get("staged", False)),
361
+ record_round=False,
362
+ )
363
+ changes_payload = []
364
+ for change in analysis.blast_radius.changes:
365
+ untouched_callers = [
366
+ caller.model_dump(mode="json")
367
+ for caller in change.callers
368
+ if not caller.in_diff
369
+ ]
370
+ changes_payload.append(
371
+ {
372
+ "file_path": change.file_path,
373
+ "name": change.name,
374
+ "kind": change.kind,
375
+ "change_type": change.change_type,
376
+ "old_signature": change.old_signature,
377
+ "new_signature": change.new_signature,
378
+ "start_line": change.start_line,
379
+ "unmodified_caller_count": change.unmodified_caller_count,
380
+ "untouched_callers": untouched_callers,
381
+ "all_callers": [c.model_dump(mode="json") for c in change.callers],
382
+ "test_callers": [
383
+ c.model_dump(mode="json") for c in change.test_callers
384
+ ],
385
+ }
386
+ )
387
+ return _tool_json_result(
388
+ {
389
+ "total_symbol_changes": analysis.blast_radius.total_symbol_changes,
390
+ "signature_breaks": analysis.blast_radius.signature_breaks,
391
+ "removed_symbols": analysis.blast_radius.removed_symbols,
392
+ "unmodified_callers_total": analysis.blast_radius.unmodified_callers_total,
393
+ "changes": changes_payload,
394
+ }
395
+ )
396
+
397
+
398
+ def _call_blastdiff_export_prompt(
399
+ repo_path: str, args: dict[str, Any]
400
+ ) -> dict[str, Any]:
401
+ analysis = analyze_repository(
402
+ repo_path=repo_path,
403
+ base_ref=args.get("base_ref"),
404
+ staged=bool(args.get("staged", False)),
405
+ record_round=False,
406
+ )
407
+ prompt = render_agent_repair_prompt(
408
+ analysis=analysis,
409
+ include_hazards=bool(args.get("include_hazards", True)),
410
+ )
411
+ return _tool_text_result(prompt)
412
+
413
+
414
+ def _call_blastdiff_get_round_delta(
415
+ repo_path: str, args: dict[str, Any]
416
+ ) -> dict[str, Any]:
417
+ base_ref = args.get("base_ref")
418
+ staged = bool(args.get("staged", False))
419
+ from_round = args.get("from_round")
420
+
421
+ analysis = analyze_repository(
422
+ repo_path=repo_path,
423
+ base_ref=base_ref,
424
+ staged=staged,
425
+ record_round=True,
426
+ )
427
+
428
+ delta = analysis.delta_since_last_round
429
+ if from_round is not None:
430
+ adapter = GitAdapter(repo_path)
431
+ repo_info = adapter.info()
432
+ store = ReviewStore(repo_info.git_dir)
433
+ session_base = resolve_session_base_ref(base_ref=base_ref, staged=staged)
434
+ session_id = store.get_or_create_session(
435
+ branch=repo_info.branch, base_ref=session_base
436
+ )
437
+ file_hashes = compute_file_hashes(analysis.files)
438
+ delta = store.compute_delta(
439
+ session_id=session_id,
440
+ current_file_hashes=file_hashes,
441
+ from_round=int(from_round),
442
+ )
443
+
444
+ return _tool_json_result(
445
+ {
446
+ "current_round": analysis.current_round,
447
+ "total_rounds": len(analysis.rounds),
448
+ "delta": delta.model_dump(mode="json") if delta is not None else None,
449
+ "rounds": [
450
+ {
451
+ "round_number": r.round_number,
452
+ "created_at": r.created_at,
453
+ "head_sha": r.head_sha,
454
+ "summary": r.summary,
455
+ }
456
+ for r in analysis.rounds
457
+ ],
458
+ }
459
+ )
460
+
461
+
462
+ def _call_blastdiff_get_symbol_impact(
463
+ repo_path: str, args: dict[str, Any]
464
+ ) -> dict[str, Any]:
465
+ file_path = str(args.get("file_path", "")).strip()
466
+ symbol = str(args.get("symbol", "")).strip()
467
+ line = int(args.get("line", 1))
468
+ if not file_path or not symbol:
469
+ return _tool_text_result("file_path and symbol are required.", is_error=True)
470
+
471
+ report = analyze_symbol_impact_in_repo(
472
+ repo_path=repo_path,
473
+ symbol=symbol,
474
+ file_path=file_path,
475
+ line=line,
476
+ base_ref=args.get("base_ref"),
477
+ staged=bool(args.get("staged", False)),
478
+ )
479
+ return _tool_json_result(report.model_dump(mode="json"))
480
+
481
+
482
+ def _dispatch_tool(
483
+ name: str, arguments: dict[str, Any], repo_path: str
484
+ ) -> dict[str, Any]:
485
+ if name == "blastdiff_analyze":
486
+ return _call_blastdiff_analyze(repo_path, arguments)
487
+ if name == "blastdiff_list_threads":
488
+ return _call_blastdiff_list_threads(repo_path, arguments)
489
+ if name == "blastdiff_resolve_thread":
490
+ return _call_blastdiff_resolve_thread(repo_path, arguments)
491
+ if name == "blastdiff_get_blast_radius":
492
+ return _call_blastdiff_get_blast_radius(repo_path, arguments)
493
+ if name == "blastdiff_export_prompt":
494
+ return _call_blastdiff_export_prompt(repo_path, arguments)
495
+ if name == "blastdiff_get_round_delta":
496
+ return _call_blastdiff_get_round_delta(repo_path, arguments)
497
+ if name == "blastdiff_get_symbol_impact":
498
+ return _call_blastdiff_get_symbol_impact(repo_path, arguments)
499
+ raise KeyError(name)
500
+
501
+
502
+ def handle_mcp_request(
503
+ request: dict[str, Any], repo_path: str = "."
504
+ ) -> dict[str, Any] | None:
505
+ """Pure dispatcher for a single JSON-RPC 2.0 MCP request."""
506
+ if not isinstance(request, dict):
507
+ return _jsonrpc_error(None, -32600, "Invalid Request")
508
+
509
+ has_id = "id" in request
510
+ req_id = request.get("id")
511
+ method = request.get("method")
512
+ params = request.get("params")
513
+ if params is None:
514
+ params = {}
515
+
516
+ if not isinstance(method, str):
517
+ return _jsonrpc_error(req_id, -32600, "Invalid Request: missing method")
518
+
519
+ if method.startswith("notifications/"):
520
+ return None
521
+
522
+ if method == "initialize":
523
+ protocol_version = (
524
+ params.get("protocolVersion", DEFAULT_PROTOCOL_VERSION)
525
+ if isinstance(params, dict)
526
+ else DEFAULT_PROTOCOL_VERSION
527
+ )
528
+ return _jsonrpc_result(
529
+ req_id,
530
+ {
531
+ "protocolVersion": str(protocol_version),
532
+ "capabilities": {"tools": {}},
533
+ "serverInfo": {"name": "blastdiff", "version": __version__},
534
+ },
535
+ )
536
+
537
+ if method == "ping":
538
+ return _jsonrpc_result(req_id, {})
539
+
540
+ if method == "tools/list":
541
+ return _jsonrpc_result(req_id, {"tools": TOOL_DEFINITIONS})
542
+
543
+ if method == "tools/call":
544
+ if not isinstance(params, dict):
545
+ return _jsonrpc_error(req_id, -32602, "Invalid params")
546
+ tool_name = params.get("name")
547
+ arguments = params.get("arguments") or {}
548
+ if not isinstance(tool_name, str) or tool_name not in _TOOL_NAMES:
549
+ return _jsonrpc_error(
550
+ req_id, -32602, f"Unknown tool: {tool_name}"
551
+ )
552
+ if not isinstance(arguments, dict):
553
+ return _jsonrpc_error(
554
+ req_id, -32602, "Invalid params: arguments must be an object"
555
+ )
556
+ try:
557
+ result = _dispatch_tool(tool_name, arguments, repo_path)
558
+ except (GitError, ValueError) as exc:
559
+ result = _tool_text_result(str(exc), is_error=True)
560
+ except Exception as exc:
561
+ result = _tool_text_result(
562
+ f"Internal error executing {tool_name}: {exc}", is_error=True
563
+ )
564
+ return _jsonrpc_result(req_id, result)
565
+
566
+ if not has_id:
567
+ return None
568
+
569
+ return _jsonrpc_error(req_id, -32601, f"Method not found: {method}")
570
+
571
+
572
+ def run_mcp_stdio(repo_path: str = ".") -> None:
573
+ """Serve MCP JSON-RPC 2.0 requests over newline-delimited stdin/stdout."""
574
+ for raw_line in sys.stdin:
575
+ line = raw_line.strip()
576
+ if not line:
577
+ continue
578
+ try:
579
+ payload = json.loads(line)
580
+ except json.JSONDecodeError as exc:
581
+ err = _jsonrpc_error(None, -32700, f"Parse error: {exc}")
582
+ sys.stdout.write(json.dumps(err, ensure_ascii=False) + "\n")
583
+ sys.stdout.flush()
584
+ continue
585
+
586
+ response = handle_mcp_request(payload, repo_path=repo_path)
587
+ if response is not None:
588
+ sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
589
+ sys.stdout.flush()