@grafema/mcp 0.2.1-beta → 0.2.6-beta

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.
Files changed (96) hide show
  1. package/README.md +49 -25
  2. package/dist/analysis-worker.js +16 -8
  3. package/dist/analysis-worker.js.map +1 -0
  4. package/dist/analysis.d.ts.map +1 -1
  5. package/dist/analysis.js +1 -0
  6. package/dist/analysis.js.map +1 -0
  7. package/dist/config.d.ts.map +1 -1
  8. package/dist/config.js +27 -7
  9. package/dist/config.js.map +1 -0
  10. package/dist/definitions.d.ts +4 -4
  11. package/dist/definitions.d.ts.map +1 -1
  12. package/dist/definitions.js +158 -3
  13. package/dist/definitions.js.map +1 -0
  14. package/dist/handlers/analysis-handlers.d.ts +9 -0
  15. package/dist/handlers/analysis-handlers.d.ts.map +1 -0
  16. package/dist/handlers/analysis-handlers.js +73 -0
  17. package/dist/handlers/analysis-handlers.js.map +1 -0
  18. package/dist/handlers/context-handlers.d.ts +21 -0
  19. package/dist/handlers/context-handlers.d.ts.map +1 -0
  20. package/dist/handlers/context-handlers.js +330 -0
  21. package/dist/handlers/context-handlers.js.map +1 -0
  22. package/dist/handlers/coverage-handlers.d.ts +6 -0
  23. package/dist/handlers/coverage-handlers.d.ts.map +1 -0
  24. package/dist/handlers/coverage-handlers.js +42 -0
  25. package/dist/handlers/coverage-handlers.js.map +1 -0
  26. package/dist/handlers/dataflow-handlers.d.ts +8 -0
  27. package/dist/handlers/dataflow-handlers.d.ts.map +1 -0
  28. package/dist/handlers/dataflow-handlers.js +140 -0
  29. package/dist/handlers/dataflow-handlers.js.map +1 -0
  30. package/dist/handlers/documentation-handlers.d.ts +6 -0
  31. package/dist/handlers/documentation-handlers.d.ts.map +1 -0
  32. package/dist/handlers/documentation-handlers.js +79 -0
  33. package/dist/handlers/documentation-handlers.js.map +1 -0
  34. package/dist/handlers/guarantee-handlers.d.ts +21 -0
  35. package/dist/handlers/guarantee-handlers.d.ts.map +1 -0
  36. package/dist/handlers/guarantee-handlers.js +251 -0
  37. package/dist/handlers/guarantee-handlers.js.map +1 -0
  38. package/dist/handlers/guard-handlers.d.ts +14 -0
  39. package/dist/handlers/guard-handlers.d.ts.map +1 -0
  40. package/dist/handlers/guard-handlers.js +77 -0
  41. package/dist/handlers/guard-handlers.js.map +1 -0
  42. package/dist/handlers/index.d.ts +14 -0
  43. package/dist/handlers/index.d.ts.map +1 -0
  44. package/dist/handlers/index.js +14 -0
  45. package/dist/handlers/index.js.map +1 -0
  46. package/dist/handlers/issue-handlers.d.ts +6 -0
  47. package/dist/handlers/issue-handlers.d.ts.map +1 -0
  48. package/dist/handlers/issue-handlers.js +66 -0
  49. package/dist/handlers/issue-handlers.js.map +1 -0
  50. package/dist/handlers/project-handlers.d.ts +7 -0
  51. package/dist/handlers/project-handlers.d.ts.map +1 -0
  52. package/dist/handlers/project-handlers.js +153 -0
  53. package/dist/handlers/project-handlers.js.map +1 -0
  54. package/dist/handlers/query-handlers.d.ts +8 -0
  55. package/dist/handlers/query-handlers.d.ts.map +1 -0
  56. package/dist/handlers/query-handlers.js +171 -0
  57. package/dist/handlers/query-handlers.js.map +1 -0
  58. package/dist/handlers.d.ts +6 -2
  59. package/dist/handlers.d.ts.map +1 -1
  60. package/dist/handlers.js +367 -20
  61. package/dist/handlers.js.map +1 -0
  62. package/dist/prompts.d.ts +25 -0
  63. package/dist/prompts.d.ts.map +1 -0
  64. package/dist/prompts.js +33 -0
  65. package/dist/prompts.js.map +1 -0
  66. package/dist/server.js +52 -20
  67. package/dist/server.js.map +1 -0
  68. package/dist/state.js +1 -0
  69. package/dist/state.js.map +1 -0
  70. package/dist/types.d.ts +59 -1
  71. package/dist/types.d.ts.map +1 -1
  72. package/dist/types.js +1 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/utils.js +2 -1
  75. package/dist/utils.js.map +1 -0
  76. package/package.json +4 -3
  77. package/src/analysis-worker.ts +20 -9
  78. package/src/analysis.ts +2 -1
  79. package/src/config.ts +36 -4
  80. package/src/definitions.ts +162 -5
  81. package/src/handlers/analysis-handlers.ts +105 -0
  82. package/src/handlers/context-handlers.ts +410 -0
  83. package/src/handlers/coverage-handlers.ts +56 -0
  84. package/src/handlers/dataflow-handlers.ts +193 -0
  85. package/src/handlers/documentation-handlers.ts +89 -0
  86. package/src/handlers/guarantee-handlers.ts +278 -0
  87. package/src/handlers/guard-handlers.ts +100 -0
  88. package/src/handlers/index.ts +14 -0
  89. package/src/handlers/issue-handlers.ts +81 -0
  90. package/src/handlers/project-handlers.ts +200 -0
  91. package/src/handlers/query-handlers.ts +232 -0
  92. package/src/prompts.ts +56 -0
  93. package/src/server.ts +87 -21
  94. package/src/types.ts +68 -1
  95. package/src/utils.ts +2 -2
  96. package/src/handlers.ts +0 -1180
