@aryam/fixmap 0.9.0 → 0.9.2

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 (69) hide show
  1. package/README.md +109 -9
  2. package/dist/agent-setup.d.ts +6 -97
  3. package/dist/agent-setup.js +20 -6
  4. package/dist/agent-setup.js.map +1 -1
  5. package/dist/analysis-source.d.ts +1 -0
  6. package/dist/analysis-source.js +6 -2
  7. package/dist/analysis-source.js.map +1 -1
  8. package/dist/annotation-command.d.ts +8 -0
  9. package/dist/annotation-command.js +187 -0
  10. package/dist/annotation-command.js.map +1 -0
  11. package/dist/annotation-tool.d.ts +62 -0
  12. package/dist/annotation-tool.js +64 -0
  13. package/dist/annotation-tool.js.map +1 -0
  14. package/dist/ask-command.d.ts +9 -0
  15. package/dist/ask-command.js +127 -0
  16. package/dist/ask-command.js.map +1 -0
  17. package/dist/capability-command.d.ts +11 -0
  18. package/dist/capability-command.js +540 -0
  19. package/dist/capability-command.js.map +1 -0
  20. package/dist/change-scope-command.d.ts +7 -0
  21. package/dist/change-scope-command.js +162 -0
  22. package/dist/change-scope-command.js.map +1 -0
  23. package/dist/cli-runner.d.ts +2 -1
  24. package/dist/cli-runner.js +165 -47
  25. package/dist/cli-runner.js.map +1 -1
  26. package/dist/cli.js +26 -1
  27. package/dist/cli.js.map +1 -1
  28. package/dist/decode-input.d.ts +4 -0
  29. package/dist/decode-input.js +44 -0
  30. package/dist/decode-input.js.map +1 -0
  31. package/dist/doctor.d.ts +1 -0
  32. package/dist/doctor.js +14 -1
  33. package/dist/doctor.js.map +1 -1
  34. package/dist/editor-command.d.ts +8 -0
  35. package/dist/editor-command.js +46 -0
  36. package/dist/editor-command.js.map +1 -0
  37. package/dist/history-command.d.ts +14 -0
  38. package/dist/history-command.js +145 -0
  39. package/dist/history-command.js.map +1 -0
  40. package/dist/mcp.d.ts +20 -0
  41. package/dist/mcp.js +599 -11
  42. package/dist/mcp.js.map +1 -1
  43. package/dist/migration-command.d.ts +15 -0
  44. package/dist/migration-command.js +142 -0
  45. package/dist/migration-command.js.map +1 -0
  46. package/dist/repository-source.d.ts +1 -0
  47. package/dist/repository-source.js +7 -3
  48. package/dist/repository-source.js.map +1 -1
  49. package/dist/reverse-docs-command.d.ts +16 -0
  50. package/dist/reverse-docs-command.js +114 -0
  51. package/dist/reverse-docs-command.js.map +1 -0
  52. package/dist/runtime-command.d.ts +15 -0
  53. package/dist/runtime-command.js +121 -0
  54. package/dist/runtime-command.js.map +1 -0
  55. package/dist/sandbox-command.d.ts +9 -0
  56. package/dist/sandbox-command.js +158 -0
  57. package/dist/sandbox-command.js.map +1 -0
  58. package/dist/supply-chain-command.d.ts +20 -0
  59. package/dist/supply-chain-command.js +131 -0
  60. package/dist/supply-chain-command.js.map +1 -0
  61. package/dist/watch-command.js +7 -5
  62. package/dist/watch-command.js.map +1 -1
  63. package/dist/watch.d.ts +1 -0
  64. package/dist/watch.js +46 -2
  65. package/dist/watch.js.map +1 -1
  66. package/dist/workspace-command.d.ts +13 -0
  67. package/dist/workspace-command.js +267 -0
  68. package/dist/workspace-command.js.map +1 -0
  69. package/package.json +4 -4
package/dist/mcp.js CHANGED
@@ -1,13 +1,24 @@
1
1
  import { readFileSync } from "node:fs";
2
+ import { ANNOTATION_TOOL, runAnnotationTool } from "./annotation-tool.js";
2
3
  import { dirname, join, resolve } from "node:path";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
- import { compareReports, buildFixMapGraph, explainFile, renderComparisonMarkdown, renderExplanationMarkdown, renderAgentReport, renderContextPackMarkdown, renderFixMapGraphMermaid, renderJsonReport, renderMarkdownReport, renderVerifyMarkdown, resolveExclusions, scanRepo, stripByteOrderMark, validateFixMapReport, verifyPlan } from "@aryam/fixmap-core";
7
+ import { CallToolRequestSchema, ListToolsRequestSchema, isInitializedNotification, isJSONRPCRequest } from "@modelcontextprotocol/sdk/types.js";
8
+ import { answerFixMapQuestion, buildMigrationPlan, draftReverseDocumentation, mapRuntimeEvidence, compareReports, compareArchitectureRefs, buildFixMapGraph, explainFile, renderComparisonMarkdown, renderExplanationMarkdown, renderAgentReport, renderContextPackMarkdown, renderFixMapGraphMermaid, renderJsonReport, renderMarkdownReport, renderVerifyMarkdown, resolveExclusions, scanRepo, validateFixMapReport, verifyPlan } from "@aryam/fixmap-core";
8
9
  import { renderDoctorReport, runDoctorChecks } from "./doctor.js";