package/src/handlers.ts DELETED
@@ -1,1180 +0,0 @@
1
- /**
2
- * MCP Tool Handlers
3
- */
4
-
5
- import { join } from 'path';
6
- import { ensureAnalyzed } from './analysis.js';
7
- import { getProjectPath, getAnalysisStatus, getOrCreateBackend, getGuaranteeManager, getGuaranteeAPI, isAnalysisRunning } from './state.js';
8
- import { CoverageAnalyzer, findCallsInFunction, findContainingFunction } from '@grafema/core';
9
- import type { CallInfo, CallerInfo } from '@grafema/core';
10
- import {
11
- normalizeLimit,
12
- formatPaginationInfo,
13
- guardResponseSize,
14
- serializeBigInt,
15
- findSimilarTypes,
16
- textResult,
17
- errorResult,
18
- } from './utils.js';
19
- import type {
20
- ToolResult,
21
- QueryGraphArgs,
22
- FindCallsArgs,
23
- FindNodesArgs,
24
- TraceAliasArgs,
25
- TraceDataFlowArgs,
26
- CheckInvariantArgs,
27
- AnalyzeProjectArgs,
28
- GetSchemaArgs,
29
- CreateGuaranteeArgs,
30
- CheckGuaranteesArgs,
31
- DeleteGuaranteeArgs,
32
- GetCoverageArgs,
33
- GetDocumentationArgs,
34
- FindGuardsArgs,
35
- GuardInfo,
36
- GetFunctionDetailsArgs,
37
- GraphBackend,
38
- GraphNode,
39
- } from './types.js';
40
- import { isGuaranteeType } from '@grafema/core';
41
-
42
- // === QUERY HANDLERS ===
43
-
44
- export async function handleQueryGraph(args: QueryGraphArgs): Promise<ToolResult> {
45
- const db = await ensureAnalyzed();
46
- const { query, limit: requestedLimit, offset: requestedOffset, format } = args;
47
- const explain = (args as any).explain;
48
-
49
- const limit = normalizeLimit(requestedLimit);
50
- const offset = Math.max(0, requestedOffset || 0);
51
-
52
- try {
53
- // Check if backend supports Datalog queries
54
- if (!('checkGuarantee' in db)) {
55
- return errorResult('Backend does not support Datalog queries');
56
- }
57
-
58
- const checkFn = (db as unknown as { checkGuarantee: (q: string) => Promise<Array<{ bindings: Array<{ name: string; value: string }> }>> }).checkGuarantee;
59
- const results = await checkFn(query);
60
- const total = results.length;
61
-
62
- if (total === 0) {
63
- const nodeCounts = await db.countNodesByType();
64
- const totalNodes = Object.values(nodeCounts).reduce((a, b) => a + b, 0);
65
-
66
- const typeMatch = query.match(/node\([^,]+,\s*"([^"]+)"\)/);
67
- const queriedType = typeMatch ? typeMatch[1] : null;
68
-
69
- let hint = '';
70
- if (queriedType && !nodeCounts[queriedType]) {
71
- const availableTypes = Object.keys(nodeCounts);
72
- const similar = findSimilarTypes(queriedType, availableTypes);
73
- if (similar.length > 0) {
74
- hint = `\n💡 Did you mean: ${similar.join(', ')}?`;
75
- } else {
76
- hint = `\n💡 Available types: ${availableTypes.slice(0, 10).join(', ')}${availableTypes.length > 10 ? '...' : ''}`;
77
- }
78
- }
79
-
80
- return textResult(
81
- `Query returned no results.${hint}\n📊 Graph: ${totalNodes.toLocaleString()} nodes`
82
- );
83
- }
84
-
85
- const paginatedResults = results.slice(offset, offset + limit);
86
- const hasMore = offset + limit < total;
87
-
88
- const enrichedResults: unknown[] = [];
89
- for (const result of paginatedResults) {
90
- const nodeId = result.bindings?.find((b: any) => b.name === 'X')?.value;
91
- if (nodeId) {
92
- const node = await db.getNode(nodeId);
93
- if (node) {
94
- enrichedResults.push({
95
- ...node,
96
- id: nodeId,
97
- file: node.file,
98
- line: node.line,
99
- });
100
- }
101
- }
102
- }
103
-
104
- const paginationInfo = formatPaginationInfo({
105
- limit,
106
- offset,
107
- returned: enrichedResults.length,
108
- total,
109
- hasMore,
110
- });
111
-
112
- const responseText = `Found ${total} result(s):${paginationInfo}\n\n${JSON.stringify(
113
- serializeBigInt(enrichedResults),
114
- null,
115
- 2
116
- )}`;
117
-
118
- return textResult(guardResponseSize(responseText));
119
- } catch (error) {
120
- return errorResult((error as Error).message);
121
- }
122
- }
123
-
124
- export async function handleFindCalls(args: FindCallsArgs): Promise<ToolResult> {
125
- const db = await ensureAnalyzed();
126
- const { target: name, limit: requestedLimit, offset: requestedOffset } = args;
127
- const className = (args as any).className;
128
-
129
- const limit = normalizeLimit(requestedLimit);
130
- const offset = Math.max(0, requestedOffset || 0);
131
-
132
- const calls: unknown[] = [];
133
- let skipped = 0;
134
- let totalMatched = 0;
135
-
136
- for await (const node of db.queryNodes({ type: 'CALL' })) {
137
- if ((node as any).name !== name && (node as any).method !== name) continue;
138
- if (className && (node as any).object !== className) continue;
139
-
140
- totalMatched++;
141
-
142
- if (skipped < offset) {
143
- skipped++;
144
- continue;
145
- }
146
-
147
- if (calls.length >= limit) continue;
148
-
149
- const callsEdges = await db.getOutgoingEdges(node.id, ['CALLS']);
150
- const isResolved = callsEdges.length > 0;
151
-
152
- let target = null;
153
- if (isResolved) {
154
- const targetNode = await db.getNode(callsEdges[0].dst);
155
- target = targetNode
156
- ? {
157
- type: targetNode.type,
158
- name: targetNode.name,
159
- file: targetNode.file,
160
- line: targetNode.line,
161
- }
162
- : null;
163
- }
164
-
165
- calls.push({
166
- id: node.id,
167
- name: (node as any).name,
168
- object: (node as any).object,
169
- file: node.file,
170
- line: node.line,
171
- resolved: isResolved,
172
- target,
173
- });
174
- }
175
-
176
- if (totalMatched === 0) {
177
- return textResult(`No calls found for "${className ? className + '.' : ''}${name}"`);
178
- }
179
-
180
- const resolved = calls.filter((c: any) => c.resolved).length;
181
- const unresolved = calls.length - resolved;
182
- const hasMore = offset + calls.length < totalMatched;
183
-
184
- const paginationInfo = formatPaginationInfo({
185
- limit,
186
- offset,
187
- returned: calls.length,
188
- total: totalMatched,
189
- hasMore,
190
- });
191
-
192
- const responseText =
193
- `Found ${totalMatched} call(s) to "${className ? className + '.' : ''}${name}":${paginationInfo}\n` +
194
- `- Resolved: ${resolved}\n` +
195
- `- Unresolved: ${unresolved}\n\n` +
196
- JSON.stringify(serializeBigInt(calls), null, 2);
197
-
198
- return textResult(guardResponseSize(responseText));
199
- }
200
-
201
- export async function handleFindNodes(args: FindNodesArgs): Promise<ToolResult> {
202
- const db = await ensureAnalyzed();
203
- const { type, name, file, limit: requestedLimit, offset: requestedOffset } = args;
204
-
205
- const limit = normalizeLimit(requestedLimit);
206
- const offset = Math.max(0, requestedOffset || 0);
207
-
208
- const filter: Record<string, unknown> = {};
209
- if (type) filter.type = type;
210
- if (name) filter.name = name;
211
- if (file) filter.file = file;
212
-
213
- const nodes: GraphNode[] = [];
214
- let skipped = 0;
215
- let totalMatched = 0;
216
-
217
- for await (const node of db.queryNodes(filter)) {
218
- totalMatched++;
219
-
220
- if (skipped < offset) {
221
- skipped++;
222
- continue;
223
- }
224
-
225
- if (nodes.length < limit) {
226
- nodes.push(node);
227
- }
228
- }
229
-
230
- if (totalMatched === 0) {
231
- return textResult('No nodes found matching criteria');
232
- }
233
-
234
- const hasMore = offset + nodes.length < totalMatched;
235
- const paginationInfo = formatPaginationInfo({
236
- limit,
237
- offset,
238
- returned: nodes.length,
239
- total: totalMatched,
240
- hasMore,
241
- });
242
-
243
- return textResult(
244
- `Found ${totalMatched} node(s):${paginationInfo}\n\n${JSON.stringify(
245
- serializeBigInt(nodes),
246
- null,
247
- 2
248
- )}`
249
- );
250
- }
251
-
252
- // === TRACE HANDLERS ===
253
-
254
- export async function handleTraceAlias(args: TraceAliasArgs): Promise<ToolResult> {
255
- const db = await ensureAnalyzed();
256
- const { variableName, file } = args;
257
- const projectPath = getProjectPath();
258
-
259
- let varNode: GraphNode | null = null;
260
-
261
- for await (const node of db.queryNodes({ type: 'VARIABLE' })) {
262
- if (node.name === variableName && node.file?.includes(file || '')) {
263
- varNode = node;
264
- break;
265
- }
266
- }
267
-
268
- if (!varNode) {
269
- for await (const node of db.queryNodes({ type: 'CONSTANT' })) {
270
- if (node.name === variableName && node.file?.includes(file || '')) {
271
- varNode = node;
272
- break;
273
- }
274
- }
275
- }
276
-
277
- if (!varNode) {
278
- return errorResult(`Variable "${variableName}" not found in ${file || 'project'}`);
279
- }
280
-
281
- const chain: unknown[] = [];
282
- const visited = new Set<string>();
283
- let current: GraphNode | null = varNode;
284
- const MAX_DEPTH = 20;
285
-
286
- while (current && chain.length < MAX_DEPTH) {
287
- if (visited.has(current.id)) {
288
- chain.push({ type: 'CYCLE_DETECTED', id: current.id });
289
- break;
290
- }
291
- visited.add(current.id);
292
-
293
- chain.push({
294
- type: current.type,
295
- name: current.name,
296
- file: current.file,
297
- line: current.line,
298
- });
299
-
300
- const edges = await db.getOutgoingEdges(current.id, ['ASSIGNED_FROM']);
301
- if (edges.length === 0) break;
302
-
303
- current = await db.getNode(edges[0].dst);
304
- }
305
-
306
- return textResult(
307
- `Alias chain for "${variableName}" (${chain.length} steps):\n\n${JSON.stringify(
308
- serializeBigInt(chain),
309
- null,
310
- 2
311
- )}`
312
- );
313
- }
314
-
315
- export async function handleTraceDataFlow(args: TraceDataFlowArgs): Promise<ToolResult> {
316
- const db = await ensureAnalyzed();
317
- const { source, direction = 'forward', max_depth = 10 } = args;
318
-
319
- // Find source node
320
- let sourceNode: GraphNode | null = null;
321
-
322
- // Try to find by ID first
323
- sourceNode = await db.getNode(source);
324
-
325
- // If not found, search by name
326
- if (!sourceNode) {
327
- for await (const node of db.queryNodes({ name: source })) {
328
- sourceNode = node;
329
- break;
330
- }
331
- }
332
-
333
- if (!sourceNode) {
334
- return errorResult(`Source "${source}" not found`);
335
- }
336
-
337
- const visited = new Set<string>();
338
- const paths: unknown[] = [];
339
-
340
- async function trace(nodeId: string, depth: number, path: string[]): Promise<void> {
341
- if (depth > max_depth || visited.has(nodeId)) return;
342
- visited.add(nodeId);
343
-
344
- const newPath = [...path, nodeId];
345
-
346
- if (direction === 'forward' || direction === 'both') {
347
- const outEdges = await db.getOutgoingEdges(nodeId, [
348
- 'ASSIGNED_FROM',
349
- 'DERIVES_FROM',
350
- 'PASSES_ARGUMENT',
351
- ]);
352
- for (const edge of outEdges) {
353
- await trace(edge.dst, depth + 1, newPath);
354
- }
355
- }
356
-
357
- if (direction === 'backward' || direction === 'both') {
358
- const inEdges = await db.getIncomingEdges(nodeId, [
359
- 'ASSIGNED_FROM',
360
- 'DERIVES_FROM',
361
- 'PASSES_ARGUMENT',
362
- ]);
363
- for (const edge of inEdges) {
364
- await trace(edge.src, depth + 1, newPath);
365
- }
366
- }
367
-
368
- if (depth > 0) {
369
- paths.push(newPath);
370
- }
371
- }
372
-
373
- await trace(sourceNode.id, 0, []);
374
-
375
- return textResult(
376
- `Data flow from "${source}" (${paths.length} paths):\n\n${JSON.stringify(paths, null, 2)}`
377
- );
378
- }
379
-
380
- export async function handleCheckInvariant(args: CheckInvariantArgs): Promise<ToolResult> {
381
- const db = await ensureAnalyzed();
382
- const { rule, name: description } = args;
383
-
384
- if (!('checkGuarantee' in db)) {
385
- return errorResult('Backend does not support Datalog queries');
386
- }
387
-
388
- try {
389
- const checkFn = (db as unknown as { checkGuarantee: (q: string) => Promise<Array<{ bindings: Array<{ name: string; value: string }> }>> }).checkGuarantee;
390
- const violations = await checkFn(rule);
391
- const total = violations.length;
392
-
393
- if (total === 0) {
394
- return textResult(`✅ Invariant holds: ${description || 'No violations found'}`);
395
- }
396
-
397
- const enrichedViolations: unknown[] = [];
398
- for (const v of violations.slice(0, 20)) {
399
- const nodeId = v.bindings?.find((b: any) => b.name === 'X')?.value;
400
- if (nodeId) {
401
- const node = await db.getNode(nodeId);
402
- if (node) {
403
- enrichedViolations.push({
404
- id: nodeId,
405
- type: node.type,
406
- name: node.name,
407
- file: node.file,
408
- line: node.line,
409
- });
410
- }
411
- }
412
- }
413
-
414
- return textResult(
415
- `❌ ${total} violation(s) found:\n\n${JSON.stringify(
416
- serializeBigInt(enrichedViolations),
417
- null,
418
- 2
419
- )}${total > 20 ? `\n\n... and ${total - 20} more` : ''}`
420
- );
421
- } catch (error) {
422
- return errorResult((error as Error).message);
423
- }
424
- }
425
-
426
- // === ANALYSIS HANDLERS ===
427
-
428
- export async function handleAnalyzeProject(args: AnalyzeProjectArgs): Promise<ToolResult> {
429
- const { service, force } = args;
430
-
431
- // Early check: return error for force=true if analysis is already running
432
- // This provides immediate feedback instead of waiting or causing corruption
433
- if (force && isAnalysisRunning()) {
434
- return errorResult(
435
- 'Cannot force re-analysis: analysis is already in progress. ' +
436
- 'Use get_analysis_status to check current status, or wait for completion.'
437
- );
438
- }
439
-
440
- // Note: setIsAnalyzed(false) is now handled inside ensureAnalyzed() within the lock
441
- // to prevent race conditions where multiple calls could both clear the database
442
-
443
- try {
444
- await ensureAnalyzed(service || null, force || false);
445
- const status = getAnalysisStatus();
446
-
447
- return textResult(
448
- `Analysis complete!\n` +
449
- `- Services discovered: ${status.servicesDiscovered}\n` +
450
- `- Services analyzed: ${status.servicesAnalyzed}\n` +
451
- `- Total time: ${status.timings.total || 'N/A'}s`
452
- );
453
- } catch (error) {
454
- return errorResult((error as Error).message);
455
- }
456
- }
457
-
458
- export async function handleGetAnalysisStatus(): Promise<ToolResult> {
459
- const status = getAnalysisStatus();
460
-
461
- return textResult(
462
- `Analysis Status:\n` +
463
- `- Running: ${status.running}\n` +
464
- `- Phase: ${status.phase || 'N/A'}\n` +
465
- `- Message: ${status.message || 'N/A'}\n` +
466
- `- Services discovered: ${status.servicesDiscovered}\n` +
467
- `- Services analyzed: ${status.servicesAnalyzed}\n` +
468
- (status.error ? `- Error: ${status.error}\n` : '')
469
- );
470
- }
471
-
472
- export async function handleGetStats(): Promise<ToolResult> {
473
- const db = await getOrCreateBackend();
474
-
475
- const nodeCount = await db.nodeCount();
476
- const edgeCount = await db.edgeCount();
477
- const nodesByType = await db.countNodesByType();
478
- const edgesByType = await db.countEdgesByType();
479
-
480
- return textResult(
481
- `Graph Statistics:\n\n` +
482
- `Total nodes: ${nodeCount.toLocaleString()}\n` +
483
- `Total edges: ${edgeCount.toLocaleString()}\n\n` +
484
- `Nodes by type:\n${JSON.stringify(nodesByType, null, 2)}\n\n` +
485
- `Edges by type:\n${JSON.stringify(edgesByType, null, 2)}`
486
- );
487
- }
488
-
489
- export async function handleGetSchema(args: GetSchemaArgs): Promise<ToolResult> {
490
- const db = await getOrCreateBackend();
491
- const { type = 'all' } = args;
492
-
493
- const nodesByType = await db.countNodesByType();
494
- const edgesByType = await db.countEdgesByType();
495
-
496
- let output = '';
497
-
498
- if (type === 'nodes' || type === 'all') {
499
- output += `Node Types (${Object.keys(nodesByType).length}):\n`;
500
- for (const [t, count] of Object.entries(nodesByType)) {
501
- output += ` - ${t}: ${count}\n`;
502
- }
503
- }
504
-
505
- if (type === 'edges' || type === 'all') {
506
- output += `\nEdge Types (${Object.keys(edgesByType).length}):\n`;
507
- for (const [t, count] of Object.entries(edgesByType)) {
508
- output += ` - ${t}: ${count}\n`;
509
- }
510
- }
511
-
512
- return textResult(output);
513
- }
514
-
515
- // === GUARANTEE HANDLERS ===
516
-
517
- /**
518
- * Create a new guarantee (Datalog-based or contract-based)
519
- */
520
- export async function handleCreateGuarantee(args: CreateGuaranteeArgs): Promise<ToolResult> {
521
- await getOrCreateBackend(); // Ensure managers are initialized
522
-
523
- const { name, rule, type, priority, status, owner, schema, condition, description, governs, severity } = args;
524
-
525
- try {
526
- // Determine if this is a contract-based guarantee
527
- if (type && isGuaranteeType(type)) {
528
- // Contract-based guarantee
529
- const api = getGuaranteeAPI();
530
- if (!api) {
531
- return errorResult('GuaranteeAPI not initialized');
532
- }
533
-
534
- const guarantee = await api.createGuarantee({
535
- type,
536
- name,
537
- priority,
538
- status,
539
- owner,
540
- schema,
541
- condition,
542
- description,
543
- governs,
544
- });
545
-
546
- return textResult(
547
- `✅ Created contract-based guarantee: ${guarantee.id}\n` +
548
- `Type: ${guarantee.type}\n` +
549
- `Priority: ${guarantee.priority}\n` +
550
- `Status: ${guarantee.status}` +
551
- (guarantee.description ? `\nDescription: ${guarantee.description}` : '')
552
- );
553
- } else {
554
- // Datalog-based guarantee
555
- if (!rule) {
556
- return errorResult('Datalog-based guarantee requires "rule" field');
557
- }
558
-
559
- const manager = getGuaranteeManager();
560
- if (!manager) {
561
- return errorResult('GuaranteeManager not initialized');
562
- }
563
-
564
- const guarantee = await manager.create({
565
- id: name,
566
- name,
567
- rule,
568
- severity: severity || 'warning',
569
- governs: governs || ['**/*.js'],
570
- });
571
-
572
- return textResult(
573
- `✅ Created Datalog-based guarantee: ${guarantee.id}\n` +
574
- `Rule: ${guarantee.rule}\n` +
575
- `Severity: ${guarantee.severity}`
576
- );
577
- }
578
- } catch (error) {
579
- return errorResult(`Failed to create guarantee: ${(error as Error).message}`);
580
- }
581
- }
582
-
583
- /**
584
- * List all guarantees (both Datalog-based and contract-based)
585
- */
586
- export async function handleListGuarantees(): Promise<ToolResult> {
587
- await getOrCreateBackend(); // Ensure managers are initialized
588
-
589
- const results: string[] = [];
590
-
591
- try {
592
- // List Datalog-based guarantees
593
- const manager = getGuaranteeManager();
594
- if (manager) {
595
- const datalogGuarantees = await manager.list();
596
- if (datalogGuarantees.length > 0) {
597
- results.push('## Datalog-based Guarantees\n');
598
- for (const g of datalogGuarantees) {
599
- results.push(`- **${g.id}** (${g.severity})`);
600
- results.push(` Rule: ${g.rule.substring(0, 80)}${g.rule.length > 80 ? '...' : ''}`);
601
- }
602
- }
603
- }
604
-
605
- // List contract-based guarantees
606
- const api = getGuaranteeAPI();
607
- if (api) {
608
- const contractGuarantees = await api.findGuarantees();
609
- if (contractGuarantees.length > 0) {
610
- if (results.length > 0) results.push('\n');
611
- results.push('## Contract-based Guarantees\n');
612
- for (const g of contractGuarantees) {
613
- results.push(`- **${g.id}** [${g.priority}] (${g.status})`);
614
- if (g.description) results.push(` ${g.description}`);
615
- }
616
- }
617
- }
618
-
619
- if (results.length === 0) {
620
- return textResult('No guarantees defined yet.');
621
- }
622
-
623
- return textResult(results.join('\n'));
624
- } catch (error) {
625
- return errorResult(`Failed to list guarantees: ${(error as Error).message}`);
626
- }
627
- }
628
-
629
- /**
630
- * Check guarantees (both Datalog-based and contract-based)
631
- */
632
- export async function handleCheckGuarantees(args: CheckGuaranteesArgs): Promise<ToolResult> {
633
- await getOrCreateBackend(); // Ensure managers are initialized
634
-
635
- const { names } = args;
636
- const results: string[] = [];
637
- let totalPassed = 0;
638
- let totalFailed = 0;
639
-
640
- try {
641
- const manager = getGuaranteeManager();
642
- const api = getGuaranteeAPI();
643
-
644
- if (names && names.length > 0) {
645
- // Check specific guarantees
646
- for (const name of names) {
647
- // Try Datalog-based first
648
- if (manager) {
649
- try {
650
- const result = await manager.check(name);
651
- if (result.passed) {
652
- totalPassed++;
653
- results.push(`✅ ${result.guaranteeId}: PASSED`);
654
- } else {
655
- totalFailed++;
656
- results.push(`❌ ${result.guaranteeId}: FAILED (${result.violationCount} violations)`);
657
- for (const v of result.violations.slice(0, 5)) {
658
- results.push(` - ${v.file}:${v.line} (${v.type})`);
659
- }
660
- if (result.violationCount > 5) {
661
- results.push(` ... and ${result.violationCount - 5} more`);
662
- }
663
- }
664
- continue;
665
- } catch {
666
- // Not a Datalog guarantee, try contract-based
667
- }
668
- }
669
-
670
- // Try contract-based
671
- if (api) {
672
- try {
673
- const result = await api.checkGuarantee(name);
674
- if (result.passed) {
675
- totalPassed++;
676
- results.push(`✅ ${result.id}: PASSED`);
677
- } else {
678
- totalFailed++;
679
- results.push(`❌ ${result.id}: FAILED`);
680
- for (const err of result.errors.slice(0, 5)) {
681
- results.push(` - ${err}`);
682
- }
683
- }
684
- } catch {
685
- results.push(`⚠️ ${name}: Not found`);
686
- }
687
- }
688
- }
689
- } else {
690
- // Check all guarantees
691
- if (manager) {
692
- const datalogResult = await manager.checkAll();
693
- totalPassed += datalogResult.passed;
694
- totalFailed += datalogResult.failed;
695
-
696
- if (datalogResult.total > 0) {
697
- results.push('## Datalog Guarantees\n');
698
- for (const r of datalogResult.results) {
699
- if (r.passed) {
700
- results.push(`✅ ${r.guaranteeId}: PASSED`);
701
- } else {
702
- results.push(`❌ ${r.guaranteeId}: FAILED (${r.violationCount} violations)`);
703
- }
704
- }
705
- }
706
- }
707
-
708
- if (api) {
709
- const contractResult = await api.checkAllGuarantees();
710
- totalPassed += contractResult.passed;
711
- totalFailed += contractResult.failed;
712
-
713
- if (contractResult.total > 0) {
714
- if (results.length > 0) results.push('\n');
715
- results.push('## Contract Guarantees\n');
716
- for (const r of contractResult.results) {
717
- if (r.passed) {
718
- results.push(`✅ ${r.id}: PASSED`);
719
- } else {
720
- results.push(`❌ ${r.id}: FAILED`);
721
- }
722
- }
723
- }
724
- }
725
- }
726
-
727
- if (results.length === 0) {
728
- return textResult('No guarantees to check.');
729
- }
730
-
731
- const summary = `\n---\nTotal: ${totalPassed + totalFailed} | ✅ Passed: ${totalPassed} | ❌ Failed: ${totalFailed}`;
732
- return textResult(results.join('\n') + summary);
733
- } catch (error) {
734
- return errorResult(`Failed to check guarantees: ${(error as Error).message}`);
735
- }
736
- }
737
-
738
- /**
739
- * Delete a guarantee
740
- */
741
- export async function handleDeleteGuarantee(args: DeleteGuaranteeArgs): Promise<ToolResult> {
742
- await getOrCreateBackend(); // Ensure managers are initialized
743
-
744
- const { name } = args;
745
-
746
- try {
747
- // Try Datalog-based first
748
- const manager = getGuaranteeManager();
749
- if (manager) {
750
- try {
751
- await manager.delete(name);
752
- return textResult(`✅ Deleted Datalog guarantee: ${name}`);
753
- } catch {
754
- // Not found in Datalog, try contract-based
755
- }
756
- }
757
-
758
- // Try contract-based
759
- const api = getGuaranteeAPI();
760
- if (api) {
761
- const deleted = await api.deleteGuarantee(name);
762
- if (deleted) {
763
- return textResult(`✅ Deleted contract guarantee: ${name}`);
764
- }
765
- }
766
-
767
- return errorResult(`Guarantee not found: ${name}`);
768
- } catch (error) {
769
- return errorResult(`Failed to delete guarantee: ${(error as Error).message}`);
770
- }
771
- }
772
-
773
- // === COVERAGE & DOCS ===
774
-
775
- export async function handleGetCoverage(args: GetCoverageArgs): Promise<ToolResult> {
776
- const db = await getOrCreateBackend();
777
- const projectPath = getProjectPath();
778
- const { path: targetPath = projectPath } = args;
779
-
780
- try {
781
- const analyzer = new CoverageAnalyzer(db, targetPath);
782
- const result = await analyzer.analyze();
783
-
784
- // Format output for AI agents
785
- let output = `Analysis Coverage for ${targetPath}\n`;
786
- output += `==============================\n\n`;
787
-
788
- output += `File breakdown:\n`;
789
- output += ` Total files: ${result.total}\n`;
790
- output += ` Analyzed: ${result.analyzed.count} (${result.percentages.analyzed}%) - in graph\n`;
791
- output += ` Unsupported: ${result.unsupported.count} (${result.percentages.unsupported}%) - no indexer available\n`;
792
- output += ` Unreachable: ${result.unreachable.count} (${result.percentages.unreachable}%) - not imported from entrypoints\n`;
793
-
794
- if (result.unsupported.count > 0) {
795
- output += `\nUnsupported files by extension:\n`;
796
- for (const [ext, files] of Object.entries(result.unsupported.byExtension)) {
797
- output += ` ${ext}: ${files.length} files\n`;
798
- }
799
- }
800
-
801
- if (result.unreachable.count > 0) {
802
- output += `\nUnreachable source files:\n`;
803
- for (const [ext, files] of Object.entries(result.unreachable.byExtension)) {
804
- output += ` ${ext}: ${files.length} files\n`;
805
- }
806
- }
807
-
808
- return textResult(output);
809
- } catch (error) {
810
- return errorResult(`Failed to calculate coverage: ${(error as Error).message}`);
811
- }
812
- }
813
-
814
- export async function handleGetDocumentation(args: GetDocumentationArgs): Promise<ToolResult> {
815
- const { topic = 'overview' } = args;
816
-
817
- const docs: Record<string, string> = {
818
- overview: `
819
- # Grafema Code Analysis
820
-
821
- Grafema is a static code analyzer that builds a graph of your codebase.
822
-
823
- ## Key Tools
824
- - query_graph: Execute Datalog queries
825
- - find_calls: Find function/method calls
826
- - trace_alias: Trace variable aliases
827
- - check_invariant: Verify code invariants
828
-
829
- ## Quick Start
830
- 1. Use get_stats to see graph size
831
- 2. Use find_nodes to explore the codebase
832
- 3. Use query_graph for complex queries
833
- `,
834
- queries: `
835
- # Datalog Queries
836
-
837
- ## Syntax
838
- violation(X) :- node(X, "TYPE"), attr(X, "name", "value").
839
-
840
- ## Available Predicates
841
- - node(Id, Type) - match nodes
842
- - edge(Src, Dst, Type) - match edges
843
- - attr(Id, Name, Value) - match attributes
844
- - \\+ - negation (not)
845
-
846
- ## Examples
847
- Find all functions:
848
- violation(X) :- node(X, "FUNCTION").
849
-
850
- Find unresolved calls:
851
- violation(X) :- node(X, "CALL"), \\+ edge(X, _, "CALLS").
852
- `,
853
- types: `
854
- # Node & Edge Types
855
-
856
- ## Core Node Types
857
- - MODULE, FUNCTION, CLASS, METHOD, VARIABLE
858
- - CALL, IMPORT, EXPORT, PARAMETER
859
-
860
- ## HTTP/Network
861
- - http:route, http:request, db:query
862
-
863
- ## Edge Types
864
- - CONTAINS, CALLS, DEPENDS_ON
865
- - ASSIGNED_FROM, INSTANCE_OF, PASSES_ARGUMENT
866
- `,
867
- guarantees: `
868
- # Code Guarantees
869
-
870
- Guarantees are persistent code invariants.
871
-
872
- ## Create
873
- Use create_guarantee with a name and Datalog rule.
874
-
875
- ## Check
876
- Use check_guarantees to verify all guarantees.
877
-
878
- ## Example
879
- Name: no-eval
880
- Rule: violation(X) :- node(X, "CALL"), attr(X, "name", "eval").
881
- `,
882
- };
883
-
884
- const content = docs[topic] || docs.overview;
885
- return textResult(content.trim());
886
- }
887
-
888
- // === FIND GUARDS (REG-274) ===
889
-
890
- /**
891
- * Find conditional guards protecting a node.
892
- *
893
- * Walks up the containment tree via CONTAINS edges, collecting
894
- * SCOPE nodes that have conditional=true (if_statement, else_statement, etc.).
895
- *
896
- * Returns guards in inner-to-outer order.
897
- */
898
- export async function handleFindGuards(args: FindGuardsArgs): Promise<ToolResult> {
899
- const db = await getOrCreateBackend();
900
- const { nodeId } = args;
901
-
902
- // Verify target node exists
903
- const targetNode = await db.getNode(nodeId);
904
- if (!targetNode) {
905
- return errorResult(`Node not found: ${nodeId}`);
906
- }
907
-
908
- const guards: GuardInfo[] = [];
909
- const visited = new Set<string>();
910
- let currentId = nodeId;
911
-
912
- // Walk up the containment tree
913
- while (true) {
914
- if (visited.has(currentId)) break;
915
- visited.add(currentId);
916
-
917
- // Get parent via incoming CONTAINS edge
918
- const incomingEdges = await db.getIncomingEdges(currentId, ['CONTAINS']);
919
- if (incomingEdges.length === 0) break;
920
-
921
- const parentId = incomingEdges[0].src;
922
- const parentNode = await db.getNode(parentId);
923
-
924
- if (!parentNode) break;
925
-
926
- // Check if this is a conditional scope
927
- if (parentNode.conditional) {
928
- // Parse constraints if stored as string
929
- let constraints = parentNode.constraints;
930
- if (typeof constraints === 'string') {
931
- try {
932
- constraints = JSON.parse(constraints);
933
- } catch {
934
- // Keep as string if not valid JSON
935
- }
936
- }
937
-
938
- guards.push({
939
- scopeId: parentNode.id,
940
- scopeType: (parentNode.scopeType as string) || 'unknown',
941
- condition: parentNode.condition as string | undefined,
942
- constraints: constraints as unknown[] | undefined,
943
- file: parentNode.file || '',
944
- line: (parentNode.line as number) || 0,
945
- });
946
- }
947
-
948
- currentId = parentId;
949
- }
950
-
951
- if (guards.length === 0) {
952
- return textResult(
953
- `No guards found for node: ${nodeId}\n` +
954
- `The node is not protected by any conditional scope (if/else/switch/etc.).`
955
- );
956
- }
957
-
958
- const summary = guards.map((g, i) => {
959
- const indent = ' '.repeat(i);
960
- return `${indent}${i + 1}. ${g.scopeType} at ${g.file}:${g.line}` +
961
- (g.condition ? `\n${indent} condition: ${g.condition}` : '');
962
- }).join('\n');
963
-
964
- return textResult(
965
- `Found ${guards.length} guard(s) for node: ${nodeId}\n` +
966
- `(inner to outer order)\n\n` +
967
- summary +
968
- `\n\n` +
969
- JSON.stringify(serializeBigInt(guards), null, 2)
970
- );
971
- }
972
-
973
- // === GET FUNCTION DETAILS (REG-254) ===
974
-
975
- /**
976
- * Get comprehensive function details including calls made and callers.
977
- *
978
- * Graph structure:
979
- * ```
980
- * FUNCTION -[HAS_SCOPE]-> SCOPE -[CONTAINS]-> CALL/METHOD_CALL
981
- * SCOPE -[CONTAINS]-> SCOPE (nested blocks)
982
- * CALL -[CALLS]-> FUNCTION (target)
983
- * ```
984
- *
985
- * This is the core tool for understanding function behavior.
986
- * Use transitive=true to follow call chains (A -> B -> C).
987
- */
988
- export async function handleGetFunctionDetails(
989
- args: GetFunctionDetailsArgs
990
- ): Promise<ToolResult> {
991
- const db = await ensureAnalyzed();
992
- const { name, file, transitive = false } = args;
993
-
994
- // Step 1: Find the function
995
- const candidates: GraphNode[] = [];
996
- for await (const node of db.queryNodes({ type: 'FUNCTION' })) {
997
- if (node.name !== name) continue;
998
- if (file && !node.file?.includes(file)) continue;
999
- candidates.push(node);
1000
- }
1001
-
1002
- if (candidates.length === 0) {
1003
- return errorResult(
1004
- `Function "${name}" not found.` +
1005
- (file ? ` (searched in files matching "${file}")` : '')
1006
- );
1007
- }
1008
-
1009
- if (candidates.length > 1 && !file) {
1010
- const locations = candidates.map(f => `${f.file}:${f.line}`).join(', ');
1011
- return errorResult(
1012
- `Multiple functions named "${name}" found: ${locations}. ` +
1013
- `Use the "file" parameter to disambiguate.`
1014
- );
1015
- }
1016
-
1017
- const targetFunction = candidates[0];
1018
-
1019
- // Step 2: Find calls using shared utility
1020
- const calls = await findCallsInFunction(db, targetFunction.id, {
1021
- transitive,
1022
- transitiveDepth: 5,
1023
- });
1024
-
1025
- // Step 3: Find callers
1026
- const calledBy: CallerInfo[] = [];
1027
- const incomingCalls = await db.getIncomingEdges(targetFunction.id, ['CALLS']);
1028
- const seenCallers = new Set<string>();
1029
-
1030
- for (const edge of incomingCalls) {
1031
- const caller = await findContainingFunction(db, edge.src);
1032
- if (caller && !seenCallers.has(caller.id)) {
1033
- seenCallers.add(caller.id);
1034
- calledBy.push(caller);
1035
- }
1036
- }
1037
-
1038
- // Step 4: Build result
1039
- const result = {
1040
- id: targetFunction.id,
1041
- name: targetFunction.name,
1042
- file: targetFunction.file,
1043
- line: targetFunction.line as number | undefined,
1044
- async: targetFunction.async as boolean | undefined,
1045
- calls,
1046
- calledBy,
1047
- };
1048
-
1049
- // Format output
1050
- const summary = [
1051
- `Function: ${result.name}`,
1052
- `File: ${result.file || 'unknown'}:${result.line || '?'}`,
1053
- `Async: ${result.async || false}`,
1054
- `Transitive: ${transitive}`,
1055
- '',
1056
- `Calls (${calls.length}):`,
1057
- ...formatCallsForDisplay(calls),
1058
- '',
1059
- `Called by (${calledBy.length}):`,
1060
- ...calledBy.map(c => ` - ${c.name} (${c.file}:${c.line})`),
1061
- ].join('\n');
1062
-
1063
- return textResult(
1064
- summary + '\n\n' +
1065
- JSON.stringify(serializeBigInt(result), null, 2)
1066
- );
1067
- }
1068
-
1069
- /**
1070
- * Format calls for display, grouped by depth if transitive
1071
- */
1072
- function formatCallsForDisplay(calls: CallInfo[]): string[] {
1073
- const directCalls = calls.filter(c => (c.depth || 0) === 0);
1074
- const transitiveCalls = calls.filter(c => (c.depth || 0) > 0);
1075
-
1076
- const lines: string[] = [];
1077
-
1078
- // Direct calls
1079
- for (const c of directCalls) {
1080
- const target = c.resolved
1081
- ? ` -> ${c.target?.name} (${c.target?.file}:${c.target?.line})`
1082
- : ' (unresolved)';
1083
- const prefix = c.type === 'METHOD_CALL' ? `${c.object}.` : '';
1084
- lines.push(` - ${prefix}${c.name}()${target}`);
1085
- }
1086
-
1087
- // Transitive calls (grouped by depth)
1088
- if (transitiveCalls.length > 0) {
1089
- lines.push('');
1090
- lines.push(' Transitive calls:');
1091
-
1092
- const byDepth = new Map<number, CallInfo[]>();
1093
- for (const c of transitiveCalls) {
1094
- const depth = c.depth || 1;
1095
- if (!byDepth.has(depth)) byDepth.set(depth, []);
1096
- byDepth.get(depth)!.push(c);
1097
- }
1098
-
1099
- for (const [depth, depthCalls] of Array.from(byDepth.entries()).sort((a, b) => a[0] - b[0])) {
1100
- for (const c of depthCalls) {
1101
- const indent = ' '.repeat(depth + 1);
1102
- const prefix = c.type === 'METHOD_CALL' ? `${c.object}.` : '';
1103
- const target = c.resolved ? ` -> ${c.target?.name}` : '';
1104
- lines.push(`${indent}[depth=${depth}] ${prefix}${c.name}()${target}`);
1105
- }
1106
- }
1107
- }
1108
-
1109
- return lines;
1110
- }
1111
-
1112
- // === BUG REPORTING ===
1113
-
1114
- export async function handleReportIssue(args: import('./types.js').ReportIssueArgs): Promise<ToolResult> {
1115
- const { title, description, context, labels = ['bug'] } = args;
1116
- // Use user's token if provided, otherwise fall back to project's issue-only token
1117
- const GRAFEMA_ISSUE_TOKEN = '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';
1118
- const githubToken = process.env.GITHUB_TOKEN || GRAFEMA_ISSUE_TOKEN;
1119
- const repo = 'Disentinel/grafema';
1120
-
1121
- // Build issue body
1122
- const body = `## Description
1123
- ${description}
1124
-
1125
- ${context ? `## Context\n\`\`\`\n${context}\n\`\`\`\n` : ''}
1126
- ## Environment
1127
- - Grafema version: 0.1.0-alpha.1
1128
- - Reported via: MCP tool
1129
-
1130
- ---
1131
- *This issue was automatically created via Grafema MCP server.*`;
1132
-
1133
- // Try GitHub API if token is available
1134
- if (githubToken) {
1135
- try {
1136
- const response = await fetch(`https://api.github.com/repos/${repo}/issues`, {
1137
- method: 'POST',
1138
- headers: {
1139
- 'Authorization': `token ${githubToken}`,
1140
- 'Content-Type': 'application/json',
1141
- 'Accept': 'application/vnd.github.v3+json',
1142
- },
1143
- body: JSON.stringify({
1144
- title,
1145
- body,
1146
- labels: labels.filter(l => ['bug', 'enhancement', 'documentation', 'question'].includes(l)),
1147
- }),
1148
- });
1149
-
1150
- if (response.ok) {
1151
- const issue = await response.json() as { html_url: string; number: number };
1152
- return textResult(
1153
- `✅ Issue created successfully!\n\n` +
1154
- `**Issue #${issue.number}**: ${issue.html_url}\n\n` +
1155
- `Thank you for reporting this issue.`
1156
- );
1157
- } else {
1158
- const error = await response.text();
1159
- throw new Error(`GitHub API error: ${response.status} - ${error}`);
1160
- }
1161
- } catch (error) {
1162
- // Fall through to manual template if API fails
1163
- console.error('[report_issue] GitHub API failed:', error);
1164
- }
1165
- }
1166
-
1167
- // Fallback: return template for manual submission
1168
- const issueUrl = `https://github.com/${repo}/issues/new`;
1169
- const encodedTitle = encodeURIComponent(title);
1170
- const encodedBody = encodeURIComponent(body);
1171
- const encodedLabels = encodeURIComponent(labels.join(','));
1172
- const directUrl = `${issueUrl}?title=${encodedTitle}&body=${encodedBody}&labels=${encodedLabels}`;
1173
-
1174
- return textResult(
1175
- `⚠️ Failed to create issue automatically. Please create it manually:\n\n` +
1176
- `**Quick link** (may truncate long descriptions):\n${directUrl}\n\n` +
1177
- `**Or copy this template to** ${issueUrl}:\n\n` +
1178
- `---\n**Title:** ${title}\n\n${body}\n---`
1179
- );
1180
- }