10
+ import { describeInputReadError, readDecodedTextFile } from "./decode-input.js";
9
11
  import { clarifyMissingPath } from "./explain-path.js";
10
12
  import { analyzeRepository, contextFromAnalysis } from "./analysis-source.js";
13
+ import { renderAskMarkdown } from "./ask-command.js";
14
+ import { parseMigrationInput, renderMigrationPlanMarkdown } from "./migration-command.js";
15
+ import { parseReverseDocsInput, renderReverseDocsMarkdown } from "./reverse-docs-command.js";
16
+ import { renderHistoryMarkdown } from "./history-command.js";
17
+ import { buildSupplyChainReport, renderSupplyChainMarkdown } from "./supply-chain-command.js";
18
+ import { parseRuntimeInput, renderRuntimeMarkdown } from "./runtime-command.js";
19
+ import { runWorkspaceCommand } from "./workspace-command.js";
20
+ import { runChangeScopeCommand } from "./change-scope-command.js";
21
+ import { runCapabilitiesCommand, runCapabilityCommand } from "./capability-command.js";
11
22
  import { buildReportForRepository, isSafeGitRefName, tryParseGitHubIssueSource } from "./repository-source.js";
12
23
  export const MAX_MCP_LIMIT = 20;
13
24
  const PLAN_TOOL = {
@@ -61,7 +72,11 @@ const PLAN_TOOL = {
61
72
  },
62
73
  workingTree: { type: "boolean", description: "Map staged and unstaged tracked changes against HEAD" },
63
74
  includeUntracked: { type: "boolean", description: "With workingTree, include untracked files" },
64
- noCache: { type: "boolean", description: "Bypass the exact-state repository scan cache" }
75
+ noCache: { type: "boolean", description: "Bypass the exact-state repository scan cache" },
76
+ semanticModel: {
77
+ type: "string",
78
+ description: "Existing local Transformers.js embedding model directory. Never downloads a model or uploads source."
79
+ }
65
80
  },
66
81
  additionalProperties: false
67
82
  }
@@ -134,6 +149,179 @@ const GRAPH_TOOL = {
134
149
  additionalProperties: false
135
150
  }
136
151
  };
152
+ const WORKSPACE_TOOL = {
153
+ name: "fixmap_workspace",
154
+ title: "FixMap workspace",
155
+ description: "Preview (may change before v0.10.0): Build a versioned package and impact graph across 1-32 local repository checkouts from a reviewed JSON config. " +
156
+ "Resolves Node, Python, and Maven package versions plus manifest/import/submodule evidence without executing repository code. " +
157
+ "Use seeds to trace provider-to-consumer impact.",
158
+ inputSchema: {
159
+ type: "object",
160
+ properties: {
161
+ config: { type: "string", description: "Local workspace JSON config path; repository paths inside it are relative to this file" },
162
+ seeds: {
163
+ type: "array",
164
+ items: { type: "string" },
165
+ description: "Repository IDs whose downstream consumers should be traced"
166
+ },
167
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" },
168
+ noCache: { type: "boolean", description: "Bypass the exact-state scan cache in every workspace repository" }
169
+ },
170
+ required: ["config"],
171
+ additionalProperties: false
172
+ }
173
+ };
174
+ const CHANGE_SCOPE_TOOL = {
175
+ name: "fixmap_change_scope",
176
+ title: "FixMap change scope",
177
+ description: "Preview (may change before v0.10.0): Expand explicit planned files/directories over bounded import and dependent evidence, then join tests, contracts, ADRs, owners, and architecture policy. " +
178
+ "The caller supplies every starting anchor; FixMap does not interpret product requirements, call an API or LLM, or require an account.",
179
+ inputSchema: {
180
+ type: "object",
181
+ properties: {
182
+ touch: { type: "array", items: { type: "string" }, description: "Existing file or directory anchors" },
183
+ add: { type: "array", items: { type: "string" }, description: "Planned path anchors; missing paths stay unresolved" },
184
+ direction: { type: "string", enum: ["dependencies", "dependents", "both"], description: "Structural traversal direction (default both)" },
185
+ depth: { type: "integer", minimum: 0, maximum: 8, description: "Maximum traversal depth (default 2)" },
186
+ maxNodes: { type: "integer", minimum: 1, maximum: 2000, description: "Maximum selected plus affected nodes (default 200)" },
187
+ workspace: { type: "string", description: "Stable workspace identity (default local)" },
188
+ repository: { type: "string", description: "Stable repository identity (default checkout name)" },
189
+ repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" },
190
+ format: { type: "string", description: "Output format: markdown (default) or json" },
191
+ noCache: { type: "boolean", description: "Bypass repository scan caches" }
192
+ },
193
+ additionalProperties: false
194
+ }
195
+ };
196
+ const CAPABILITY_TOOL = {
197
+ name: "fixmap_capability",
198
+ title: "FixMap capability",
199
+ description: "Preview (may change before v0.10.0): List human-owned product capabilities, rebuild one current capability map, or compare it across exact Git refs from .fixmap/capabilities.json. " +
200
+ "The store contains explicit names, anchors, and bounds only; no generated conclusions, API, LLM, semantic inference, or account.",
201
+ inputSchema: {
202
+ type: "object",
203
+ properties: {
204
+ id: { type: "string", description: "Capability id to show; omit to list definitions" },
205
+ from: { type: "string", description: "Earlier exact Git ref; requires id and to" },
206
+ to: { type: "string", description: "Later exact Git ref; requires id and from" },
207
+ repo: { type: "string", description: "Local checkout path (defaults to the MCP server repository)" },
208
+ format: { type: "string", description: "Output format: markdown (default) or json" },
209
+ noCache: { type: "boolean", description: "Bypass repository scan caches" }
210
+ },
211
+ additionalProperties: false
212
+ }
213
+ };
214
+ const ASK_TOOL = {
215
+ name: "fixmap_ask",
216
+ title: "FixMap ask",
217
+ description: "Preview (may change before v0.10.0): Answer structural questions from a saved FixMap report using ranked context, impact, tests, risks, diagnostics, annotations, ADRs, and architecture policy. " +
218
+ "Deterministic mode reads no source content, calls no model, cites report evidence, and preserves unknowns instead of guessing.",
219
+ inputSchema: {
220
+ type: "object",
221
+ properties: {
222
+ report: {
223
+ description: "FixMap report JSON object or local report path",
224
+ anyOf: [{ type: "object" }, { type: "string" }]
225
+ },
226
+ question: { type: "string", description: "Structural question of at most 5,000 characters" },
227
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
228
+ },
229
+ required: ["report", "question"],
230
+ additionalProperties: false
231
+ }
232
+ };
233
+ const MIGRATION_TOOL = {
234
+ name: "fixmap_migrate",
235
+ title: "FixMap migrate",
236
+ description: "Preview (may change before v0.10.0): Build dependency-ordered, review-only migration phases against one exact identity graph. " +
237
+ "Every explicit step must declare edits, compatibility, tests, and rollback; cycles, unknown identities, and unsafe parallel overlap fail closed. " +
238
+ "This tool never executes commands or applies changes.",
239
+ inputSchema: {
240
+ type: "object",
241
+ properties: {
242
+ input: {
243
+ description: "Version-1 migration input object or path to a local JSON input file",
244
+ anyOf: [{ type: "object" }, { type: "string" }]
245
+ },
246
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
247
+ },
248
+ required: ["input"],
249
+ additionalProperties: false
250
+ }
251
+ };
252
+ const REVERSE_DOCS_TOOL = {
253
+ name: "fixmap_reverse_docs",
254
+ title: "FixMap reverse docs",
255
+ description: "Preview (may change before v0.10.0): Build deterministic, review-only module or architecture documentation drafts from exact file fingerprints, structural edges, and authored decisions. " +
256
+ "Observations, inferences, and unknowns remain separate; this tool never writes or overwrites repository files.",
257
+ inputSchema: {
258
+ type: "object",
259
+ properties: {
260
+ input: {
261
+ description: "Version-1 reverse-documentation input object or path to a local JSON input file",
262
+ anyOf: [{ type: "object" }, { type: "string" }]
263
+ },
264
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
265
+ },
266
+ required: ["input"],
267
+ additionalProperties: false
268
+ }
269
+ };
270
+ const HISTORY_TOOL = {
271
+ name: "fixmap_history",
272
+ title: "FixMap history",
273
+ description: "Preview (may change before v0.10.0): Compare architecture at two exact committed Git refs without checking out either ref or changing the worktree. " +
274
+ "Returns immutable commit IDs plus added/removed edges, cycle and boundary drift, and coupling growth.",
275
+ inputSchema: {
276
+ type: "object",
277
+ properties: {
278
+ repo: { type: "string", description: "Local Git checkout path (defaults to the MCP server repository)" },
279
+ from: { type: "string", description: "Earlier committed Git ref" },
280
+ to: { type: "string", description: "Later committed Git ref" },
281
+ couplingDelta: { type: "integer", minimum: 1, maximum: 10000, description: "Minimum coupling growth to report (default 2)" },
282
+ applyPolicy: { type: "boolean", description: "Apply the repository architecture policy when present (default true)" },
283
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
284
+ },
285
+ required: ["from", "to"],
286
+ additionalProperties: false
287
+ }
288
+ };
289
+ const SUPPLY_CHAIN_TOOL = {
290
+ name: "fixmap_supply_chain",
291
+ title: "FixMap supply chain",
292
+ description: "Preview (may change before v0.10.0): Validate and render a version-1 normalized external scanner or SBOM bundle with package-aware vulnerability, outdated-version, and license-policy evidence. " +
293
+ "FixMap never fetches advisory data, maintains no vulnerability corpus, executes no scanner, and authorizes no remediation.",
294
+ inputSchema: {
295
+ type: "object",
296
+ properties: {
297
+ input: {
298
+ description: "Version-1 supply-chain bundle object or path to a local JSON file",
299
+ anyOf: [{ type: "object" }, { type: "string" }]
300
+ },
301
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
302
+ },
303
+ required: ["input"],
304
+ additionalProperties: false
305
+ }
306
+ };
307
+ const RUNTIME_TOOL = {
308
+ name: "fixmap_runtime",
309
+ title: "FixMap runtime",
310
+ description: "Preview (may change before v0.10.0): Map a redaction-reviewed OpenTelemetry, normalized APM, Speedscope, or pprof bundle only through explicit repository IDs, paths, and exact file fingerprints. " +
311
+ "Labels and symbols never establish identity; correlation never establishes causality.",
312
+ inputSchema: {
313
+ type: "object",
314
+ properties: {
315
+ input: {
316
+ description: "Version-1 runtime input object or path containing bundle and exact repository snapshots",
317
+ anyOf: [{ type: "object" }, { type: "string" }]
318
+ },
319
+ format: { type: "string", description: "Output format: markdown (default) or json, case-insensitive" }
320
+ },
321
+ required: ["input"],
322
+ additionalProperties: false
323
+ }
324
+ };
137
325
  const VERIFY_TOOL = {
138
326
  name: "fixmap_verify",
139
327
  title: "FixMap verify",
@@ -193,9 +381,11 @@ const DOCTOR_TOOL = {
193
381
  export function createFixMapMcpServer(repositorySourceDependencies = {}, defaultRepo = process.cwd()) {
194
382
  const server = new Server({ name: "fixmap", version: readVersion() }, { capabilities: { tools: {} } });
195
383
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
196
- tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL]
384
+ tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL]
197
385
  }));
198
386
  server.setRequestHandler(CallToolRequestSchema, async (request) => {
387
+ if (request.params.name === ANNOTATION_TOOL.name)
388
+ return runAnnotationTool(request.params.arguments, defaultRepo);
199
389
  if (request.params.name === CONTEXT_TOOL.name || request.params.name === GRAPH_TOOL.name) {
200
390
  const kind = request.params.name === CONTEXT_TOOL.name ? "context" : "graph";
201
391
  const parsed = parseAnalysisToolArguments(request.params.arguments ?? {}, kind);
@@ -214,7 +404,8 @@ export function createFixMapMcpServer(repositorySourceDependencies = {}, default
214
404
  includeUntracked: args.includeUntracked,
215
405
  useCache: !args.noCache,
216
406
  limit: args.limit,
217
- exclude: args.exclude
407
+ exclude: args.exclude,
408
+ semanticModelPath: args.semanticModel
218
409
  }, repositorySourceDependencies);
219
410
  if (kind === "context") {
220
411
  const pack = contextFromAnalysis(analysis, args.budget ?? 10_000);
@@ -229,6 +420,324 @@ export function createFixMapMcpServer(repositorySourceDependencies = {}, default
229
420
  return { isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] };
230
421
  }
231
422
  }
423
+ if (request.params.name === CHANGE_SCOPE_TOOL.name) {
424
+ const record = request.params.arguments;
425
+ const unknown = Object.keys(record ?? {}).filter((key) => !["touch", "add", "direction", "depth", "maxNodes", "workspace", "repository", "repo", "format", "noCache"].includes(key));
426
+ if (unknown.length > 0)
427
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] };
428
+ const touch = validateStringList(record?.touch, "touch");
429
+ if (!touch.success)
430
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${touch.message}` }] };
431
+ const add = validateStringList(record?.add, "add");
432
+ if (!add.success)
433
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${add.message}` }] };
434
+ if (touch.values.length + add.values.length === 0)
435
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: provide at least one "touch" or "add" path.' }] };
436
+ if (touch.values.length + add.values.length > 64)
437
+ return { isError: true, content: [{ type: "text", text: "Invalid arguments: change scope supports at most 64 total anchors." }] };
438
+ for (const key of ["workspace", "repository", "repo"]) {
439
+ if (record?.[key] !== undefined && (typeof record[key] !== "string" || !record[key].trim())) {
440
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: "${key}" must be a non-empty string.` }] };
441
+ }
442
+ }
443
+ if (record?.repo && /^https?:\/\//i.test(String(record.repo)))
444
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "repo" must be a local checkout.' }] };
445
+ if (record?.direction !== undefined && !["dependencies", "dependents", "both"].includes(String(record.direction)))
446
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "direction" must be dependencies, dependents, or both.' }] };
447
+ if (record?.depth !== undefined && (!Number.isSafeInteger(record.depth) || Number(record.depth) < 0 || Number(record.depth) > 8))
448
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "depth" must be an integer from 0 to 8.' }] };
449
+ if (record?.maxNodes !== undefined && (!Number.isSafeInteger(record.maxNodes) || Number(record.maxNodes) < 1 || Number(record.maxNodes) > 2_000))
450
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "maxNodes" must be an integer from 1 to 2000.' }] };
451
+ if (record?.noCache !== undefined && typeof record.noCache !== "boolean")
452
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "noCache" must be a boolean.' }] };
453
+ const format = normalizeFormat(record?.format);
454
+ if (!format.success)
455
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
456
+ const stdout = [];
457
+ const stderr = [];
458
+ const commandArgs = [];
459
+ for (const path of touch.values)
460
+ commandArgs.push("--touch", path);
461
+ for (const path of add.values)
462
+ commandArgs.push("--add", path);
463
+ commandArgs.push("--repo", typeof record?.repo === "string" ? record.repo.trim() : defaultRepo, "--format", format.value ?? "markdown");
464
+ if (typeof record?.direction === "string")
465
+ commandArgs.push("--direction", record.direction);
466
+ if (record?.depth !== undefined)
467
+ commandArgs.push("--depth", String(record.depth));
468
+ if (record?.maxNodes !== undefined)
469
+ commandArgs.push("--max-nodes", String(record.maxNodes));
470
+ if (typeof record?.workspace === "string")
471
+ commandArgs.push("--workspace", record.workspace.trim());
472
+ if (typeof record?.repository === "string")
473
+ commandArgs.push("--repository", record.repository.trim());
474
+ if (record?.noCache === true)
475
+ commandArgs.push("--no-cache");
476
+ const exitCode = await runChangeScopeCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) });
477
+ return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] };
478
+ }
479
+ if (request.params.name === CAPABILITY_TOOL.name) {
480
+ const record = request.params.arguments;
481
+ const unknown = Object.keys(record ?? {}).filter((key) => !["id", "from", "to", "repo", "format", "noCache"].includes(key));
482
+ if (unknown.length > 0)
483
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] };
484
+ for (const key of ["id", "from", "to", "repo"])
485
+ if (record?.[key] !== undefined && (typeof record[key] !== "string" || !record[key].trim()))
486
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: "${key}" must be a non-empty string.` }] };
487
+ if (record?.repo && /^https?:\/\//i.test(String(record.repo)))
488
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "repo" must be a local checkout.' }] };
489
+ if (record?.noCache !== undefined && typeof record.noCache !== "boolean")
490
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "noCache" must be a boolean.' }] };
491
+ const refCount = Number(record?.from !== undefined) + Number(record?.to !== undefined);
492
+ if (refCount === 1)
493
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "from" and "to" must be provided together.' }] };
494
+ if (refCount === 2 && typeof record?.id !== "string")
495
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: capability history requires "id".' }] };
496
+ if (refCount === 2 && record?.noCache === true)
497
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "noCache" does not apply to immutable Git-ref capability history.' }] };
498
+ const format = normalizeFormat(record?.format);
499
+ if (!format.success)
500
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
501
+ const stdout = [];
502
+ const stderr = [];
503
+ const commandArgs = ["--repo", typeof record?.repo === "string" ? record.repo.trim() : defaultRepo, "--format", format.value ?? "markdown"];
504
+ if (record?.noCache === true)
505
+ commandArgs.push("--no-cache");
506
+ const exitCode = refCount === 2
507
+ ? await runCapabilityCommand([
508
+ "diff", String(record.id).trim(), "--from", String(record.from).trim(), "--to", String(record.to).trim(), ...commandArgs
509
+ ], { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) })
510
+ : typeof record?.id === "string"
511
+ ? await runCapabilityCommand([record.id.trim(), ...commandArgs], { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) })
512
+ : await runCapabilitiesCommand(commandArgs, { stdout: (value) => stdout.push(value), stderr: (value) => stderr.push(value) });
513
+ return { ...(exitCode === 0 ? {} : { isError: true }), content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }] };
514
+ }
515
+ if (request.params.name === WORKSPACE_TOOL.name) {
516
+ const record = request.params.arguments;
517
+ const unknown = Object.keys(record ?? {}).filter((key) => !["config", "seeds", "format", "noCache"].includes(key));
518
+ if (unknown.length > 0) {
519
+ return {
520
+ isError: true,
521
+ content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }]
522
+ };
523
+ }
524
+ if (typeof record?.config !== "string" || !record.config.trim()) {
525
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "config" is required and must be a non-empty local path.' }] };
526
+ }
527
+ if (record.seeds !== undefined && (!Array.isArray(record.seeds) || record.seeds.length > 32 ||
528
+ record.seeds.some((seed) => typeof seed !== "string" || !seed.trim()))) {
529
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "seeds" must be an array of at most 32 non-empty repository IDs.' }] };
530
+ }
531
+ if (record.noCache !== undefined && typeof record.noCache !== "boolean") {
532
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "noCache" must be a boolean.' }] };
533
+ }
534
+ const format = normalizeFormat(record.format);
535
+ if (!format.success)
536
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
537
+ const stdout = [];
538
+ const stderr = [];
539
+ const commandArgs = ["--config", record.config.trim(), "--format", format.value ?? "markdown"];
540
+ for (const seed of record.seeds ?? [])
541
+ commandArgs.push("--seed", seed.trim());
542
+ if (record.noCache === true)
543
+ commandArgs.push("--no-cache");
544
+ const exitCode = await runWorkspaceCommand(commandArgs, {
545
+ stdout: (text) => stdout.push(text),
546
+ stderr: (text) => stderr.push(text)
547
+ });
548
+ return {
549
+ ...(exitCode === 0 ? {} : { isError: true }),
550
+ content: [{ type: "text", text: exitCode === 0 ? stdout.join("") : stderr.join("") }]
551
+ };
552
+ }
553
+ if (request.params.name === ASK_TOOL.name) {
554
+ const record = request.params.arguments;
555
+ const unknown = Object.keys(record ?? {}).filter((key) => !["report", "question", "format"].includes(key));
556
+ if (unknown.length > 0) {
557
+ return {
558
+ isError: true,
559
+ content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }]
560
+ };
561
+ }
562
+ const loaded = loadReportInput(record?.report, '"report"');
563
+ if (!loaded.success)
564
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${loaded.message}` }] };
565
+ if (typeof record?.question !== "string" || !record.question.trim() || record.question.length > 5_000 || record.question.includes("\0")) {
566
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "question" is required and must contain at most 5,000 characters and no null bytes.' }] };
567
+ }
568
+ const format = normalizeFormat(record.format);
569
+ if (!format.success)
570
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
571
+ try {
572
+ const answer = await answerFixMapQuestion(loaded.report, record.question);
573
+ return {
574
+ content: [{
575
+ type: "text",
576
+ text: format.value === "json" ? `${JSON.stringify(answer, null, 2)}\n` : renderAskMarkdown(answer)
577
+ }]
578
+ };
579
+ }
580
+ catch (error) {
581
+ return { isError: true, content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }] };
582
+ }
583
+ }
584
+ if (request.params.name === MIGRATION_TOOL.name) {
585
+ const record = request.params.arguments;
586
+ const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key));
587
+ if (unknown.length > 0) {
588
+ return {
589
+ isError: true,
590
+ content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }]
591
+ };
592
+ }
593
+ if (record?.input === undefined) {
594
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "input" is required and must be a migration object or local JSON path.' }] };
595
+ }
596
+ const format = normalizeFormat(record.format);
597
+ if (!format.success)
598
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
599
+ try {
600
+ const raw = typeof record.input === "string"
601
+ ? JSON.parse(readDecodedTextFile(record.input))
602
+ : record.input;
603
+ const input = parseMigrationInput(raw);
604
+ const plan = buildMigrationPlan(input.graph, input.steps);
605
+ return {
606
+ content: [{
607
+ type: "text",
608
+ text: format.value === "json" ? `${JSON.stringify(plan, null, 2)}\n` : renderMigrationPlanMarkdown(plan)
609
+ }]
610
+ };
611
+ }
612
+ catch (error) {
613
+ const message = typeof record.input === "string"
614
+ ? describeInputReadError(record.input, error)
615
+ : error instanceof Error ? error.message : String(error);
616
+ return { isError: true, content: [{ type: "text", text: message }] };
617
+ }
618
+ }
619
+ if (request.params.name === REVERSE_DOCS_TOOL.name) {
620
+ const record = request.params.arguments;
621
+ const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key));
622
+ if (unknown.length > 0) {
623
+ return {
624
+ isError: true,
625
+ content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }]
626
+ };
627
+ }
628
+ if (record?.input === undefined) {
629
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "input" is required and must be a reverse-documentation object or local JSON path.' }] };
630
+ }
631
+ const format = normalizeFormat(record.format);
632
+ if (!format.success)
633
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
634
+ try {
635
+ const raw = typeof record.input === "string"
636
+ ? JSON.parse(readDecodedTextFile(record.input))
637
+ : record.input;
638
+ const input = parseReverseDocsInput(raw);
639
+ const drafts = draftReverseDocumentation(input.repo, input.architecture, input.decisions, input.targets);
640
+ return {
641
+ content: [{
642
+ type: "text",
643
+ text: format.value === "json" ? `${JSON.stringify(drafts, null, 2)}\n` : renderReverseDocsMarkdown(drafts)
644
+ }]
645
+ };
646
+ }
647
+ catch (error) {
648
+ const message = typeof record.input === "string"
649
+ ? describeInputReadError(record.input, error)
650
+ : error instanceof Error ? error.message : String(error);
651
+ return { isError: true, content: [{ type: "text", text: message }] };
652
+ }
653
+ }
654
+ if (request.params.name === HISTORY_TOOL.name) {
655
+ const record = request.params.arguments;
656
+ const unknown = Object.keys(record ?? {}).filter((key) => !["repo", "from", "to", "couplingDelta", "applyPolicy", "format"].includes(key));
657
+ if (unknown.length > 0) {
658
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] };
659
+ }
660
+ if (typeof record?.from !== "string" || !record.from.trim() || /[\0\r\n]/.test(record.from) || record.from.length > 500 ||
661
+ typeof record.to !== "string" || !record.to.trim() || /[\0\r\n]/.test(record.to) || record.to.length > 500) {
662
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "from" and "to" are required bounded single-line Git refs.' }] };
663
+ }
664
+ if (record.repo !== undefined && (typeof record.repo !== "string" || !record.repo.trim() || record.repo.includes("\0"))) {
665
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "repo" must be a non-empty local path.' }] };
666
+ }
667
+ if (record.couplingDelta !== undefined && (!Number.isSafeInteger(record.couplingDelta) || Number(record.couplingDelta) < 1 || Number(record.couplingDelta) > 10_000)) {
668
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "couplingDelta" must be an integer from 1 to 10000.' }] };
669
+ }
670
+ if (record.applyPolicy !== undefined && typeof record.applyPolicy !== "boolean") {
671
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "applyPolicy" must be a boolean.' }] };
672
+ }
673
+ const format = normalizeFormat(record.format);
674
+ if (!format.success)
675
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
676
+ const repoRoot = resolve(typeof record.repo === "string" ? record.repo.trim() : defaultRepo ?? process.cwd());
677
+ try {
678
+ const result = await compareArchitectureRefs({
679
+ repoRoot,
680
+ fromRef: record.from.trim(),
681
+ toRef: record.to.trim(),
682
+ couplingDelta: record.couplingDelta === undefined ? 2 : Number(record.couplingDelta),
683
+ applyRepositoryPolicy: record.applyPolicy === undefined ? true : record.applyPolicy
684
+ });
685
+ return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(result, null, 2)}\n` : renderHistoryMarkdown(result) }] };
686
+ }
687
+ catch (error) {
688
+ const message = error instanceof Error ? error.message : String(error);
689
+ return { isError: true, content: [{ type: "text", text: message.includes("Could not resolve Git ref")
690
+ ? `Could not resolve one of the requested Git refs in "${repoRoot}". Confirm both refs exist and the path is a Git checkout.`
691
+ : `Could not compare historical architecture in "${repoRoot}".` }] };
692
+ }
693
+ }
694
+ if (request.params.name === SUPPLY_CHAIN_TOOL.name) {
695
+ const record = request.params.arguments;
696
+ const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key));
697
+ if (unknown.length > 0) {
698
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] };
699
+ }
700
+ if (record?.input === undefined) {
701
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "input" is required and must be a supply-chain object or local JSON path.' }] };
702
+ }
703
+ const format = normalizeFormat(record.format);
704
+ if (!format.success)
705
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
706
+ try {
707
+ const raw = typeof record.input === "string" ? JSON.parse(readDecodedTextFile(record.input)) : record.input;
708
+ const report = await buildSupplyChainReport(raw);
709
+ return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(report, null, 2)}\n` : renderSupplyChainMarkdown(report) }] };
710
+ }
711
+ catch (error) {
712
+ const message = typeof record.input === "string"
713
+ ? describeInputReadError(record.input, error)
714
+ : error instanceof Error ? error.message : String(error);
715
+ return { isError: true, content: [{ type: "text", text: message }] };
716
+ }
717
+ }
718
+ if (request.params.name === RUNTIME_TOOL.name) {
719
+ const record = request.params.arguments;
720
+ const unknown = Object.keys(record ?? {}).filter((key) => !["input", "format"].includes(key));
721
+ if (unknown.length > 0)
722
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` }] };
723
+ if (record?.input === undefined)
724
+ return { isError: true, content: [{ type: "text", text: 'Invalid arguments: "input" is required and must be a runtime object or local JSON path.' }] };
725
+ const format = normalizeFormat(record.format);
726
+ if (!format.success)
727
+ return { isError: true, content: [{ type: "text", text: `Invalid arguments: ${format.message}` }] };
728
+ try {
729
+ const raw = typeof record.input === "string" ? JSON.parse(readDecodedTextFile(record.input)) : record.input;
730
+ const input = parseRuntimeInput(raw);
731
+ const mapped = mapRuntimeEvidence(input.bundle, input.snapshots);
732
+ return { content: [{ type: "text", text: format.value === "json" ? `${JSON.stringify(mapped, null, 2)}\n` : renderRuntimeMarkdown(mapped) }] };
733
+ }
734
+ catch (error) {
735
+ const message = typeof record.input === "string"
736
+ ? describeInputReadError(record.input, error)
737
+ : error instanceof Error ? error.message : String(error);
738
+ return { isError: true, content: [{ type: "text", text: message }] };
739
+ }
740
+ }
232
741
  if (request.params.name === COMPARE_TOOL.name) {
233
742
  const record = request.params.arguments;
234
743
  const unknown = Object.keys(record ?? {}).filter((key) => !["previous", "current", "format"].includes(key));
@@ -390,7 +899,8 @@ export function createFixMapMcpServer(repositorySourceDependencies = {}, default
390
899
  includeUntracked: args.includeUntracked,
391
900
  useCache: !args.noCache,
392
901
  limit: args.limit,
393
- exclude: args.exclude
902
+ exclude: args.exclude,
903
+ semanticModelPath: args.semanticModel
394
904
  }, repositorySourceDependencies);
395
905
  }
396
906
  catch (error) {
@@ -428,7 +938,7 @@ export function parsePlanArguments(input) {
428
938
  return { success: false, message: "tool arguments must be an object." };
429
939
  }
430
940
  const record = input;
431
- const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache"]);
941
+ const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel"]);
432
942
  const unknown = Object.keys(record).filter((key) => !allowed.has(key));
433
943
  if (unknown.length > 0) {
434
944
  return {
@@ -442,6 +952,9 @@ export function parsePlanArguments(input) {
442
952
  return { success: false, message: `"${name}" must be a string.` };
443
953
  }
444
954
  }
955
+ if (record.semanticModel !== undefined && (typeof record.semanticModel !== "string" || !record.semanticModel.trim())) {
956
+ return { success: false, message: '"semanticModel" must be a non-empty local directory path.' };
957
+ }
445
958
  for (const name of ["issue", "diff", "base", "head", "repo", "ref"]) {
446
959
  if (typeof record[name] === "string" && !record[name].trim())
447
960
  return { success: false, message: `"${name}" must not be blank.` };
@@ -489,6 +1002,8 @@ export function parsePlanArguments(input) {
489
1002
  value.includeUntracked = true;
490
1003
  if (record.noCache === true)
491
1004
  value.noCache = true;
1005
+ if (typeof record.semanticModel === "string")
1006
+ value.semanticModel = record.semanticModel.trim();
492
1007
  if (value.ref && !/^https?:\/\//i.test(value.repo ?? "") && !tryParseGitHubIssueSource(value.issue ?? "")) {
493
1008
  return { success: false, message: '"ref" requires a remote GitHub "repo" or issue URL.' };
494
1009
  }
@@ -504,7 +1019,7 @@ function parseAnalysisToolArguments(input, kind) {
504
1019
  return { success: false, message: "tool arguments must be an object." };
505
1020
  }
506
1021
  const record = input;
507
- const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", ...(kind === "context" ? ["budget"] : [])]);
1022
+ const allowed = new Set(["issue", "diff", "base", "head", "repo", "ref", "format", "limit", "exclude", "workingTree", "includeUntracked", "noCache", "semanticModel", ...(kind === "context" ? ["budget"] : [])]);
508
1023
  const unknown = Object.keys(record).filter((key) => !allowed.has(key));
509
1024
  if (unknown.length > 0)
510
1025
  return { success: false, message: `unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` };
@@ -632,6 +1147,9 @@ export function parseVerifyArguments(input) {
632
1147
  if (unknown.length > 0) {
633
1148
  return { success: false, message: `unknown argument${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}.` };
634
1149
  }
1150
+ if (record.report === undefined) {
1151
+ return { success: false, message: '"report" is required and must be a FixMap report object or a path to a FixMap JSON report.' };
1152
+ }
635
1153
  const loaded = loadReportInput(record.report, '"report"');
636
1154
  if (!loaded.success) {
637
1155
  return { success: false, message: loaded.message };
@@ -686,6 +1204,15 @@ function normalizePlanFormat(candidate) {
686
1204
  ? { success: true, value }
687
1205
  : { success: false, message: '"format" must be "markdown", "json", or "agent".' };
688
1206
  }
1207
+ function validateStringList(candidate, label) {
1208
+ if (candidate === undefined)
1209
+ return { success: true, values: [] };
1210
+ if (!Array.isArray(candidate) || candidate.length > 64 ||
1211
+ candidate.some((entry) => typeof entry !== "string" || !entry.trim() || entry.length > 1_000 || entry.includes("\0"))) {
1212
+ return { success: false, message: `"${label}" must be an array of at most 64 bounded non-empty paths.` };
1213
+ }
1214
+ return { success: true, values: candidate.map((entry) => String(entry).trim()) };
1215
+ }
689
1216
  function normalizeFormat(candidate) {
690
1217
  if (candidate === undefined)
691
1218
  return { success: true, value: undefined };
@@ -710,12 +1237,12 @@ function loadReportInput(input, label) {
710
1237
  }
711
1238
  let contents;
712
1239
  try {
713
- contents = stripByteOrderMark(readFileSync(path, "utf8"));
1240
+ contents = readDecodedTextFile(path);
714
1241
  }
715
1242
  catch (error) {
716
1243
  return {
717
1244
  success: false,
718
- message: `${label} looked like a file path but could not be read: ${error instanceof Error ? error.message : String(error)}.`
1245
+ message: `${label} looked like a file path but could not be read: ${describeInputReadError(path, error)}`
719
1246
  };
720
1247
  }
721
1248
  let parsed;
@@ -737,7 +1264,68 @@ function asFixMapReport(candidate, label) {
737
1264
  return validateFixMapReport(candidate, label);
738
1265
  }
739
1266
  export async function runMcpServer(defaultRepo = process.cwd()) {
740
- await createFixMapMcpServer({}, defaultRepo).connect(new StdioServerTransport());
1267
+ await createFixMapMcpServer({}, defaultRepo).connect(new InitializationGuardTransport(new StdioServerTransport()));
1268
+ }
1269
+ /**
1270
+ * The SDK handles capability negotiation but currently dispatches requests received before
1271
+ * `notifications/initialized`. Keep the protocol boundary honest here, and turn malformed
1272
+ * JSON lines into JSON-RPC parse errors instead of leaving a stdio client waiting forever.
1273
+ */
1274
+ export class InitializationGuardTransport {
1275
+ inner;
1276
+ onclose;
1277
+ onerror;
1278
+ onmessage;
1279
+ initializeRequested = false;
1280
+ initialized = false;
1281
+ constructor(inner) {
1282
+ this.inner = inner;
1283
+ }
1284
+ async start() {
1285
+ this.inner.onclose = () => this.onclose?.();
1286
+ this.inner.onerror = (error) => {
1287
+ if (error instanceof SyntaxError) {
1288
+ void this.inner.send({
1289
+ jsonrpc: "2.0",
1290
+ id: null,
1291
+ error: { code: -32700, message: "Parse error" }
1292
+ }).catch((sendError) => this.onerror?.(toError(sendError)));
1293
+ return;
1294
+ }
1295
+ this.onerror?.(error);
1296
+ };
1297
+ this.inner.onmessage = (message, extra) => {
1298
+ if (isInitializedNotification(message)) {
1299
+ if (!this.initializeRequested)
1300
+ return;
1301
+ this.initialized = true;
1302
+ this.onmessage?.(message, extra);
1303
+ return;
1304
+ }
1305
+ if (isJSONRPCRequest(message) && message.method === "initialize") {
1306
+ this.initializeRequested = true;
1307
+ }
1308
+ if (isJSONRPCRequest(message) && message.method !== "initialize" && message.method !== "ping" && !this.initialized) {
1309
+ void this.inner.send({
1310
+ jsonrpc: "2.0",
1311
+ id: message.id,
1312
+ error: { code: -32002, message: "Server not initialized" }
1313
+ }).catch((sendError) => this.onerror?.(toError(sendError)));
1314
+ return;
1315
+ }
1316
+ this.onmessage?.(message, extra);
1317
+ };
1318
+ await this.inner.start();
1319
+ }
1320
+ send(message) {
1321
+ return this.inner.send(message);
1322
+ }
1323
+ close() {
1324
+ return this.inner.close();
1325
+ }
1326
+ }
1327
+ function toError(candidate) {
1328
+ return candidate instanceof Error ? candidate : new Error(String(candidate));
741
1329
  }
742
1330
  function readVersion() {
743
1331
  const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));