@neat.is/mcp 0.2.9 → 0.3.0
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.
- package/dist/index.cjs +98 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +98 -15
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -73,12 +73,12 @@ async function readNodeResource(client2, id, project) {
|
|
|
73
73
|
const uri = nodeUri(id);
|
|
74
74
|
const prefix = corePrefix(project);
|
|
75
75
|
try {
|
|
76
|
-
const [
|
|
76
|
+
const [nodeBody, edges] = await Promise.all([
|
|
77
77
|
client2.get(`${prefix}/graph/node/${encodeURIComponent(id)}`),
|
|
78
78
|
client2.get(`${prefix}/graph/edges/${encodeURIComponent(id)}`)
|
|
79
79
|
]);
|
|
80
80
|
const body = {
|
|
81
|
-
node:
|
|
81
|
+
node: nodeBody.node,
|
|
82
82
|
// Outbound only — the issue spec says "attrs + outbound edges". Inbound
|
|
83
83
|
// edges are still reachable via the other endpoint and would double the
|
|
84
84
|
// payload for hub nodes (e.g. a shared database).
|
|
@@ -109,9 +109,10 @@ async function readNodeResource(client2, id, project) {
|
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
111
|
async function readPolicyViolationsResource(client2, limit = POLICY_VIOLATIONS_DEFAULT_LIMIT, project) {
|
|
112
|
-
const
|
|
112
|
+
const body = await client2.get(
|
|
113
113
|
`${corePrefix(project)}/policies/violations`
|
|
114
114
|
);
|
|
115
|
+
const violations = body.violations;
|
|
115
116
|
const ordered = [...violations].reverse().slice(0, limit);
|
|
116
117
|
return {
|
|
117
118
|
contents: [
|
|
@@ -128,7 +129,10 @@ async function readPolicyViolationsResource(client2, limit = POLICY_VIOLATIONS_D
|
|
|
128
129
|
};
|
|
129
130
|
}
|
|
130
131
|
async function readRecentIncidentsResource(client2, limit = INCIDENTS_DEFAULT_LIMIT, project) {
|
|
131
|
-
const
|
|
132
|
+
const body = await client2.get(
|
|
133
|
+
`${corePrefix(project)}/incidents`
|
|
134
|
+
);
|
|
135
|
+
const events = body.events;
|
|
132
136
|
const ordered = [...events].reverse().slice(0, limit);
|
|
133
137
|
return {
|
|
134
138
|
contents: [
|
|
@@ -197,9 +201,12 @@ function registerResources(server2, client2, options = {}) {
|
|
|
197
201
|
const tick = async () => {
|
|
198
202
|
if (stopped) return;
|
|
199
203
|
try {
|
|
200
|
-
const
|
|
204
|
+
const incidents = await client2.get(
|
|
205
|
+
`${corePrefix(project)}/incidents`
|
|
206
|
+
);
|
|
207
|
+
const events = incidents.events;
|
|
201
208
|
const next = {
|
|
202
|
-
total:
|
|
209
|
+
total: incidents.total,
|
|
203
210
|
lastId: events.length > 0 ? events[events.length - 1].id : void 0
|
|
204
211
|
};
|
|
205
212
|
if (incidentsChanged(lastIncidents, next)) {
|
|
@@ -210,9 +217,10 @@ function registerResources(server2, client2, options = {}) {
|
|
|
210
217
|
} catch {
|
|
211
218
|
}
|
|
212
219
|
try {
|
|
213
|
-
const
|
|
220
|
+
const polBody = await client2.get(
|
|
214
221
|
`${corePrefix(project)}/policies/violations`
|
|
215
222
|
);
|
|
223
|
+
const violations = polBody.violations;
|
|
216
224
|
const next = {
|
|
217
225
|
total: violations.length,
|
|
218
226
|
lastId: violations.length > 0 ? violations[violations.length - 1].id : void 0
|
|
@@ -240,6 +248,9 @@ function registerResources(server2, client2, options = {}) {
|
|
|
240
248
|
};
|
|
241
249
|
}
|
|
242
250
|
|
|
251
|
+
// src/index.ts
|
|
252
|
+
var import_types3 = require("@neat.is/types");
|
|
253
|
+
|
|
243
254
|
// src/tools.ts
|
|
244
255
|
var import_types = require("@neat.is/types");
|
|
245
256
|
|
|
@@ -287,7 +298,7 @@ async function getRootCause(client2, input) {
|
|
|
287
298
|
const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : "";
|
|
288
299
|
const path = projectPath(
|
|
289
300
|
input.project,
|
|
290
|
-
`/
|
|
301
|
+
`/graph/root-cause/${encodeURIComponent(input.errorNode)}${qs}`
|
|
291
302
|
);
|
|
292
303
|
return withMissingNodeFallback(async () => {
|
|
293
304
|
const result = await client2.get(path);
|
|
@@ -313,7 +324,7 @@ async function getBlastRadius(client2, input) {
|
|
|
313
324
|
const qs = input.depth !== void 0 ? `?depth=${input.depth}` : "";
|
|
314
325
|
const path = projectPath(
|
|
315
326
|
input.project,
|
|
316
|
-
`/
|
|
327
|
+
`/graph/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`
|
|
317
328
|
);
|
|
318
329
|
return withMissingNodeFallback(async () => {
|
|
319
330
|
const result = await client2.get(path);
|
|
@@ -347,7 +358,7 @@ async function getDependencies(client2, input) {
|
|
|
347
358
|
const depth = input.depth ?? 3;
|
|
348
359
|
const path = projectPath(
|
|
349
360
|
input.project,
|
|
350
|
-
`/graph/
|
|
361
|
+
`/graph/dependencies/${encodeURIComponent(input.nodeId)}?depth=${depth}`
|
|
351
362
|
);
|
|
352
363
|
return withMissingNodeFallback(async () => {
|
|
353
364
|
const result = await client2.get(path);
|
|
@@ -426,9 +437,10 @@ function formatDuration(ms) {
|
|
|
426
437
|
}
|
|
427
438
|
async function getIncidentHistory(client2, input) {
|
|
428
439
|
return withMissingNodeFallback(async () => {
|
|
429
|
-
const
|
|
440
|
+
const body = await client2.get(
|
|
430
441
|
projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`)
|
|
431
442
|
);
|
|
443
|
+
const events = body.events;
|
|
432
444
|
if (events.length === 0) {
|
|
433
445
|
return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`);
|
|
434
446
|
}
|
|
@@ -439,7 +451,7 @@ async function getIncidentHistory(client2, input) {
|
|
|
439
451
|
blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`);
|
|
440
452
|
}
|
|
441
453
|
return formatToolResponse({
|
|
442
|
-
summary: `${input.nodeId} has ${
|
|
454
|
+
summary: `${input.nodeId} has ${body.total} recorded incident${body.total === 1 ? "" : "s"}; showing the ${ordered.length} most recent.`,
|
|
443
455
|
block: blockLines.join("\n"),
|
|
444
456
|
// ErrorEvents are observation records, not graph edges — provenance is
|
|
445
457
|
// OBSERVED by definition (the OTel span happened).
|
|
@@ -551,9 +563,10 @@ async function getRecentStaleEdges(client2, input) {
|
|
|
551
563
|
if (input.edgeType) params.set("edgeType", input.edgeType);
|
|
552
564
|
const qs = params.size > 0 ? `?${params.toString()}` : "";
|
|
553
565
|
try {
|
|
554
|
-
const
|
|
555
|
-
projectPath(input.project, `/
|
|
566
|
+
const body = await client2.get(
|
|
567
|
+
projectPath(input.project, `/stale-events${qs}`)
|
|
556
568
|
);
|
|
569
|
+
const events = body.events;
|
|
557
570
|
if (events.length === 0) {
|
|
558
571
|
return formatEmptyResponse(
|
|
559
572
|
input.edgeType ? `No stale ${input.edgeType} edges recorded.` : "No stale-edge transitions recorded yet."
|
|
@@ -592,9 +605,10 @@ async function checkPolicies(client2, input) {
|
|
|
592
605
|
qsParams.set("policyId", input.scope.policyId);
|
|
593
606
|
}
|
|
594
607
|
const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : "";
|
|
595
|
-
|
|
608
|
+
const body = await client2.get(
|
|
596
609
|
projectPath(input.project, `/policies/violations${qs}`)
|
|
597
610
|
);
|
|
611
|
+
violations = body.violations;
|
|
598
612
|
allowed = violations.every((v) => v.onViolation !== "block");
|
|
599
613
|
}
|
|
600
614
|
if (violations.length === 0) {
|
|
@@ -638,6 +652,62 @@ async function checkPolicies(client2, input) {
|
|
|
638
652
|
return formatErrorResponse(`Error talking to neat-core: ${err.message}`);
|
|
639
653
|
}
|
|
640
654
|
}
|
|
655
|
+
function buildDivergencesPath(input) {
|
|
656
|
+
const params = new URLSearchParams();
|
|
657
|
+
if (input.type && input.type.length > 0) params.set("type", input.type.join(","));
|
|
658
|
+
if (input.minConfidence !== void 0) {
|
|
659
|
+
params.set("minConfidence", String(input.minConfidence));
|
|
660
|
+
}
|
|
661
|
+
if (input.node) params.set("node", input.node);
|
|
662
|
+
const qs = params.size > 0 ? `?${params.toString()}` : "";
|
|
663
|
+
return projectPath(input.project, `/graph/divergences${qs}`);
|
|
664
|
+
}
|
|
665
|
+
function formatDivergenceLine(d) {
|
|
666
|
+
switch (d.type) {
|
|
667
|
+
case "missing-observed":
|
|
668
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} (${d.edgeType}) \u2014 confidence ${d.confidence.toFixed(2)}`;
|
|
669
|
+
case "missing-extracted":
|
|
670
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} (${d.edgeType}) \u2014 confidence ${d.confidence.toFixed(2)}`;
|
|
671
|
+
case "version-mismatch":
|
|
672
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 declared ${d.extractedVersion}, observed engine ${d.observedVersion} (${d.compatibility})`;
|
|
673
|
+
case "host-mismatch":
|
|
674
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 declared host ${d.extractedHost}, observed host ${d.observedHost}`;
|
|
675
|
+
case "compat-violation":
|
|
676
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 ${d.rule.kind}${d.rule.package ? ` (${d.rule.package})` : ""}`;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
async function getDivergences(client2, input) {
|
|
680
|
+
try {
|
|
681
|
+
const result = await client2.get(buildDivergencesPath(input));
|
|
682
|
+
if (result.totalAffected === 0) {
|
|
683
|
+
return formatEmptyResponse(
|
|
684
|
+
"No divergences found between the declared (EXTRACTED) and observed (OBSERVED) views of the graph."
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
const headline = result.divergences[0];
|
|
688
|
+
const summary = `Found ${result.totalAffected} divergence${result.totalAffected === 1 ? "" : "s"} between code and production. Highest-confidence: ${headline.type} on ${headline.source} \u2192 ${headline.target}. ${headline.reason}`;
|
|
689
|
+
const blockLines = [];
|
|
690
|
+
for (const d of result.divergences) {
|
|
691
|
+
blockLines.push(formatDivergenceLine(d));
|
|
692
|
+
blockLines.push(` reason: ${d.reason}`);
|
|
693
|
+
blockLines.push(` recommendation: ${d.recommendation}`);
|
|
694
|
+
}
|
|
695
|
+
const maxConfidence = result.divergences.reduce(
|
|
696
|
+
(m, d) => Math.max(m, d.confidence),
|
|
697
|
+
0
|
|
698
|
+
);
|
|
699
|
+
return formatToolResponse({
|
|
700
|
+
summary,
|
|
701
|
+
block: blockLines.join("\n"),
|
|
702
|
+
confidence: maxConfidence,
|
|
703
|
+
// Composite provenance — divergences sit between EXTRACTED and
|
|
704
|
+
// OBSERVED by construction; that's what makes them divergences.
|
|
705
|
+
provenance: "composite (EXTRACTED + OBSERVED)"
|
|
706
|
+
});
|
|
707
|
+
} catch (err) {
|
|
708
|
+
return formatErrorResponse(`Error talking to neat-core: ${err.message}`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
641
711
|
async function postJson(client2, path, body) {
|
|
642
712
|
const c = client2;
|
|
643
713
|
if (typeof c.post !== "function") {
|
|
@@ -737,6 +807,19 @@ server.tool(
|
|
|
737
807
|
},
|
|
738
808
|
async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) })
|
|
739
809
|
);
|
|
810
|
+
server.tool(
|
|
811
|
+
"get_divergences",
|
|
812
|
+
"Returns places where what the code declares (EXTRACTED) doesn't match what production observed (OBSERVED). The single most NEAT-shaped query \u2014 the one that justifies the whole graph. Use when the user asks 'is anything weird?' or 'what does production do that the code doesn't?' or 'find me a bug' on an unfamiliar codebase. Returns divergences ranked by confidence \xD7 severity. Prefer this over `get_root_cause` when no specific node is failing.",
|
|
813
|
+
{
|
|
814
|
+
type: import_zod.z.array(import_types3.DivergenceTypeSchema).optional().describe(
|
|
815
|
+
"Filter by divergence type. One or more of: missing-observed, missing-extracted, version-mismatch, host-mismatch, compat-violation. Omit for all."
|
|
816
|
+
),
|
|
817
|
+
minConfidence: import_zod.z.number().min(0).max(1).optional().describe("Drop divergences below this confidence threshold (0.0 - 1.0)."),
|
|
818
|
+
node: import_zod.z.string().optional().describe("Scope to divergences involving this node id (as source or target)."),
|
|
819
|
+
project: projectField
|
|
820
|
+
},
|
|
821
|
+
async (input) => getDivergences(client, { ...input, project: projectFor(input) })
|
|
822
|
+
);
|
|
740
823
|
server.tool(
|
|
741
824
|
"check_policies",
|
|
742
825
|
"Inspect or dry-run the project's policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).",
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/resources.ts","../src/tools.ts","../src/format.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { CheckPoliciesScopeSchema, HypotheticalActionSchema } from '@neat.is/types'\nimport { createHttpClient } from './client.js'\nimport { registerResources } from './resources.js'\nimport {\n checkPolicies,\n getBlastRadius,\n getDependencies,\n getGraphDiff,\n getIncidentHistory,\n getObservedDependencies,\n getRecentStaleEdges,\n getRootCause,\n semanticSearch,\n} from './tools.js'\n\nconst baseUrl = process.env.NEAT_CORE_URL ?? 'http://localhost:8080'\nconst client = createHttpClient(baseUrl)\n\n// `NEAT_DEFAULT_PROJECT` is the implicit project for tool calls that don't\n// pass a `project` arg. Unset means \"use the core's `default` project\" — we\n// route those calls through the legacy unprefixed URL so an older core (one\n// that predates #83) still gets the request it expects.\nconst defaultProject = process.env.NEAT_DEFAULT_PROJECT\nconst projectFor = (input: { project?: string }): string | undefined =>\n input.project ?? defaultProject\n\nconst projectField = z\n .string()\n .optional()\n .describe(\n 'Project name when the core hosts more than one (set NEAT_PROJECTS=...). Omit to use the default project.',\n )\n\nconst server = new McpServer({\n name: 'neat',\n version: '0.1.0',\n})\n\nserver.tool(\n 'get_root_cause',\n 'Trace a failing node up its dependency graph to find the underlying cause. Use this when something is breaking and you want to know which upstream component is the actual culprit.',\n {\n errorNode: z\n .string()\n .describe('Graph node id where the error surfaced, e.g. \"database:payments-db\"'),\n errorId: z\n .string()\n .optional()\n .describe('Specific error event id from incident history; if set, the result is coloured with that error message'),\n project: projectField,\n },\n async (input) => getRootCause(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_blast_radius',\n 'List every node downstream of the given node — what would break if this node failed or was redeployed.',\n {\n nodeId: z.string().describe('Graph node id to compute blast radius from'),\n depth: z\n .number()\n .int()\n .nonnegative()\n .max(20)\n .optional()\n .describe('Max BFS depth (default 10)'),\n project: projectField,\n },\n async (input) => getBlastRadius(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_dependencies',\n 'List the transitive outgoing dependencies of a node, BFS to depth N (default 3, max 10). Each result carries distance, edge type, and provenance — both static (EXTRACTED) and runtime (OBSERVED). Pass depth=1 for direct-only.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n depth: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('BFS depth (default 3, max 10). depth=1 returns direct dependencies only.'),\n project: projectField,\n },\n async (input) => getDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_observed_dependencies',\n 'List only the runtime (OBSERVED via OTel) outgoing dependencies of a node. Use this to compare what code SAYS the service depends on vs what production actually does.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n project: projectField,\n },\n async (input) => getObservedDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_incident_history',\n 'Return recent OTel error events recorded against a node, most recent first.',\n {\n nodeId: z.string().describe('Graph node id to query'),\n limit: z.number().int().positive().max(100).optional().describe('Max events to return (default 20)'),\n project: projectField,\n },\n async (input) => getIncidentHistory(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'semantic_search',\n 'Search nodes by natural-language query. Uses embedding vectors when an embedder is available (Ollama nomic-embed-text → in-process MiniLM → substring fallback) — phrase the query the way you would describe what you want.',\n {\n query: z.string().describe('Free-text query, e.g. \"service handling checkout payments\"'),\n project: projectField,\n },\n async (input) => semanticSearch(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_graph_diff',\n 'Diff a saved graph snapshot against the current live graph. Useful for change reviews and post-incidents — answers \"what changed in the architecture between then and now.\" Returns added/removed/changed nodes and edges with both snapshot timestamps.',\n {\n againstSnapshot: z\n .string()\n .describe(\n 'Path or http(s) URL of the snapshot to diff against (the \"before\" state). The current graph is the \"after\".',\n ),\n project: projectField,\n },\n async (input) => getGraphDiff(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_recent_stale_edges',\n 'List the most recent OBSERVED → STALE edge transitions. Use this to spot integrations that have gone quiet — a CALLS edge that just went stale typically means an upstream stopped calling, not that the link is healthy.',\n {\n limit: z\n .number()\n .int()\n .positive()\n .max(200)\n .optional()\n .describe('Max events to return (default 50)'),\n edgeType: z\n .string()\n .optional()\n .describe('Filter by edge type — e.g. \"CALLS\" or \"CONNECTS_TO\"'),\n project: projectField,\n },\n async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'check_policies',\n 'Inspect or dry-run the project\\'s policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).',\n {\n scope: CheckPoliciesScopeSchema.optional().describe(\n 'Narrow to a subset. Default \"all\".',\n ),\n hypotheticalAction: HypotheticalActionSchema.optional().describe(\n 'Dry-run mode: simulate the action and return resulting violations. Omit for current state.',\n ),\n project: projectField,\n },\n async (input) =>\n checkPolicies(client, {\n ...input,\n project: projectFor(input),\n } as Parameters<typeof checkPolicies>[1]),\n)\n\n// Resources sit alongside tools — same data, different access pattern. Read\n// the per-node resource for raw attrs+edges JSON; subscribe to the incidents\n// resource to be notified when new errors land. The eight tools above are\n// unchanged.\nconst incidentsPollMs = process.env.NEAT_RESOURCE_POLL_MS\n ? Number(process.env.NEAT_RESOURCE_POLL_MS)\n : undefined\nconst resourceRegistration = registerResources(server, client, {\n ...(incidentsPollMs !== undefined ? { incidentsPollMs } : {}),\n ...(defaultProject ? { project: defaultProject } : {}),\n})\n\nasync function main(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nconst stopPolling = (): void => {\n resourceRegistration.stop()\n}\nprocess.on('SIGTERM', stopPolling)\nprocess.on('SIGINT', stopPolling)\n\nmain().catch((err) => {\n console.error(err)\n process.exit(1)\n})\n","// Thin HTTP client for the neat-core REST surface. Tools call out via this\n// instead of fetch() directly so tests can swap in a stub implementation\n// without monkey-patching globals.\n\nexport interface HttpClient {\n get<T>(path: string): Promise<T>\n // POST is optional on the interface so test stubs that only need GET don't\n // have to implement it. Production createHttpClient always provides it.\n post?<T>(path: string, body: unknown): Promise<T>\n}\n\nexport function createHttpClient(baseUrl: string): HttpClient {\n const root = baseUrl.replace(/\\/$/, '')\n return {\n async get<T>(path: string): Promise<T> {\n const res = await fetch(`${root}${path}`)\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on GET ${path}: ${body}`)\n }\n return (await res.json()) as T\n },\n async post<T>(path: string, body: unknown): Promise<T> {\n const res = await fetch(`${root}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on POST ${path}: ${text}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n","// MCP Resources — additive surface alongside the eight tools. Two resources:\n//\n// neat://node/<id> — one resource per graph node. Read returns the\n// node attributes plus its outbound edges.\n// neat://incidents/recent — most recent error events. Pollable by the SDK\n// via subscribe; we send `notifications/resources/\n// updated` when /incidents grows.\n//\n// Pure read helpers are exported so tests can exercise them without spinning up\n// an MCP transport. `registerResources()` does the SDK wiring + the poll loop.\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type {\n ListResourcesResult,\n ReadResourceResult,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { ErrorEvent, GraphEdge, GraphNode, PolicyViolation } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\ninterface SerializedGraph {\n nodes: GraphNode[]\n edges: GraphEdge[]\n}\n\nconst NODE_RESOURCE_MIME = 'application/json'\nconst INCIDENTS_URI = 'neat://incidents/recent'\nconst INCIDENTS_DEFAULT_LIMIT = 50\nconst POLICY_VIOLATIONS_URI = 'neat://policies/violations'\nconst POLICY_VIOLATIONS_DEFAULT_LIMIT = 100\n\nfunction nodeUri(id: string): string {\n // Node ids contain `:` which RFC 6570 percent-encodes; doing it explicitly\n // here keeps the URI we hand the SDK identical to what `list` produces.\n return `neat://node/${encodeURIComponent(id)}`\n}\n\n// Project-aware URL prefix for the underlying core. When unset, hit the\n// legacy unprefixed routes (which the core resolves to project=`default`).\nfunction corePrefix(project: string | undefined): string {\n return project ? `/projects/${encodeURIComponent(project)}` : ''\n}\n\nfunction nameFromAttrs(attrs: GraphNode): string {\n return (attrs as { name?: string }).name ?? attrs.id\n}\n\nexport async function listNodeResources(\n client: HttpClient,\n project?: string,\n): Promise<ListResourcesResult> {\n const graph = await client.get<SerializedGraph>(`${corePrefix(project)}/graph`)\n return {\n resources: graph.nodes.map((n) => ({\n uri: nodeUri(n.id),\n name: nameFromAttrs(n),\n description: `${n.type} — ${nameFromAttrs(n)}`,\n mimeType: NODE_RESOURCE_MIME,\n })),\n }\n}\n\nexport async function readNodeResource(\n client: HttpClient,\n id: string,\n project?: string,\n): Promise<ReadResourceResult> {\n const uri = nodeUri(id)\n const prefix = corePrefix(project)\n try {\n const [attrs, edges] = await Promise.all([\n client.get<GraphNode>(`${prefix}/graph/node/${encodeURIComponent(id)}`),\n client.get<EdgesResponse>(`${prefix}/graph/edges/${encodeURIComponent(id)}`),\n ])\n const body = {\n node: attrs,\n // Outbound only — the issue spec says \"attrs + outbound edges\". Inbound\n // edges are still reachable via the other endpoint and would double the\n // payload for hub nodes (e.g. a shared database).\n outboundEdges: edges.outbound,\n }\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(body, null, 2),\n },\n ],\n }\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify({ error: 'node not found', id }),\n },\n ],\n }\n }\n throw err\n }\n}\n\nexport async function readPolicyViolationsResource(\n client: HttpClient,\n limit: number = POLICY_VIOLATIONS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const violations = await client.get<PolicyViolation[]>(\n `${corePrefix(project)}/policies/violations`,\n )\n // Latest first; cap at limit so an exploding violations log doesn't blow\n // up the resource read. The full file is still on disk for forensic use.\n const ordered = [...violations].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: POLICY_VIOLATIONS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: violations.length, violations: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\nexport async function readRecentIncidentsResource(\n client: HttpClient,\n limit: number = INCIDENTS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const events = await client.get<ErrorEvent[]>(`${corePrefix(project)}/incidents`)\n // ndjson order is append-time = oldest first. Reverse so most-recent leads.\n const ordered = [...events].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: INCIDENTS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: events.length, events: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\n// Pure helper so the poll loop can be tested without timers. Returns true when\n// the visible state of /incidents has changed in a way subscribers should hear\n// about. Compares total count + the id of the newest event — either is enough\n// on its own, but the pair makes deletes (if they ever happen) survive a\n// missed update.\nexport function incidentsChanged(\n prev: { total: number; lastId?: string } | null,\n next: { total: number; lastId?: string },\n): boolean {\n if (!prev) return false // first observation seeds, doesn't notify\n if (prev.total !== next.total) return true\n if (prev.lastId !== next.lastId) return true\n return false\n}\n\nexport interface RegisterResourcesOptions {\n // Poll interval for /incidents in ms. 5s by default; 0 disables polling.\n incidentsPollMs?: number\n // Project this MCP instance reports against. Unset → core's `default`\n // project via the legacy unprefixed URLs.\n project?: string\n}\n\nexport interface ResourceRegistration {\n // Stops the poll loop. The SDK keeps the registered resources around as\n // long as the server is alive — calling stop() doesn't unregister them.\n stop: () => void\n}\n\nexport function registerResources(\n server: McpServer,\n client: HttpClient,\n options: RegisterResourcesOptions = {},\n): ResourceRegistration {\n const pollMs = options.incidentsPollMs ?? 5000\n const project = options.project\n\n // neat://node/<id> — templated. The list callback enumerates current nodes;\n // the read callback resolves a specific id.\n server.registerResource(\n 'graph-node',\n new ResourceTemplate('neat://node/{id}', {\n list: async () => listNodeResources(client, project),\n }),\n {\n description:\n 'A single graph node by id. Reading returns the node attributes plus its outbound edges as JSON.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async (_uri, variables) => {\n const raw = variables.id\n const id = Array.isArray(raw) ? raw[0] : raw\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error('neat://node/{id} requires an id')\n }\n const decoded = id.includes('%') ? decodeURIComponent(id) : id\n return readNodeResource(client, decoded, project)\n },\n )\n\n // neat://incidents/recent — static. Subscribers get notifications/resources/\n // updated on each tick where /incidents has changed.\n server.registerResource(\n 'incidents-recent',\n INCIDENTS_URI,\n {\n description:\n 'Most recent error events recorded by neat-core, newest first. JSON: { count, total, events[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readRecentIncidentsResource(client, INCIDENTS_DEFAULT_LIMIT, project),\n )\n\n // neat://policies/violations — static. Same poll-and-notify pattern as\n // incidents. Subscribers get resource-updated notifications when the\n // policy-violations.ndjson grows. ADR-045.\n server.registerResource(\n 'policies-violations',\n POLICY_VIOLATIONS_URI,\n {\n description:\n 'Current policy violations from policy-violations.ndjson, newest first. JSON: { count, total, violations[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readPolicyViolationsResource(client, POLICY_VIOLATIONS_DEFAULT_LIMIT, project),\n )\n\n let stopped = false\n let timer: NodeJS.Timeout | null = null\n let lastIncidents: { total: number; lastId?: string } | null = null\n let lastViolations: { total: number; lastId?: string } | null = null\n\n const tick = async (): Promise<void> => {\n if (stopped) return\n // Incidents poll.\n try {\n const events = await client.get<ErrorEvent[]>(`${corePrefix(project)}/incidents`)\n const next = {\n total: events.length,\n lastId: events.length > 0 ? events[events.length - 1].id : undefined,\n }\n if (incidentsChanged(lastIncidents, next)) {\n await server.server.sendResourceUpdated({ uri: INCIDENTS_URI }).catch(() => {})\n }\n lastIncidents = next\n } catch {\n // Core down — keep polling, next tick will catch up.\n }\n // Policy-violations poll. Fires the alert action's notifications/\n // resources/updated for neat://policies/violations subscribers per\n // ADR-044 §alert. Same change-detection shape as incidents.\n try {\n const violations = await client.get<PolicyViolation[]>(\n `${corePrefix(project)}/policies/violations`,\n )\n const next = {\n total: violations.length,\n lastId:\n violations.length > 0 ? violations[violations.length - 1].id : undefined,\n }\n if (incidentsChanged(lastViolations, next)) {\n await server.server\n .sendResourceUpdated({ uri: POLICY_VIOLATIONS_URI })\n .catch(() => {})\n }\n lastViolations = next\n } catch {\n // Core down or no policies yet — keep polling.\n }\n }\n\n if (pollMs > 0) {\n // Seed `last` on first tick so we don't fire an \"updated\" notification\n // when the server first comes up.\n timer = setInterval(() => {\n void tick()\n }, pollMs)\n if (typeof timer.unref === 'function') timer.unref()\n }\n\n return {\n stop: (): void => {\n stopped = true\n if (timer) clearInterval(timer)\n timer = null\n },\n }\n}\n","// Tool implementations. Each one takes an HttpClient + the validated input and\n// returns an MCP CallToolResult routed through formatToolResponse for the\n// three-part shape (NL + structured + footer) per ADR-039 / contract #12.\n// Keeping these as pure functions of (client, input) means tests don't need a\n// running server — just a stub client that returns canned JSON.\n\nimport type {\n BlastRadiusAffectedNode,\n BlastRadiusResult,\n ErrorEvent,\n GraphEdge,\n GraphNode,\n HypotheticalAction,\n PolicyViolation,\n RootCauseResult,\n TransitiveDependenciesResult,\n} from '@neat.is/types'\nimport { Provenance } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\nimport {\n formatEmptyResponse,\n formatErrorResponse,\n formatToolResponse,\n type ToolResponse,\n} from './format.js'\n\nexport type { ToolResponse } from './format.js'\n\n// Project-aware path builder. When `project` is set, route through\n// /projects/<name>/...; otherwise hit the legacy root URL (which the core\n// resolves to project=`default`). Keeping the legacy path means callers\n// running an older core still talk to a known route.\nfunction projectPath(project: string | undefined, suffix: string): string {\n if (!project) return suffix\n return `/projects/${encodeURIComponent(project)}${suffix}`\n}\n\n// Most tools want \"node missing → friendly message, anything else → real error\".\nasync function withMissingNodeFallback(\n fn: () => Promise<ToolResponse>,\n notFoundMessage: string,\n): Promise<ToolResponse> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return formatEmptyResponse(notFoundMessage)\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface RootCauseInput {\n errorNode: string\n errorId?: string\n project?: string\n}\n\nexport async function getRootCause(client: HttpClient, input: RootCauseInput): Promise<ToolResponse> {\n const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : ''\n const path = projectPath(\n input.project,\n `/traverse/root-cause/${encodeURIComponent(input.errorNode)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<RootCauseResult>(path)\n const arrowPath = result.traversalPath.join(' ← ')\n const provenances = result.edgeProvenances.length\n ? result.edgeProvenances.join(', ')\n : '(direct, no edges traversed)'\n const summary =\n `Root cause for ${input.errorNode} is ${result.rootCauseNode}. ` +\n result.rootCauseReason +\n (result.fixRecommendation ? ` Recommended fix: ${result.fixRecommendation}.` : '')\n const blockLines = [\n `Traversal path: ${arrowPath}`,\n `Edge provenances: ${provenances}`,\n ]\n if (result.fixRecommendation) {\n blockLines.push(`Recommended fix: ${result.fixRecommendation}`)\n }\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: result.confidence,\n provenance: result.edgeProvenances.length ? result.edgeProvenances : undefined,\n })\n }, `No root cause found for ${input.errorNode}. The node may be healthy, or it may not exist in the graph.`)\n}\n\nexport interface BlastRadiusInput {\n nodeId: string\n depth?: number\n project?: string\n}\n\nexport async function getBlastRadius(\n client: HttpClient,\n input: BlastRadiusInput,\n): Promise<ToolResponse> {\n const qs = input.depth !== undefined ? `?depth=${input.depth}` : ''\n const path = projectPath(\n input.project,\n `/traverse/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<BlastRadiusResult>(path)\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n `${result.origin} has no downstream dependencies. Nothing else would break if it failed.`,\n )\n }\n const sorted = [...result.affectedNodes].sort(\n (a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId),\n )\n const blockLines = sorted.map(formatBlastEntry)\n // Worst-case confidence — the path with the lowest cascaded confidence\n // is the headline number; agents should treat this as \"what's the\n // weakest reachability NEAT actually knows about?\"\n const minConfidence = sorted.reduce(\n (m, n) => Math.min(m, n.confidence),\n Number.POSITIVE_INFINITY,\n )\n const provenances = [...new Set(sorted.map((n) => n.edgeProvenance))]\n return formatToolResponse({\n summary: `Blast radius for ${result.origin}: ${result.totalAffected} affected node${result.totalAffected === 1 ? '' : 's'} reachable downstream.`,\n block: blockLines.join('\\n'),\n confidence: Number.isFinite(minConfidence) ? minConfidence : undefined,\n provenance: provenances.length ? provenances : undefined,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction formatBlastEntry(n: BlastRadiusAffectedNode): string {\n const tag = n.edgeProvenance === Provenance.STALE ? ' [STALE — last seen too long ago]' : ''\n return ` • ${n.nodeId} (distance ${n.distance}, ${n.edgeProvenance})${tag}`\n}\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\nexport interface DependenciesInput {\n nodeId: string\n // BFS depth. Default 3; max 10. Direct-only consumers pass 1.\n depth?: number\n project?: string\n}\n\n// Transitive get_dependencies (issue #144). Calls the new core endpoint\n// /graph/node/:id/dependencies?depth=N which BFS-walks outbound. The output\n// groups results by hop so direct dependencies stand out from transitives —\n// agents asked \"what does X depend on?\" usually want the direct list with\n// transitives as context.\nexport async function getDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n const depth = input.depth ?? 3\n const path = projectPath(\n input.project,\n `/graph/node/${encodeURIComponent(input.nodeId)}/dependencies?depth=${depth}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<TransitiveDependenciesResult>(path)\n if (result.total === 0) {\n return formatEmptyResponse(\n depth === 1\n ? `${input.nodeId} has no direct dependencies in the graph.`\n : `${input.nodeId} has no dependencies (BFS to depth ${depth}).`,\n )\n }\n // Group by distance so the structured block reads as concentric rings.\n const byDistance = new Map<number, typeof result.dependencies>()\n for (const dep of result.dependencies) {\n const ring = byDistance.get(dep.distance) ?? []\n ring.push(dep)\n byDistance.set(dep.distance, ring)\n }\n const blockLines: string[] = []\n for (const distance of [...byDistance.keys()].sort((a, b) => a - b)) {\n const label = distance === 1 ? 'Direct (distance 1)' : `Distance ${distance}`\n blockLines.push(`${label}:`)\n for (const dep of byDistance.get(distance)!) {\n blockLines.push(` • ${dep.nodeId} — ${dep.edgeType} (${dep.provenance})`)\n }\n }\n const provenances = [...new Set(result.dependencies.map((d) => d.provenance))]\n const directCount = byDistance.get(1)?.length ?? 0\n const summary =\n depth === 1\n ? `${input.nodeId} has ${directCount} direct dependenc${directCount === 1 ? 'y' : 'ies'}.`\n : `${input.nodeId} has ${result.total} dependenc${result.total === 1 ? 'y' : 'ies'} reachable to depth ${depth} (${directCount} direct).`\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n provenance: provenances,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport async function getObservedDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const edges = await client.get<EdgesResponse>(\n projectPath(input.project, `/graph/edges/${encodeURIComponent(input.nodeId)}`),\n )\n const observed = edges.outbound.filter((e) => e.provenance === Provenance.OBSERVED)\n if (observed.length === 0) {\n const hasExtracted = edges.outbound.some((e) => e.provenance === Provenance.EXTRACTED)\n const note = hasExtracted\n ? ' Static (EXTRACTED) dependencies exist but no runtime traffic has been seen — is OTel running?'\n : ''\n return formatEmptyResponse(`No OBSERVED dependencies for ${input.nodeId}.${note}`)\n }\n const blockLines = observed.map((e) => ` • ${e.target} — ${e.type}${edgeMeta(e)}`)\n return formatToolResponse({\n summary: `${input.nodeId} has ${observed.length} runtime dependenc${observed.length === 1 ? 'y' : 'ies'} confirmed by OTel.`,\n block: blockLines.join('\\n'),\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction edgeMeta(e: GraphEdge): string {\n const bits: string[] = []\n if (e.signal) {\n // Prefer the runtime signal numbers — \"saw 1,247 calls, 3 errors\" reads\n // better than a derived 0.94 confidence.\n bits.push(`spans=${e.signal.spanCount}`)\n if (e.signal.errorCount > 0) bits.push(`errors=${e.signal.errorCount}`)\n if (e.signal.lastObservedAgeMs !== undefined) {\n bits.push(`age=${formatDuration(e.signal.lastObservedAgeMs)}`)\n }\n } else if (e.callCount !== undefined) {\n bits.push(`callCount=${e.callCount}`)\n }\n if (e.lastObserved) bits.push(`lastObserved=${e.lastObserved}`)\n if (e.confidence !== undefined) bits.push(`confidence=${e.confidence}`)\n return bits.length ? ` [${bits.join(', ')}]` : ''\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n const s = Math.round(ms / 1000)\n if (s < 60) return `${s}s`\n const m = Math.round(s / 60)\n if (m < 60) return `${m}m`\n const h = Math.round(m / 60)\n if (h < 48) return `${h}h`\n return `${Math.round(h / 24)}d`\n}\n\nexport interface IncidentHistoryInput {\n nodeId: string\n limit?: number\n project?: string\n}\n\nexport async function getIncidentHistory(\n client: HttpClient,\n input: IncidentHistoryInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const events = await client.get<ErrorEvent[]>(\n projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`),\n )\n if (events.length === 0) {\n return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`)\n }\n // ndjson order is append-time = oldest first. Reverse so the most recent\n // event leads, then trim to the requested limit.\n const ordered = [...events].reverse().slice(0, input.limit ?? 20)\n const blockLines: string[] = []\n for (const ev of ordered) {\n blockLines.push(` ${ev.timestamp} — ${ev.service}: ${ev.errorMessage}`)\n blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`)\n }\n return formatToolResponse({\n summary: `${input.nodeId} has ${events.length} recorded incident${events.length === 1 ? '' : 's'}; showing the ${ordered.length} most recent.`,\n block: blockLines.join('\\n'),\n // ErrorEvents are observation records, not graph edges — provenance is\n // OBSERVED by definition (the OTel span happened).\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport interface SemanticSearchInput {\n query: string\n project?: string\n}\n\ninterface SearchResponse {\n query: string\n provider?: 'ollama' | 'transformers' | 'substring'\n matches: (GraphNode & { score?: number })[]\n}\n\nexport async function semanticSearch(\n client: HttpClient,\n input: SemanticSearchInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<SearchResponse>(\n projectPath(input.project, `/search?q=${encodeURIComponent(input.query)}`),\n )\n if (result.matches.length === 0) {\n return formatEmptyResponse(`No matches for \"${input.query}\".`)\n }\n const provider = result.provider ?? 'substring'\n const blockLines: string[] = []\n let topScore: number | undefined\n for (const n of result.matches) {\n // Embedding tiers attach a cosine score in [0,1]; substring fallback\n // doesn't, so we elide the score when it's the placeholder 1.\n const score = provider !== 'substring' && typeof n.score === 'number' ? n.score : undefined\n const scoreBit = score !== undefined ? ` [score=${score.toFixed(2)}]` : ''\n if (score !== undefined && (topScore === undefined || score > topScore)) topScore = score\n blockLines.push(\n ` • ${n.id} (${n.type}) — ${(n as { name?: string }).name ?? n.id}${scoreBit}`,\n )\n }\n return formatToolResponse({\n summary: `Found ${result.matches.length} match${result.matches.length === 1 ? '' : 'es'} for \"${input.query}\" via ${provider} provider.`,\n block: blockLines.join('\\n'),\n // Top similarity score doubles as a \"how confident is the embedder\n // about the best match\" signal. Substring provider returns no score —\n // the footer shows n/a in that case.\n confidence: topScore,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface GraphDiffInput {\n againstSnapshot: string\n project?: string\n}\n\ninterface GraphDiffResponse {\n base: { exportedAt?: string }\n current: { exportedAt: string }\n added: { nodes: GraphNode[]; edges: GraphEdge[] }\n removed: { nodes: GraphNode[]; edges: GraphEdge[] }\n changed: {\n nodes: { id: string; before: GraphNode; after: GraphNode }[]\n edges: { id: string; before: GraphEdge; after: GraphEdge }[]\n }\n}\n\nexport async function getGraphDiff(\n client: HttpClient,\n input: GraphDiffInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<GraphDiffResponse>(\n projectPath(\n input.project,\n `/graph/diff?against=${encodeURIComponent(input.againstSnapshot)}`,\n ),\n )\n const total =\n result.added.nodes.length +\n result.added.edges.length +\n result.removed.nodes.length +\n result.removed.edges.length +\n result.changed.nodes.length +\n result.changed.edges.length\n const baseLabel = result.base.exportedAt ?? 'unknown'\n if (total === 0) {\n return formatEmptyResponse(\n `No differences between the current graph and ${input.againstSnapshot} (base exportedAt=${baseLabel}).`,\n )\n }\n const blockLines: string[] = [\n ` base exportedAt: ${baseLabel}`,\n ` current exportedAt: ${result.current.exportedAt}`,\n '',\n ]\n if (result.added.nodes.length || result.added.edges.length) {\n blockLines.push('Added:')\n for (const n of result.added.nodes) blockLines.push(` + node ${n.id} (${n.type})`)\n for (const e of result.added.edges)\n blockLines.push(` + edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.removed.nodes.length || result.removed.edges.length) {\n blockLines.push('Removed:')\n for (const n of result.removed.nodes) blockLines.push(` - node ${n.id} (${n.type})`)\n for (const e of result.removed.edges)\n blockLines.push(` - edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.changed.nodes.length || result.changed.edges.length) {\n blockLines.push('Changed:')\n for (const c of result.changed.nodes) {\n blockLines.push(` ~ node ${c.id} — ${summariseAttrDiff(c.before, c.after)}`)\n }\n for (const c of result.changed.edges) {\n const provBit =\n c.before.provenance !== c.after.provenance\n ? `provenance ${c.before.provenance} → ${c.after.provenance}`\n : summariseAttrDiff(c.before, c.after)\n blockLines.push(` ~ edge ${c.id} — ${provBit}`)\n }\n }\n return formatToolResponse({\n summary: `Diff against ${input.againstSnapshot}: ${total} change${total === 1 ? '' : 's'} between the snapshot and the live graph.`,\n block: blockLines.join('\\n').trimEnd(),\n // Diff results don't have a per-result provenance — the diff spans\n // every edge type and provenance kind. Footer shows n/a.\n })\n } catch (err) {\n if (err instanceof HttpError && err.status === 400) {\n return formatErrorResponse(\n `Could not load snapshot ${input.againstSnapshot}: ${err.message}`,\n )\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nfunction summariseAttrDiff(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): string {\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n const changed: string[] = []\n for (const k of keys) {\n if (JSON.stringify(before[k]) !== JSON.stringify(after[k])) changed.push(k)\n }\n return changed.length === 0\n ? 'attributes differ'\n : `fields changed: ${changed.sort().join(', ')}`\n}\n\nexport interface RecentStaleEdgesInput {\n limit?: number\n edgeType?: string\n project?: string\n}\n\ninterface StaleEventResponse {\n edgeId: string\n source: string\n target: string\n edgeType: string\n thresholdMs: number\n ageMs: number\n lastObserved: string\n transitionedAt: string\n}\n\nexport async function getRecentStaleEdges(\n client: HttpClient,\n input: RecentStaleEdgesInput,\n): Promise<ToolResponse> {\n const params = new URLSearchParams()\n if (input.limit !== undefined) params.set('limit', String(input.limit))\n if (input.edgeType) params.set('edgeType', input.edgeType)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n\n try {\n const events = await client.get<StaleEventResponse[]>(\n projectPath(input.project, `/incidents/stale${qs}`),\n )\n if (events.length === 0) {\n return formatEmptyResponse(\n input.edgeType\n ? `No stale ${input.edgeType} edges recorded.`\n : 'No stale-edge transitions recorded yet.',\n )\n }\n const blockLines = events.map(\n (e) =>\n ` ${e.transitionedAt} — ${e.source} -[${e.edgeType}]-> ${e.target}` +\n ` (last seen ${e.lastObserved}, threshold ${formatDuration(e.thresholdMs)})`,\n )\n return formatToolResponse({\n summary: `${events.length} stale-edge transition${events.length === 1 ? '' : 's'} recorded${input.edgeType ? ` for ${input.edgeType}` : ''}.`,\n block: blockLines.join('\\n'),\n // STALE by definition — every event is a transition into STALE.\n provenance: Provenance.STALE,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface CheckPoliciesInput {\n // 'all' (default) returns every current violation. 'unresolved' is reserved\n // for future resolution tracking — for the MVP it behaves the same as 'all'.\n // { policyId } narrows to violations of one named policy.\n scope?: 'all' | 'unresolved' | { policyId: string }\n // When provided, dry-run evaluation: return violations that *would* result\n // if the action were applied. Without it, return current violations.\n hypotheticalAction?: HypotheticalAction\n project?: string\n}\n\ninterface PoliciesCheckResponse {\n allowed: boolean\n hypotheticalAction?: HypotheticalAction\n violations: PolicyViolation[]\n}\n\n// check_policies — single MCP tool covering both state-read and dry-run modes\n// per ADR-045. The contract explicitly rejects the audit's two-tool split\n// (evaluate_policy + get_policy_violations); both modes route through here.\nexport async function checkPolicies(\n client: HttpClient,\n input: CheckPoliciesInput,\n): Promise<ToolResponse> {\n try {\n let violations: PolicyViolation[]\n let allowed = true\n let hypothetical: HypotheticalAction | undefined\n\n if (input.hypotheticalAction) {\n // Dry-run via POST /policies/check.\n const body = await postJson<PoliciesCheckResponse>(\n client,\n projectPath(input.project, '/policies/check'),\n { hypotheticalAction: input.hypotheticalAction },\n )\n violations = body.violations\n allowed = body.allowed\n hypothetical = body.hypotheticalAction\n } else {\n // State read via GET /policies/violations. Optional scope filters via\n // ?policyId=, severity isn't surfaced in the tool input today.\n const qsParams = new URLSearchParams()\n if (typeof input.scope === 'object' && 'policyId' in input.scope) {\n qsParams.set('policyId', input.scope.policyId)\n }\n const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : ''\n violations = await client.get<PolicyViolation[]>(\n projectPath(input.project, `/policies/violations${qs}`),\n )\n allowed = violations.every((v) => v.onViolation !== 'block')\n }\n\n if (violations.length === 0) {\n return formatEmptyResponse(\n hypothetical\n ? `No violations would result from the hypothetical action (${hypothetical.kind}).`\n : 'No policy violations recorded.',\n )\n }\n\n const blockCount = violations.filter((v) => v.onViolation === 'block').length\n const summaryParts: string[] = []\n if (hypothetical) {\n summaryParts.push(\n `Hypothetical ${hypothetical.kind} would surface ${violations.length} violation${violations.length === 1 ? '' : 's'}`,\n )\n } else {\n summaryParts.push(\n `${violations.length} policy violation${violations.length === 1 ? '' : 's'} currently recorded`,\n )\n }\n if (blockCount > 0) {\n summaryParts.push(`${blockCount} of which block`)\n }\n if (!allowed && hypothetical) {\n summaryParts.push('action denied')\n }\n const summary = summaryParts.join('; ') + '.'\n\n const blockLines = violations.map((v) => {\n const subject = v.subject.nodeId ?? v.subject.edgeId ?? v.subject.path?.[0] ?? '(global)'\n return ` • [${v.severity}/${v.onViolation}] ${v.policyName}: ${v.message} — ${subject}`\n })\n const severities = [...new Set(violations.map((v) => v.severity))]\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n // Confidence: hypothetical results inherit a 0.7 cap (the engine\n // can't fully simulate every action shape in MVP); confirmed\n // violations report 1.00 since the engine ran against current state.\n confidence: hypothetical ? 0.7 : 1,\n provenance: severities.join(' '),\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nasync function postJson<T>(\n client: HttpClient,\n path: string,\n body: unknown,\n): Promise<T> {\n // The base HttpClient interface only exposes get(). For POST we need to\n // reach into the underlying transport. Most callers pass the client built\n // by createHttpClient which has post; types are kept minimal so test\n // stubs don't have to implement post unless the tool needs it.\n const c = client as HttpClient & { post?: <U>(p: string, b: unknown) => Promise<U> }\n if (typeof c.post !== 'function') {\n throw new Error('HttpClient does not support POST — required for check_policies dry-run')\n }\n return c.post<T>(path, body)\n}\n","// Standardized three-part response format for every MCP tool (ADR-039,\n// issue #143). Output shape:\n//\n// {summary — NL paragraph: what was found, why it matters}\n//\n// {block — typed payload, formatted}\n//\n// confidence: 0.94 · provenance: OBSERVED\n//\n// Empty result → footer reads \"confidence: n/a · provenance: n/a\". Every tool\n// in packages/mcp/src/tools.ts routes through this helper so consumers get a\n// consistent shape — agents can pattern-match on the footer to know how much\n// to trust the answer.\n\nexport interface ToolResponse {\n [x: string]: unknown\n content: { type: 'text'; text: string }[]\n isError?: boolean\n}\n\nexport interface FormatToolResponseInput {\n // NL paragraph. One or two sentences. What was found and why it matters.\n summary: string\n // Structured block. The formatted typed payload — usually a bullet list,\n // sometimes a multi-section breakdown. May be empty when the summary\n // already conveys everything.\n block?: string\n // Per-result confidence in [0, 1]. Undefined → footer reads \"n/a\".\n confidence?: number\n // Per-result provenance. Single value, or an array if the result spans\n // mixed provenances (e.g. a path of OBSERVED + EXTRACTED edges). Undefined\n // → footer reads \"n/a\".\n provenance?: string | string[]\n // Set on transport / 5xx errors. Routes through ToolResponse.isError so\n // MCP clients can surface a non-\"normal\" return.\n isError?: boolean\n}\n\nfunction formatFooter(\n confidence: number | undefined,\n provenance: string | string[] | undefined,\n): string {\n const c = confidence === undefined ? 'n/a' : confidence.toFixed(2)\n const p =\n provenance === undefined\n ? 'n/a'\n : Array.isArray(provenance)\n ? [...new Set(provenance)].join(', ')\n : provenance\n return `confidence: ${c} · provenance: ${p}`\n}\n\nexport function formatToolResponse(input: FormatToolResponseInput): ToolResponse {\n const sections: string[] = [input.summary.trim()]\n if (input.block && input.block.trim().length > 0) {\n sections.push(input.block.trimEnd())\n }\n sections.push(formatFooter(input.confidence, input.provenance))\n const text = sections.join('\\n\\n')\n return {\n content: [{ type: 'text', text }],\n ...(input.isError ? { isError: true } : {}),\n }\n}\n\n// Convenience for the \"node not found / empty graph\" path. Keeps the\n// three-part shape (summary still landed) but sets the footer to n/a / n/a\n// since there's nothing to confidence-tag or provenance-tag.\nexport function formatEmptyResponse(summary: string): ToolResponse {\n return formatToolResponse({ summary })\n}\n\n// Convenience for transport / 5xx errors at the MCP boundary. isError set\n// so MCP clients route the response into their error path.\nexport function formatErrorResponse(message: string): ToolResponse {\n return formatToolResponse({ summary: message, isError: true })\n}\n"],"mappings":";;;;AAEA,IAAAA,cAA0B;AAC1B,mBAAqC;AACrC,iBAAkB;AAClB,IAAAC,gBAAmE;;;ACM5D,SAAS,iBAAiBC,UAA6B;AAC5D,QAAM,OAAOA,SAAQ,QAAQ,OAAO,EAAE;AACtC,SAAO;AAAA,IACL,MAAM,IAAO,MAA0B;AACrC,YAAM,MAAM,MAAM,MAAM,GAAG,IAAI,GAAG,IAAI,EAAE;AACxC,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,cAAM,IAAI,UAAU,IAAI,QAAQ,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,WAAW,IAAI,K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AAc,QAAQ;AAAA,IACpB,GAAG;AAAA,IACH,SAAS,WAAW,KAAK;AAAA,EAC3B,CAAwC;AAC5C;AAMA,IAAM,kBAAkB,QAAQ,IAAI,wBAChC,OAAO,QAAQ,IAAI,qBAAqB,IACxC;AACJ,IAAM,uBAAuB,kBAAkB,QAAQ,QAAQ;AAAA,EAC7D,GAAI,oBAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;AAAA,EAC3D,GAAI,iBAAiB,EAAE,SAAS,eAAe,IAAI,CAAC;AACtD,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,YAAY,IAAI,kCAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,IAAM,cAAc,MAAY;AAC9B,uBAAqB,KAAK;AAC5B;AACA,QAAQ,GAAG,WAAW,WAAW;AACjC,QAAQ,GAAG,UAAU,WAAW;AAEhC,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_mcp","import_types","baseUrl","client","server","client"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/resources.ts","../src/tools.ts","../src/format.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { CheckPoliciesScopeSchema, HypotheticalActionSchema } from '@neat.is/types'\nimport { createHttpClient } from './client.js'\nimport { registerResources } from './resources.js'\nimport { DivergenceTypeSchema } from '@neat.is/types'\nimport {\n checkPolicies,\n getBlastRadius,\n getDependencies,\n getDivergences,\n getGraphDiff,\n getIncidentHistory,\n getObservedDependencies,\n getRecentStaleEdges,\n getRootCause,\n semanticSearch,\n} from './tools.js'\n\nconst baseUrl = process.env.NEAT_CORE_URL ?? 'http://localhost:8080'\nconst client = createHttpClient(baseUrl)\n\n// `NEAT_DEFAULT_PROJECT` is the implicit project for tool calls that don't\n// pass a `project` arg. Unset means \"use the core's `default` project\" — we\n// route those calls through the legacy unprefixed URL so an older core (one\n// that predates #83) still gets the request it expects.\nconst defaultProject = process.env.NEAT_DEFAULT_PROJECT\nconst projectFor = (input: { project?: string }): string | undefined =>\n input.project ?? defaultProject\n\nconst projectField = z\n .string()\n .optional()\n .describe(\n 'Project name when the core hosts more than one (set NEAT_PROJECTS=...). Omit to use the default project.',\n )\n\nconst server = new McpServer({\n name: 'neat',\n version: '0.1.0',\n})\n\nserver.tool(\n 'get_root_cause',\n 'Trace a failing node up its dependency graph to find the underlying cause. Use this when something is breaking and you want to know which upstream component is the actual culprit.',\n {\n errorNode: z\n .string()\n .describe('Graph node id where the error surfaced, e.g. \"database:payments-db\"'),\n errorId: z\n .string()\n .optional()\n .describe('Specific error event id from incident history; if set, the result is coloured with that error message'),\n project: projectField,\n },\n async (input) => getRootCause(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_blast_radius',\n 'List every node downstream of the given node — what would break if this node failed or was redeployed.',\n {\n nodeId: z.string().describe('Graph node id to compute blast radius from'),\n depth: z\n .number()\n .int()\n .nonnegative()\n .max(20)\n .optional()\n .describe('Max BFS depth (default 10)'),\n project: projectField,\n },\n async (input) => getBlastRadius(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_dependencies',\n 'List the transitive outgoing dependencies of a node, BFS to depth N (default 3, max 10). Each result carries distance, edge type, and provenance — both static (EXTRACTED) and runtime (OBSERVED). Pass depth=1 for direct-only.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n depth: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('BFS depth (default 3, max 10). depth=1 returns direct dependencies only.'),\n project: projectField,\n },\n async (input) => getDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_observed_dependencies',\n 'List only the runtime (OBSERVED via OTel) outgoing dependencies of a node. Use this to compare what code SAYS the service depends on vs what production actually does.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n project: projectField,\n },\n async (input) => getObservedDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_incident_history',\n 'Return recent OTel error events recorded against a node, most recent first.',\n {\n nodeId: z.string().describe('Graph node id to query'),\n limit: z.number().int().positive().max(100).optional().describe('Max events to return (default 20)'),\n project: projectField,\n },\n async (input) => getIncidentHistory(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'semantic_search',\n 'Search nodes by natural-language query. Uses embedding vectors when an embedder is available (Ollama nomic-embed-text → in-process MiniLM → substring fallback) — phrase the query the way you would describe what you want.',\n {\n query: z.string().describe('Free-text query, e.g. \"service handling checkout payments\"'),\n project: projectField,\n },\n async (input) => semanticSearch(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_graph_diff',\n 'Diff a saved graph snapshot against the current live graph. Useful for change reviews and post-incidents — answers \"what changed in the architecture between then and now.\" Returns added/removed/changed nodes and edges with both snapshot timestamps.',\n {\n againstSnapshot: z\n .string()\n .describe(\n 'Path or http(s) URL of the snapshot to diff against (the \"before\" state). The current graph is the \"after\".',\n ),\n project: projectField,\n },\n async (input) => getGraphDiff(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_recent_stale_edges',\n 'List the most recent OBSERVED → STALE edge transitions. Use this to spot integrations that have gone quiet — a CALLS edge that just went stale typically means an upstream stopped calling, not that the link is healthy.',\n {\n limit: z\n .number()\n .int()\n .positive()\n .max(200)\n .optional()\n .describe('Max events to return (default 50)'),\n edgeType: z\n .string()\n .optional()\n .describe('Filter by edge type — e.g. \"CALLS\" or \"CONNECTS_TO\"'),\n project: projectField,\n },\n async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_divergences',\n \"Returns places where what the code declares (EXTRACTED) doesn't match what production observed (OBSERVED). The single most NEAT-shaped query — the one that justifies the whole graph. Use when the user asks 'is anything weird?' or 'what does production do that the code doesn't?' or 'find me a bug' on an unfamiliar codebase. Returns divergences ranked by confidence × severity. Prefer this over `get_root_cause` when no specific node is failing.\",\n {\n type: z\n .array(DivergenceTypeSchema)\n .optional()\n .describe(\n 'Filter by divergence type. One or more of: missing-observed, missing-extracted, version-mismatch, host-mismatch, compat-violation. Omit for all.',\n ),\n minConfidence: z\n .number()\n .min(0)\n .max(1)\n .optional()\n .describe('Drop divergences below this confidence threshold (0.0 - 1.0).'),\n node: z\n .string()\n .optional()\n .describe('Scope to divergences involving this node id (as source or target).'),\n project: projectField,\n },\n async (input) =>\n getDivergences(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'check_policies',\n 'Inspect or dry-run the project\\'s policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).',\n {\n scope: CheckPoliciesScopeSchema.optional().describe(\n 'Narrow to a subset. Default \"all\".',\n ),\n hypotheticalAction: HypotheticalActionSchema.optional().describe(\n 'Dry-run mode: simulate the action and return resulting violations. Omit for current state.',\n ),\n project: projectField,\n },\n async (input) =>\n checkPolicies(client, {\n ...input,\n project: projectFor(input),\n } as Parameters<typeof checkPolicies>[1]),\n)\n\n// Resources sit alongside tools — same data, different access pattern. Read\n// the per-node resource for raw attrs+edges JSON; subscribe to the incidents\n// resource to be notified when new errors land. The eight tools above are\n// unchanged.\nconst incidentsPollMs = process.env.NEAT_RESOURCE_POLL_MS\n ? Number(process.env.NEAT_RESOURCE_POLL_MS)\n : undefined\nconst resourceRegistration = registerResources(server, client, {\n ...(incidentsPollMs !== undefined ? { incidentsPollMs } : {}),\n ...(defaultProject ? { project: defaultProject } : {}),\n})\n\nasync function main(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nconst stopPolling = (): void => {\n resourceRegistration.stop()\n}\nprocess.on('SIGTERM', stopPolling)\nprocess.on('SIGINT', stopPolling)\n\nmain().catch((err) => {\n console.error(err)\n process.exit(1)\n})\n","// Thin HTTP client for the neat-core REST surface. Tools call out via this\n// instead of fetch() directly so tests can swap in a stub implementation\n// without monkey-patching globals.\n\nexport interface HttpClient {\n get<T>(path: string): Promise<T>\n // POST is optional on the interface so test stubs that only need GET don't\n // have to implement it. Production createHttpClient always provides it.\n post?<T>(path: string, body: unknown): Promise<T>\n}\n\nexport function createHttpClient(baseUrl: string): HttpClient {\n const root = baseUrl.replace(/\\/$/, '')\n return {\n async get<T>(path: string): Promise<T> {\n const res = await fetch(`${root}${path}`)\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on GET ${path}: ${body}`)\n }\n return (await res.json()) as T\n },\n async post<T>(path: string, body: unknown): Promise<T> {\n const res = await fetch(`${root}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on POST ${path}: ${text}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n","// MCP Resources — additive surface alongside the eight tools. Two resources:\n//\n// neat://node/<id> — one resource per graph node. Read returns the\n// node attributes plus its outbound edges.\n// neat://incidents/recent — most recent error events. Pollable by the SDK\n// via subscribe; we send `notifications/resources/\n// updated` when /incidents grows.\n//\n// Pure read helpers are exported so tests can exercise them without spinning up\n// an MCP transport. `registerResources()` does the SDK wiring + the poll loop.\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type {\n ListResourcesResult,\n ReadResourceResult,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { ErrorEvent, GraphEdge, GraphNode, PolicyViolation } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\ninterface SerializedGraph {\n nodes: GraphNode[]\n edges: GraphEdge[]\n}\n\nconst NODE_RESOURCE_MIME = 'application/json'\nconst INCIDENTS_URI = 'neat://incidents/recent'\nconst INCIDENTS_DEFAULT_LIMIT = 50\nconst POLICY_VIOLATIONS_URI = 'neat://policies/violations'\nconst POLICY_VIOLATIONS_DEFAULT_LIMIT = 100\n\nfunction nodeUri(id: string): string {\n // Node ids contain `:` which RFC 6570 percent-encodes; doing it explicitly\n // here keeps the URI we hand the SDK identical to what `list` produces.\n return `neat://node/${encodeURIComponent(id)}`\n}\n\n// Project-aware URL prefix for the underlying core. When unset, hit the\n// legacy unprefixed routes (which the core resolves to project=`default`).\nfunction corePrefix(project: string | undefined): string {\n return project ? `/projects/${encodeURIComponent(project)}` : ''\n}\n\nfunction nameFromAttrs(attrs: GraphNode): string {\n return (attrs as { name?: string }).name ?? attrs.id\n}\n\nexport async function listNodeResources(\n client: HttpClient,\n project?: string,\n): Promise<ListResourcesResult> {\n const graph = await client.get<SerializedGraph>(`${corePrefix(project)}/graph`)\n return {\n resources: graph.nodes.map((n) => ({\n uri: nodeUri(n.id),\n name: nameFromAttrs(n),\n description: `${n.type} — ${nameFromAttrs(n)}`,\n mimeType: NODE_RESOURCE_MIME,\n })),\n }\n}\n\nexport async function readNodeResource(\n client: HttpClient,\n id: string,\n project?: string,\n): Promise<ReadResourceResult> {\n const uri = nodeUri(id)\n const prefix = corePrefix(project)\n try {\n const [nodeBody, edges] = await Promise.all([\n client.get<{ node: GraphNode }>(`${prefix}/graph/node/${encodeURIComponent(id)}`),\n client.get<EdgesResponse>(`${prefix}/graph/edges/${encodeURIComponent(id)}`),\n ])\n const body = {\n node: nodeBody.node,\n // Outbound only — the issue spec says \"attrs + outbound edges\". Inbound\n // edges are still reachable via the other endpoint and would double the\n // payload for hub nodes (e.g. a shared database).\n outboundEdges: edges.outbound,\n }\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(body, null, 2),\n },\n ],\n }\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify({ error: 'node not found', id }),\n },\n ],\n }\n }\n throw err\n }\n}\n\nexport async function readPolicyViolationsResource(\n client: HttpClient,\n limit: number = POLICY_VIOLATIONS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const body = await client.get<{ violations: PolicyViolation[] }>(\n `${corePrefix(project)}/policies/violations`,\n )\n const violations = body.violations\n // Latest first; cap at limit so an exploding violations log doesn't blow\n // up the resource read. The full file is still on disk for forensic use.\n const ordered = [...violations].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: POLICY_VIOLATIONS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: violations.length, violations: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\nexport async function readRecentIncidentsResource(\n client: HttpClient,\n limit: number = INCIDENTS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const body = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n `${corePrefix(project)}/incidents`,\n )\n const events = body.events\n // ndjson order is append-time = oldest first. Reverse so most-recent leads.\n const ordered = [...events].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: INCIDENTS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: events.length, events: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\n// Pure helper so the poll loop can be tested without timers. Returns true when\n// the visible state of /incidents has changed in a way subscribers should hear\n// about. Compares total count + the id of the newest event — either is enough\n// on its own, but the pair makes deletes (if they ever happen) survive a\n// missed update.\nexport function incidentsChanged(\n prev: { total: number; lastId?: string } | null,\n next: { total: number; lastId?: string },\n): boolean {\n if (!prev) return false // first observation seeds, doesn't notify\n if (prev.total !== next.total) return true\n if (prev.lastId !== next.lastId) return true\n return false\n}\n\nexport interface RegisterResourcesOptions {\n // Poll interval for /incidents in ms. 5s by default; 0 disables polling.\n incidentsPollMs?: number\n // Project this MCP instance reports against. Unset → core's `default`\n // project via the legacy unprefixed URLs.\n project?: string\n}\n\nexport interface ResourceRegistration {\n // Stops the poll loop. The SDK keeps the registered resources around as\n // long as the server is alive — calling stop() doesn't unregister them.\n stop: () => void\n}\n\nexport function registerResources(\n server: McpServer,\n client: HttpClient,\n options: RegisterResourcesOptions = {},\n): ResourceRegistration {\n const pollMs = options.incidentsPollMs ?? 5000\n const project = options.project\n\n // neat://node/<id> — templated. The list callback enumerates current nodes;\n // the read callback resolves a specific id.\n server.registerResource(\n 'graph-node',\n new ResourceTemplate('neat://node/{id}', {\n list: async () => listNodeResources(client, project),\n }),\n {\n description:\n 'A single graph node by id. Reading returns the node attributes plus its outbound edges as JSON.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async (_uri, variables) => {\n const raw = variables.id\n const id = Array.isArray(raw) ? raw[0] : raw\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error('neat://node/{id} requires an id')\n }\n const decoded = id.includes('%') ? decodeURIComponent(id) : id\n return readNodeResource(client, decoded, project)\n },\n )\n\n // neat://incidents/recent — static. Subscribers get notifications/resources/\n // updated on each tick where /incidents has changed.\n server.registerResource(\n 'incidents-recent',\n INCIDENTS_URI,\n {\n description:\n 'Most recent error events recorded by neat-core, newest first. JSON: { count, total, events[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readRecentIncidentsResource(client, INCIDENTS_DEFAULT_LIMIT, project),\n )\n\n // neat://policies/violations — static. Same poll-and-notify pattern as\n // incidents. Subscribers get resource-updated notifications when the\n // policy-violations.ndjson grows. ADR-045.\n server.registerResource(\n 'policies-violations',\n POLICY_VIOLATIONS_URI,\n {\n description:\n 'Current policy violations from policy-violations.ndjson, newest first. JSON: { count, total, violations[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readPolicyViolationsResource(client, POLICY_VIOLATIONS_DEFAULT_LIMIT, project),\n )\n\n let stopped = false\n let timer: NodeJS.Timeout | null = null\n let lastIncidents: { total: number; lastId?: string } | null = null\n let lastViolations: { total: number; lastId?: string } | null = null\n\n const tick = async (): Promise<void> => {\n if (stopped) return\n // Incidents poll.\n try {\n const incidents = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n `${corePrefix(project)}/incidents`,\n )\n const events = incidents.events\n const next = {\n total: incidents.total,\n lastId: events.length > 0 ? events[events.length - 1].id : undefined,\n }\n if (incidentsChanged(lastIncidents, next)) {\n await server.server.sendResourceUpdated({ uri: INCIDENTS_URI }).catch(() => {})\n }\n lastIncidents = next\n } catch {\n // Core down — keep polling, next tick will catch up.\n }\n // Policy-violations poll. Fires the alert action's notifications/\n // resources/updated for neat://policies/violations subscribers per\n // ADR-044 §alert. Same change-detection shape as incidents.\n try {\n const polBody = await client.get<{ violations: PolicyViolation[] }>(\n `${corePrefix(project)}/policies/violations`,\n )\n const violations = polBody.violations\n const next = {\n total: violations.length,\n lastId:\n violations.length > 0 ? violations[violations.length - 1].id : undefined,\n }\n if (incidentsChanged(lastViolations, next)) {\n await server.server\n .sendResourceUpdated({ uri: POLICY_VIOLATIONS_URI })\n .catch(() => {})\n }\n lastViolations = next\n } catch {\n // Core down or no policies yet — keep polling.\n }\n }\n\n if (pollMs > 0) {\n // Seed `last` on first tick so we don't fire an \"updated\" notification\n // when the server first comes up.\n timer = setInterval(() => {\n void tick()\n }, pollMs)\n if (typeof timer.unref === 'function') timer.unref()\n }\n\n return {\n stop: (): void => {\n stopped = true\n if (timer) clearInterval(timer)\n timer = null\n },\n }\n}\n","// Tool implementations. Each one takes an HttpClient + the validated input and\n// returns an MCP CallToolResult routed through formatToolResponse for the\n// three-part shape (NL + structured + footer) per ADR-039 / contract #12.\n// Keeping these as pure functions of (client, input) means tests don't need a\n// running server — just a stub client that returns canned JSON.\n\nimport type {\n BlastRadiusAffectedNode,\n BlastRadiusResult,\n Divergence,\n DivergenceResult,\n DivergenceType,\n ErrorEvent,\n GraphEdge,\n GraphNode,\n HypotheticalAction,\n PolicyViolation,\n RootCauseResult,\n TransitiveDependenciesResult,\n} from '@neat.is/types'\nimport { Provenance } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\nimport {\n formatEmptyResponse,\n formatErrorResponse,\n formatToolResponse,\n type ToolResponse,\n} from './format.js'\n\nexport type { ToolResponse } from './format.js'\n\n// Project-aware path builder. When `project` is set, route through\n// /projects/<name>/...; otherwise hit the legacy root URL (which the core\n// resolves to project=`default`). Keeping the legacy path means callers\n// running an older core still talk to a known route.\nfunction projectPath(project: string | undefined, suffix: string): string {\n if (!project) return suffix\n return `/projects/${encodeURIComponent(project)}${suffix}`\n}\n\n// Most tools want \"node missing → friendly message, anything else → real error\".\nasync function withMissingNodeFallback(\n fn: () => Promise<ToolResponse>,\n notFoundMessage: string,\n): Promise<ToolResponse> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return formatEmptyResponse(notFoundMessage)\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface RootCauseInput {\n errorNode: string\n errorId?: string\n project?: string\n}\n\nexport async function getRootCause(client: HttpClient, input: RootCauseInput): Promise<ToolResponse> {\n const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : ''\n const path = projectPath(\n input.project,\n `/graph/root-cause/${encodeURIComponent(input.errorNode)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<RootCauseResult>(path)\n const arrowPath = result.traversalPath.join(' ← ')\n const provenances = result.edgeProvenances.length\n ? result.edgeProvenances.join(', ')\n : '(direct, no edges traversed)'\n const summary =\n `Root cause for ${input.errorNode} is ${result.rootCauseNode}. ` +\n result.rootCauseReason +\n (result.fixRecommendation ? ` Recommended fix: ${result.fixRecommendation}.` : '')\n const blockLines = [\n `Traversal path: ${arrowPath}`,\n `Edge provenances: ${provenances}`,\n ]\n if (result.fixRecommendation) {\n blockLines.push(`Recommended fix: ${result.fixRecommendation}`)\n }\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: result.confidence,\n provenance: result.edgeProvenances.length ? result.edgeProvenances : undefined,\n })\n }, `No root cause found for ${input.errorNode}. The node may be healthy, or it may not exist in the graph.`)\n}\n\nexport interface BlastRadiusInput {\n nodeId: string\n depth?: number\n project?: string\n}\n\nexport async function getBlastRadius(\n client: HttpClient,\n input: BlastRadiusInput,\n): Promise<ToolResponse> {\n const qs = input.depth !== undefined ? `?depth=${input.depth}` : ''\n const path = projectPath(\n input.project,\n `/graph/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<BlastRadiusResult>(path)\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n `${result.origin} has no downstream dependencies. Nothing else would break if it failed.`,\n )\n }\n const sorted = [...result.affectedNodes].sort(\n (a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId),\n )\n const blockLines = sorted.map(formatBlastEntry)\n // Worst-case confidence — the path with the lowest cascaded confidence\n // is the headline number; agents should treat this as \"what's the\n // weakest reachability NEAT actually knows about?\"\n const minConfidence = sorted.reduce(\n (m, n) => Math.min(m, n.confidence),\n Number.POSITIVE_INFINITY,\n )\n const provenances = [...new Set(sorted.map((n) => n.edgeProvenance))]\n return formatToolResponse({\n summary: `Blast radius for ${result.origin}: ${result.totalAffected} affected node${result.totalAffected === 1 ? '' : 's'} reachable downstream.`,\n block: blockLines.join('\\n'),\n confidence: Number.isFinite(minConfidence) ? minConfidence : undefined,\n provenance: provenances.length ? provenances : undefined,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction formatBlastEntry(n: BlastRadiusAffectedNode): string {\n const tag = n.edgeProvenance === Provenance.STALE ? ' [STALE — last seen too long ago]' : ''\n return ` • ${n.nodeId} (distance ${n.distance}, ${n.edgeProvenance})${tag}`\n}\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\nexport interface DependenciesInput {\n nodeId: string\n // BFS depth. Default 3; max 10. Direct-only consumers pass 1.\n depth?: number\n project?: string\n}\n\n// Transitive get_dependencies (issue #144). Calls the core endpoint\n// /graph/dependencies/:nodeId?depth=N which BFS-walks outbound. The output\n// groups results by hop so direct dependencies stand out from transitives —\n// agents asked \"what does X depend on?\" usually want the direct list with\n// transitives as context.\nexport async function getDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n const depth = input.depth ?? 3\n const path = projectPath(\n input.project,\n `/graph/dependencies/${encodeURIComponent(input.nodeId)}?depth=${depth}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<TransitiveDependenciesResult>(path)\n if (result.total === 0) {\n return formatEmptyResponse(\n depth === 1\n ? `${input.nodeId} has no direct dependencies in the graph.`\n : `${input.nodeId} has no dependencies (BFS to depth ${depth}).`,\n )\n }\n // Group by distance so the structured block reads as concentric rings.\n const byDistance = new Map<number, typeof result.dependencies>()\n for (const dep of result.dependencies) {\n const ring = byDistance.get(dep.distance) ?? []\n ring.push(dep)\n byDistance.set(dep.distance, ring)\n }\n const blockLines: string[] = []\n for (const distance of [...byDistance.keys()].sort((a, b) => a - b)) {\n const label = distance === 1 ? 'Direct (distance 1)' : `Distance ${distance}`\n blockLines.push(`${label}:`)\n for (const dep of byDistance.get(distance)!) {\n blockLines.push(` • ${dep.nodeId} — ${dep.edgeType} (${dep.provenance})`)\n }\n }\n const provenances = [...new Set(result.dependencies.map((d) => d.provenance))]\n const directCount = byDistance.get(1)?.length ?? 0\n const summary =\n depth === 1\n ? `${input.nodeId} has ${directCount} direct dependenc${directCount === 1 ? 'y' : 'ies'}.`\n : `${input.nodeId} has ${result.total} dependenc${result.total === 1 ? 'y' : 'ies'} reachable to depth ${depth} (${directCount} direct).`\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n provenance: provenances,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport async function getObservedDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const edges = await client.get<EdgesResponse>(\n projectPath(input.project, `/graph/edges/${encodeURIComponent(input.nodeId)}`),\n )\n const observed = edges.outbound.filter((e) => e.provenance === Provenance.OBSERVED)\n if (observed.length === 0) {\n const hasExtracted = edges.outbound.some((e) => e.provenance === Provenance.EXTRACTED)\n const note = hasExtracted\n ? ' Static (EXTRACTED) dependencies exist but no runtime traffic has been seen — is OTel running?'\n : ''\n return formatEmptyResponse(`No OBSERVED dependencies for ${input.nodeId}.${note}`)\n }\n const blockLines = observed.map((e) => ` • ${e.target} — ${e.type}${edgeMeta(e)}`)\n return formatToolResponse({\n summary: `${input.nodeId} has ${observed.length} runtime dependenc${observed.length === 1 ? 'y' : 'ies'} confirmed by OTel.`,\n block: blockLines.join('\\n'),\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction edgeMeta(e: GraphEdge): string {\n const bits: string[] = []\n if (e.signal) {\n // Prefer the runtime signal numbers — \"saw 1,247 calls, 3 errors\" reads\n // better than a derived 0.94 confidence.\n bits.push(`spans=${e.signal.spanCount}`)\n if (e.signal.errorCount > 0) bits.push(`errors=${e.signal.errorCount}`)\n if (e.signal.lastObservedAgeMs !== undefined) {\n bits.push(`age=${formatDuration(e.signal.lastObservedAgeMs)}`)\n }\n } else if (e.callCount !== undefined) {\n bits.push(`callCount=${e.callCount}`)\n }\n if (e.lastObserved) bits.push(`lastObserved=${e.lastObserved}`)\n if (e.confidence !== undefined) bits.push(`confidence=${e.confidence}`)\n return bits.length ? ` [${bits.join(', ')}]` : ''\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n const s = Math.round(ms / 1000)\n if (s < 60) return `${s}s`\n const m = Math.round(s / 60)\n if (m < 60) return `${m}m`\n const h = Math.round(m / 60)\n if (h < 48) return `${h}h`\n return `${Math.round(h / 24)}d`\n}\n\nexport interface IncidentHistoryInput {\n nodeId: string\n limit?: number\n project?: string\n}\n\nexport async function getIncidentHistory(\n client: HttpClient,\n input: IncidentHistoryInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const body = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`),\n )\n const events = body.events\n if (events.length === 0) {\n return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`)\n }\n // ndjson order is append-time = oldest first. Reverse so the most recent\n // event leads, then trim to the requested limit.\n const ordered = [...events].reverse().slice(0, input.limit ?? 20)\n const blockLines: string[] = []\n for (const ev of ordered) {\n blockLines.push(` ${ev.timestamp} — ${ev.service}: ${ev.errorMessage}`)\n blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`)\n }\n return formatToolResponse({\n summary: `${input.nodeId} has ${body.total} recorded incident${body.total === 1 ? '' : 's'}; showing the ${ordered.length} most recent.`,\n block: blockLines.join('\\n'),\n // ErrorEvents are observation records, not graph edges — provenance is\n // OBSERVED by definition (the OTel span happened).\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport interface SemanticSearchInput {\n query: string\n project?: string\n}\n\ninterface SearchResponse {\n query: string\n provider?: 'ollama' | 'transformers' | 'substring'\n matches: (GraphNode & { score?: number })[]\n}\n\nexport async function semanticSearch(\n client: HttpClient,\n input: SemanticSearchInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<SearchResponse>(\n projectPath(input.project, `/search?q=${encodeURIComponent(input.query)}`),\n )\n if (result.matches.length === 0) {\n return formatEmptyResponse(`No matches for \"${input.query}\".`)\n }\n const provider = result.provider ?? 'substring'\n const blockLines: string[] = []\n let topScore: number | undefined\n for (const n of result.matches) {\n // Embedding tiers attach a cosine score in [0,1]; substring fallback\n // doesn't, so we elide the score when it's the placeholder 1.\n const score = provider !== 'substring' && typeof n.score === 'number' ? n.score : undefined\n const scoreBit = score !== undefined ? ` [score=${score.toFixed(2)}]` : ''\n if (score !== undefined && (topScore === undefined || score > topScore)) topScore = score\n blockLines.push(\n ` • ${n.id} (${n.type}) — ${(n as { name?: string }).name ?? n.id}${scoreBit}`,\n )\n }\n return formatToolResponse({\n summary: `Found ${result.matches.length} match${result.matches.length === 1 ? '' : 'es'} for \"${input.query}\" via ${provider} provider.`,\n block: blockLines.join('\\n'),\n // Top similarity score doubles as a \"how confident is the embedder\n // about the best match\" signal. Substring provider returns no score —\n // the footer shows n/a in that case.\n confidence: topScore,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface GraphDiffInput {\n againstSnapshot: string\n project?: string\n}\n\ninterface GraphDiffResponse {\n base: { exportedAt?: string }\n current: { exportedAt: string }\n added: { nodes: GraphNode[]; edges: GraphEdge[] }\n removed: { nodes: GraphNode[]; edges: GraphEdge[] }\n changed: {\n nodes: { id: string; before: GraphNode; after: GraphNode }[]\n edges: { id: string; before: GraphEdge; after: GraphEdge }[]\n }\n}\n\nexport async function getGraphDiff(\n client: HttpClient,\n input: GraphDiffInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<GraphDiffResponse>(\n projectPath(\n input.project,\n `/graph/diff?against=${encodeURIComponent(input.againstSnapshot)}`,\n ),\n )\n const total =\n result.added.nodes.length +\n result.added.edges.length +\n result.removed.nodes.length +\n result.removed.edges.length +\n result.changed.nodes.length +\n result.changed.edges.length\n const baseLabel = result.base.exportedAt ?? 'unknown'\n if (total === 0) {\n return formatEmptyResponse(\n `No differences between the current graph and ${input.againstSnapshot} (base exportedAt=${baseLabel}).`,\n )\n }\n const blockLines: string[] = [\n ` base exportedAt: ${baseLabel}`,\n ` current exportedAt: ${result.current.exportedAt}`,\n '',\n ]\n if (result.added.nodes.length || result.added.edges.length) {\n blockLines.push('Added:')\n for (const n of result.added.nodes) blockLines.push(` + node ${n.id} (${n.type})`)\n for (const e of result.added.edges)\n blockLines.push(` + edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.removed.nodes.length || result.removed.edges.length) {\n blockLines.push('Removed:')\n for (const n of result.removed.nodes) blockLines.push(` - node ${n.id} (${n.type})`)\n for (const e of result.removed.edges)\n blockLines.push(` - edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.changed.nodes.length || result.changed.edges.length) {\n blockLines.push('Changed:')\n for (const c of result.changed.nodes) {\n blockLines.push(` ~ node ${c.id} — ${summariseAttrDiff(c.before, c.after)}`)\n }\n for (const c of result.changed.edges) {\n const provBit =\n c.before.provenance !== c.after.provenance\n ? `provenance ${c.before.provenance} → ${c.after.provenance}`\n : summariseAttrDiff(c.before, c.after)\n blockLines.push(` ~ edge ${c.id} — ${provBit}`)\n }\n }\n return formatToolResponse({\n summary: `Diff against ${input.againstSnapshot}: ${total} change${total === 1 ? '' : 's'} between the snapshot and the live graph.`,\n block: blockLines.join('\\n').trimEnd(),\n // Diff results don't have a per-result provenance — the diff spans\n // every edge type and provenance kind. Footer shows n/a.\n })\n } catch (err) {\n if (err instanceof HttpError && err.status === 400) {\n return formatErrorResponse(\n `Could not load snapshot ${input.againstSnapshot}: ${err.message}`,\n )\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nfunction summariseAttrDiff(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): string {\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n const changed: string[] = []\n for (const k of keys) {\n if (JSON.stringify(before[k]) !== JSON.stringify(after[k])) changed.push(k)\n }\n return changed.length === 0\n ? 'attributes differ'\n : `fields changed: ${changed.sort().join(', ')}`\n}\n\nexport interface RecentStaleEdgesInput {\n limit?: number\n edgeType?: string\n project?: string\n}\n\ninterface StaleEventResponse {\n edgeId: string\n source: string\n target: string\n edgeType: string\n thresholdMs: number\n ageMs: number\n lastObserved: string\n transitionedAt: string\n}\n\nexport async function getRecentStaleEdges(\n client: HttpClient,\n input: RecentStaleEdgesInput,\n): Promise<ToolResponse> {\n const params = new URLSearchParams()\n if (input.limit !== undefined) params.set('limit', String(input.limit))\n if (input.edgeType) params.set('edgeType', input.edgeType)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n\n try {\n const body = await client.get<{ count: number; total: number; events: StaleEventResponse[] }>(\n projectPath(input.project, `/stale-events${qs}`),\n )\n const events = body.events\n if (events.length === 0) {\n return formatEmptyResponse(\n input.edgeType\n ? `No stale ${input.edgeType} edges recorded.`\n : 'No stale-edge transitions recorded yet.',\n )\n }\n const blockLines = events.map(\n (e) =>\n ` ${e.transitionedAt} — ${e.source} -[${e.edgeType}]-> ${e.target}` +\n ` (last seen ${e.lastObserved}, threshold ${formatDuration(e.thresholdMs)})`,\n )\n return formatToolResponse({\n summary: `${events.length} stale-edge transition${events.length === 1 ? '' : 's'} recorded${input.edgeType ? ` for ${input.edgeType}` : ''}.`,\n block: blockLines.join('\\n'),\n // STALE by definition — every event is a transition into STALE.\n provenance: Provenance.STALE,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface CheckPoliciesInput {\n // 'all' (default) returns every current violation. 'unresolved' is reserved\n // for future resolution tracking — for the MVP it behaves the same as 'all'.\n // { policyId } narrows to violations of one named policy.\n scope?: 'all' | 'unresolved' | { policyId: string }\n // When provided, dry-run evaluation: return violations that *would* result\n // if the action were applied. Without it, return current violations.\n hypotheticalAction?: HypotheticalAction\n project?: string\n}\n\ninterface PoliciesCheckResponse {\n allowed: boolean\n hypotheticalAction?: HypotheticalAction\n violations: PolicyViolation[]\n}\n\n// check_policies — single MCP tool covering both state-read and dry-run modes\n// per ADR-045. The contract explicitly rejects the audit's two-tool split\n// (evaluate_policy + get_policy_violations); both modes route through here.\nexport async function checkPolicies(\n client: HttpClient,\n input: CheckPoliciesInput,\n): Promise<ToolResponse> {\n try {\n let violations: PolicyViolation[]\n let allowed = true\n let hypothetical: HypotheticalAction | undefined\n\n if (input.hypotheticalAction) {\n // Dry-run via POST /policies/check.\n const body = await postJson<PoliciesCheckResponse>(\n client,\n projectPath(input.project, '/policies/check'),\n { hypotheticalAction: input.hypotheticalAction },\n )\n violations = body.violations\n allowed = body.allowed\n hypothetical = body.hypotheticalAction\n } else {\n // State read via GET /policies/violations. Optional scope filters via\n // ?policyId=, severity isn't surfaced in the tool input today.\n const qsParams = new URLSearchParams()\n if (typeof input.scope === 'object' && 'policyId' in input.scope) {\n qsParams.set('policyId', input.scope.policyId)\n }\n const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : ''\n const body = await client.get<{ violations: PolicyViolation[] }>(\n projectPath(input.project, `/policies/violations${qs}`),\n )\n violations = body.violations\n allowed = violations.every((v) => v.onViolation !== 'block')\n }\n\n if (violations.length === 0) {\n return formatEmptyResponse(\n hypothetical\n ? `No violations would result from the hypothetical action (${hypothetical.kind}).`\n : 'No policy violations recorded.',\n )\n }\n\n const blockCount = violations.filter((v) => v.onViolation === 'block').length\n const summaryParts: string[] = []\n if (hypothetical) {\n summaryParts.push(\n `Hypothetical ${hypothetical.kind} would surface ${violations.length} violation${violations.length === 1 ? '' : 's'}`,\n )\n } else {\n summaryParts.push(\n `${violations.length} policy violation${violations.length === 1 ? '' : 's'} currently recorded`,\n )\n }\n if (blockCount > 0) {\n summaryParts.push(`${blockCount} of which block`)\n }\n if (!allowed && hypothetical) {\n summaryParts.push('action denied')\n }\n const summary = summaryParts.join('; ') + '.'\n\n const blockLines = violations.map((v) => {\n const subject = v.subject.nodeId ?? v.subject.edgeId ?? v.subject.path?.[0] ?? '(global)'\n return ` • [${v.severity}/${v.onViolation}] ${v.policyName}: ${v.message} — ${subject}`\n })\n const severities = [...new Set(violations.map((v) => v.severity))]\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n // Confidence: hypothetical results inherit a 0.7 cap (the engine\n // can't fully simulate every action shape in MVP); confirmed\n // violations report 1.00 since the engine ran against current state.\n confidence: hypothetical ? 0.7 : 1,\n provenance: severities.join(' '),\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// get_divergences (ADR-060) — the thesis surface\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface DivergencesInput {\n type?: ReadonlyArray<DivergenceType>\n minConfidence?: number\n node?: string\n project?: string\n}\n\nfunction buildDivergencesPath(input: DivergencesInput): string {\n const params = new URLSearchParams()\n if (input.type && input.type.length > 0) params.set('type', input.type.join(','))\n if (input.minConfidence !== undefined) {\n params.set('minConfidence', String(input.minConfidence))\n }\n if (input.node) params.set('node', input.node)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n return projectPath(input.project, `/graph/divergences${qs}`)\n}\n\nfunction formatDivergenceLine(d: Divergence): string {\n switch (d.type) {\n case 'missing-observed':\n return ` • [${d.type}] ${d.source} → ${d.target} (${d.edgeType}) — confidence ${d.confidence.toFixed(2)}`\n case 'missing-extracted':\n return ` • [${d.type}] ${d.source} → ${d.target} (${d.edgeType}) — confidence ${d.confidence.toFixed(2)}`\n case 'version-mismatch':\n return ` • [${d.type}] ${d.source} → ${d.target} — declared ${d.extractedVersion}, observed engine ${d.observedVersion} (${d.compatibility})`\n case 'host-mismatch':\n return ` • [${d.type}] ${d.source} → ${d.target} — declared host ${d.extractedHost}, observed host ${d.observedHost}`\n case 'compat-violation':\n return ` • [${d.type}] ${d.source} → ${d.target} — ${d.rule.kind}${d.rule.package ? ` (${d.rule.package})` : ''}`\n }\n}\n\nexport async function getDivergences(\n client: HttpClient,\n input: DivergencesInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<DivergenceResult>(buildDivergencesPath(input))\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n 'No divergences found between the declared (EXTRACTED) and observed (OBSERVED) views of the graph.',\n )\n }\n // Sorted by confidence descending already; first entry is the headline.\n const headline = result.divergences[0]!\n const summary =\n `Found ${result.totalAffected} divergence${result.totalAffected === 1 ? '' : 's'} between code and production. ` +\n `Highest-confidence: ${headline.type} on ${headline.source} → ${headline.target}. ${headline.reason}`\n const blockLines: string[] = []\n for (const d of result.divergences) {\n blockLines.push(formatDivergenceLine(d))\n blockLines.push(` reason: ${d.reason}`)\n blockLines.push(` recommendation: ${d.recommendation}`)\n }\n const maxConfidence = result.divergences.reduce(\n (m, d) => Math.max(m, d.confidence),\n 0,\n )\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: maxConfidence,\n // Composite provenance — divergences sit between EXTRACTED and\n // OBSERVED by construction; that's what makes them divergences.\n provenance: 'composite (EXTRACTED + OBSERVED)',\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nasync function postJson<T>(\n client: HttpClient,\n path: string,\n body: unknown,\n): Promise<T> {\n // The base HttpClient interface only exposes get(). For POST we need to\n // reach into the underlying transport. Most callers pass the client built\n // by createHttpClient which has post; types are kept minimal so test\n // stubs don't have to implement post unless the tool needs it.\n const c = client as HttpClient & { post?: <U>(p: string, b: unknown) => Promise<U> }\n if (typeof c.post !== 'function') {\n throw new Error('HttpClient does not support POST — required for check_policies dry-run')\n }\n return c.post<T>(path, body)\n}\n","// Standardized three-part response format for every MCP tool (ADR-039,\n// issue #143). Output shape:\n//\n// {summary — NL paragraph: what was found, why it matters}\n//\n// {block — typed payload, formatted}\n//\n// confidence: 0.94 · provenance: OBSERVED\n//\n// Empty result → footer reads \"confidence: n/a · provenance: n/a\". Every tool\n// in packages/mcp/src/tools.ts routes through this helper so consumers get a\n// consistent shape — agents can pattern-match on the footer to know how much\n// to trust the answer.\n\nexport interface ToolResponse {\n [x: string]: unknown\n content: { type: 'text'; text: string }[]\n isError?: boolean\n}\n\nexport interface FormatToolResponseInput {\n // NL paragraph. One or two sentences. What was found and why it matters.\n summary: string\n // Structured block. The formatted typed payload — usually a bullet list,\n // sometimes a multi-section breakdown. May be empty when the summary\n // already conveys everything.\n block?: string\n // Per-result confidence in [0, 1]. Undefined → footer reads \"n/a\".\n confidence?: number\n // Per-result provenance. Single value, or an array if the result spans\n // mixed provenances (e.g. a path of OBSERVED + EXTRACTED edges). Undefined\n // → footer reads \"n/a\".\n provenance?: string | string[]\n // Set on transport / 5xx errors. Routes through ToolResponse.isError so\n // MCP clients can surface a non-\"normal\" return.\n isError?: boolean\n}\n\nfunction formatFooter(\n confidence: number | undefined,\n provenance: string | string[] | undefined,\n): string {\n const c = confidence === undefined ? 'n/a' : confidence.toFixed(2)\n const p =\n provenance === undefined\n ? 'n/a'\n : Array.isArray(provenance)\n ? [...new Set(provenance)].join(', ')\n : provenance\n return `confidence: ${c} · provenance: ${p}`\n}\n\nexport function formatToolResponse(input: FormatToolResponseInput): ToolResponse {\n const sections: string[] = [input.summary.trim()]\n if (input.block && input.block.trim().length > 0) {\n sections.push(input.block.trimEnd())\n }\n sections.push(formatFooter(input.confidence, input.provenance))\n const text = sections.join('\\n\\n')\n return {\n content: [{ type: 'text', text }],\n ...(input.isError ? { isError: true } : {}),\n }\n}\n\n// Convenience for the \"node not found / empty graph\" path. Keeps the\n// three-part shape (summary still landed) but sets the footer to n/a / n/a\n// since there's nothing to confidence-tag or provenance-tag.\nexport function formatEmptyResponse(summary: string): ToolResponse {\n return formatToolResponse({ summary })\n}\n\n// Convenience for transport / 5xx errors at the MCP boundary. isError set\n// so MCP clients route the response into their error path.\nexport function formatErrorResponse(message: string): ToolResponse {\n return formatToolResponse({ summary: message, isError: true })\n}\n"],"mappings":";;;;AAEA,IAAAA,cAA0B;AAC1B,mBAAqC;AACrC,iBAAkB;AAClB,IAAAC,gBAAmE;;;ACM5D,SAAS,iBAAiBC,UAA6B;AAC5D,QAAM,OAAOA,SAAQ,QAAQ,OAAO,EAAE;AACtC,SAAO;AAAA,IACL,MAAM,IAAO,MAA0B;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EACT;AAAA,MACC;AAAA,IACF;AAAA,IACF,eAAe,aACZ,OAAO,EACP,IAAI,CAAC,EACL,IAAI,CAAC,EACL,SAAS,EACT,SAAS,+DAA+D;AAAA,IAC3E,MAAM,aACH,OAAO,EACP,SAAS,EACT,SAAS,oEAAoE;AAAA,IAChF,SAAS;AAAA,EACX;AAAA,EACA,OAAO,UACL,eAAe,QAAQ,EAAE,GAAG,OAAO,SAAS,WAAW,KAAK,EAAE,CAAC;AACnE;AAEA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,IACE,OAAO,uCAAyB,SAAS,EAAE;AAAA,MACzC;AAAA,IACF;AAAA,IACA,oBAAoB,uCAAyB,SAAS,EAAE;AAAA,MACtD;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AAAA,EACA,OAAO,UACL,cAAc,QAAQ;AAAA,IACpB,GAAG;AAAA,IACH,SAAS,WAAW,KAAK;AAAA,EAC3B,CAAwC;AAC5C;AAMA,IAAM,kBAAkB,QAAQ,IAAI,wBAChC,OAAO,QAAQ,IAAI,qBAAqB,IACxC;AACJ,IAAM,uBAAuB,kBAAkB,QAAQ,QAAQ;AAAA,EAC7D,GAAI,oBAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;AAAA,EAC3D,GAAI,iBAAiB,EAAE,SAAS,eAAe,IAAI,CAAC;AACtD,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,YAAY,IAAI,kCAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,IAAM,cAAc,MAAY;AAC9B,uBAAqB,KAAK;AAC5B;AACA,QAAQ,GAAG,WAAW,WAAW;AACjC,QAAQ,GAAG,UAAU,WAAW;AAEhC,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_mcp","import_types","baseUrl","client","server","import_types","client"]}
|
package/dist/index.js
CHANGED
|
@@ -74,12 +74,12 @@ async function readNodeResource(client2, id, project) {
|
|
|
74
74
|
const uri = nodeUri(id);
|
|
75
75
|
const prefix = corePrefix(project);
|
|
76
76
|
try {
|
|
77
|
-
const [
|
|
77
|
+
const [nodeBody, edges] = await Promise.all([
|
|
78
78
|
client2.get(`${prefix}/graph/node/${encodeURIComponent(id)}`),
|
|
79
79
|
client2.get(`${prefix}/graph/edges/${encodeURIComponent(id)}`)
|
|
80
80
|
]);
|
|
81
81
|
const body = {
|
|
82
|
-
node:
|
|
82
|
+
node: nodeBody.node,
|
|
83
83
|
// Outbound only — the issue spec says "attrs + outbound edges". Inbound
|
|
84
84
|
// edges are still reachable via the other endpoint and would double the
|
|
85
85
|
// payload for hub nodes (e.g. a shared database).
|
|
@@ -110,9 +110,10 @@ async function readNodeResource(client2, id, project) {
|
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
112
|
async function readPolicyViolationsResource(client2, limit = POLICY_VIOLATIONS_DEFAULT_LIMIT, project) {
|
|
113
|
-
const
|
|
113
|
+
const body = await client2.get(
|
|
114
114
|
`${corePrefix(project)}/policies/violations`
|
|
115
115
|
);
|
|
116
|
+
const violations = body.violations;
|
|
116
117
|
const ordered = [...violations].reverse().slice(0, limit);
|
|
117
118
|
return {
|
|
118
119
|
contents: [
|
|
@@ -129,7 +130,10 @@ async function readPolicyViolationsResource(client2, limit = POLICY_VIOLATIONS_D
|
|
|
129
130
|
};
|
|
130
131
|
}
|
|
131
132
|
async function readRecentIncidentsResource(client2, limit = INCIDENTS_DEFAULT_LIMIT, project) {
|
|
132
|
-
const
|
|
133
|
+
const body = await client2.get(
|
|
134
|
+
`${corePrefix(project)}/incidents`
|
|
135
|
+
);
|
|
136
|
+
const events = body.events;
|
|
133
137
|
const ordered = [...events].reverse().slice(0, limit);
|
|
134
138
|
return {
|
|
135
139
|
contents: [
|
|
@@ -198,9 +202,12 @@ function registerResources(server2, client2, options = {}) {
|
|
|
198
202
|
const tick = async () => {
|
|
199
203
|
if (stopped) return;
|
|
200
204
|
try {
|
|
201
|
-
const
|
|
205
|
+
const incidents = await client2.get(
|
|
206
|
+
`${corePrefix(project)}/incidents`
|
|
207
|
+
);
|
|
208
|
+
const events = incidents.events;
|
|
202
209
|
const next = {
|
|
203
|
-
total:
|
|
210
|
+
total: incidents.total,
|
|
204
211
|
lastId: events.length > 0 ? events[events.length - 1].id : void 0
|
|
205
212
|
};
|
|
206
213
|
if (incidentsChanged(lastIncidents, next)) {
|
|
@@ -211,9 +218,10 @@ function registerResources(server2, client2, options = {}) {
|
|
|
211
218
|
} catch {
|
|
212
219
|
}
|
|
213
220
|
try {
|
|
214
|
-
const
|
|
221
|
+
const polBody = await client2.get(
|
|
215
222
|
`${corePrefix(project)}/policies/violations`
|
|
216
223
|
);
|
|
224
|
+
const violations = polBody.violations;
|
|
217
225
|
const next = {
|
|
218
226
|
total: violations.length,
|
|
219
227
|
lastId: violations.length > 0 ? violations[violations.length - 1].id : void 0
|
|
@@ -241,6 +249,9 @@ function registerResources(server2, client2, options = {}) {
|
|
|
241
249
|
};
|
|
242
250
|
}
|
|
243
251
|
|
|
252
|
+
// src/index.ts
|
|
253
|
+
import { DivergenceTypeSchema } from "@neat.is/types";
|
|
254
|
+
|
|
244
255
|
// src/tools.ts
|
|
245
256
|
import { Provenance } from "@neat.is/types";
|
|
246
257
|
|
|
@@ -288,7 +299,7 @@ async function getRootCause(client2, input) {
|
|
|
288
299
|
const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : "";
|
|
289
300
|
const path = projectPath(
|
|
290
301
|
input.project,
|
|
291
|
-
`/
|
|
302
|
+
`/graph/root-cause/${encodeURIComponent(input.errorNode)}${qs}`
|
|
292
303
|
);
|
|
293
304
|
return withMissingNodeFallback(async () => {
|
|
294
305
|
const result = await client2.get(path);
|
|
@@ -314,7 +325,7 @@ async function getBlastRadius(client2, input) {
|
|
|
314
325
|
const qs = input.depth !== void 0 ? `?depth=${input.depth}` : "";
|
|
315
326
|
const path = projectPath(
|
|
316
327
|
input.project,
|
|
317
|
-
`/
|
|
328
|
+
`/graph/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`
|
|
318
329
|
);
|
|
319
330
|
return withMissingNodeFallback(async () => {
|
|
320
331
|
const result = await client2.get(path);
|
|
@@ -348,7 +359,7 @@ async function getDependencies(client2, input) {
|
|
|
348
359
|
const depth = input.depth ?? 3;
|
|
349
360
|
const path = projectPath(
|
|
350
361
|
input.project,
|
|
351
|
-
`/graph/
|
|
362
|
+
`/graph/dependencies/${encodeURIComponent(input.nodeId)}?depth=${depth}`
|
|
352
363
|
);
|
|
353
364
|
return withMissingNodeFallback(async () => {
|
|
354
365
|
const result = await client2.get(path);
|
|
@@ -427,9 +438,10 @@ function formatDuration(ms) {
|
|
|
427
438
|
}
|
|
428
439
|
async function getIncidentHistory(client2, input) {
|
|
429
440
|
return withMissingNodeFallback(async () => {
|
|
430
|
-
const
|
|
441
|
+
const body = await client2.get(
|
|
431
442
|
projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`)
|
|
432
443
|
);
|
|
444
|
+
const events = body.events;
|
|
433
445
|
if (events.length === 0) {
|
|
434
446
|
return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`);
|
|
435
447
|
}
|
|
@@ -440,7 +452,7 @@ async function getIncidentHistory(client2, input) {
|
|
|
440
452
|
blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`);
|
|
441
453
|
}
|
|
442
454
|
return formatToolResponse({
|
|
443
|
-
summary: `${input.nodeId} has ${
|
|
455
|
+
summary: `${input.nodeId} has ${body.total} recorded incident${body.total === 1 ? "" : "s"}; showing the ${ordered.length} most recent.`,
|
|
444
456
|
block: blockLines.join("\n"),
|
|
445
457
|
// ErrorEvents are observation records, not graph edges — provenance is
|
|
446
458
|
// OBSERVED by definition (the OTel span happened).
|
|
@@ -552,9 +564,10 @@ async function getRecentStaleEdges(client2, input) {
|
|
|
552
564
|
if (input.edgeType) params.set("edgeType", input.edgeType);
|
|
553
565
|
const qs = params.size > 0 ? `?${params.toString()}` : "";
|
|
554
566
|
try {
|
|
555
|
-
const
|
|
556
|
-
projectPath(input.project, `/
|
|
567
|
+
const body = await client2.get(
|
|
568
|
+
projectPath(input.project, `/stale-events${qs}`)
|
|
557
569
|
);
|
|
570
|
+
const events = body.events;
|
|
558
571
|
if (events.length === 0) {
|
|
559
572
|
return formatEmptyResponse(
|
|
560
573
|
input.edgeType ? `No stale ${input.edgeType} edges recorded.` : "No stale-edge transitions recorded yet."
|
|
@@ -593,9 +606,10 @@ async function checkPolicies(client2, input) {
|
|
|
593
606
|
qsParams.set("policyId", input.scope.policyId);
|
|
594
607
|
}
|
|
595
608
|
const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : "";
|
|
596
|
-
|
|
609
|
+
const body = await client2.get(
|
|
597
610
|
projectPath(input.project, `/policies/violations${qs}`)
|
|
598
611
|
);
|
|
612
|
+
violations = body.violations;
|
|
599
613
|
allowed = violations.every((v) => v.onViolation !== "block");
|
|
600
614
|
}
|
|
601
615
|
if (violations.length === 0) {
|
|
@@ -639,6 +653,62 @@ async function checkPolicies(client2, input) {
|
|
|
639
653
|
return formatErrorResponse(`Error talking to neat-core: ${err.message}`);
|
|
640
654
|
}
|
|
641
655
|
}
|
|
656
|
+
function buildDivergencesPath(input) {
|
|
657
|
+
const params = new URLSearchParams();
|
|
658
|
+
if (input.type && input.type.length > 0) params.set("type", input.type.join(","));
|
|
659
|
+
if (input.minConfidence !== void 0) {
|
|
660
|
+
params.set("minConfidence", String(input.minConfidence));
|
|
661
|
+
}
|
|
662
|
+
if (input.node) params.set("node", input.node);
|
|
663
|
+
const qs = params.size > 0 ? `?${params.toString()}` : "";
|
|
664
|
+
return projectPath(input.project, `/graph/divergences${qs}`);
|
|
665
|
+
}
|
|
666
|
+
function formatDivergenceLine(d) {
|
|
667
|
+
switch (d.type) {
|
|
668
|
+
case "missing-observed":
|
|
669
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} (${d.edgeType}) \u2014 confidence ${d.confidence.toFixed(2)}`;
|
|
670
|
+
case "missing-extracted":
|
|
671
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} (${d.edgeType}) \u2014 confidence ${d.confidence.toFixed(2)}`;
|
|
672
|
+
case "version-mismatch":
|
|
673
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 declared ${d.extractedVersion}, observed engine ${d.observedVersion} (${d.compatibility})`;
|
|
674
|
+
case "host-mismatch":
|
|
675
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 declared host ${d.extractedHost}, observed host ${d.observedHost}`;
|
|
676
|
+
case "compat-violation":
|
|
677
|
+
return ` \u2022 [${d.type}] ${d.source} \u2192 ${d.target} \u2014 ${d.rule.kind}${d.rule.package ? ` (${d.rule.package})` : ""}`;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
async function getDivergences(client2, input) {
|
|
681
|
+
try {
|
|
682
|
+
const result = await client2.get(buildDivergencesPath(input));
|
|
683
|
+
if (result.totalAffected === 0) {
|
|
684
|
+
return formatEmptyResponse(
|
|
685
|
+
"No divergences found between the declared (EXTRACTED) and observed (OBSERVED) views of the graph."
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
const headline = result.divergences[0];
|
|
689
|
+
const summary = `Found ${result.totalAffected} divergence${result.totalAffected === 1 ? "" : "s"} between code and production. Highest-confidence: ${headline.type} on ${headline.source} \u2192 ${headline.target}. ${headline.reason}`;
|
|
690
|
+
const blockLines = [];
|
|
691
|
+
for (const d of result.divergences) {
|
|
692
|
+
blockLines.push(formatDivergenceLine(d));
|
|
693
|
+
blockLines.push(` reason: ${d.reason}`);
|
|
694
|
+
blockLines.push(` recommendation: ${d.recommendation}`);
|
|
695
|
+
}
|
|
696
|
+
const maxConfidence = result.divergences.reduce(
|
|
697
|
+
(m, d) => Math.max(m, d.confidence),
|
|
698
|
+
0
|
|
699
|
+
);
|
|
700
|
+
return formatToolResponse({
|
|
701
|
+
summary,
|
|
702
|
+
block: blockLines.join("\n"),
|
|
703
|
+
confidence: maxConfidence,
|
|
704
|
+
// Composite provenance — divergences sit between EXTRACTED and
|
|
705
|
+
// OBSERVED by construction; that's what makes them divergences.
|
|
706
|
+
provenance: "composite (EXTRACTED + OBSERVED)"
|
|
707
|
+
});
|
|
708
|
+
} catch (err) {
|
|
709
|
+
return formatErrorResponse(`Error talking to neat-core: ${err.message}`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
642
712
|
async function postJson(client2, path, body) {
|
|
643
713
|
const c = client2;
|
|
644
714
|
if (typeof c.post !== "function") {
|
|
@@ -738,6 +808,19 @@ server.tool(
|
|
|
738
808
|
},
|
|
739
809
|
async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) })
|
|
740
810
|
);
|
|
811
|
+
server.tool(
|
|
812
|
+
"get_divergences",
|
|
813
|
+
"Returns places where what the code declares (EXTRACTED) doesn't match what production observed (OBSERVED). The single most NEAT-shaped query \u2014 the one that justifies the whole graph. Use when the user asks 'is anything weird?' or 'what does production do that the code doesn't?' or 'find me a bug' on an unfamiliar codebase. Returns divergences ranked by confidence \xD7 severity. Prefer this over `get_root_cause` when no specific node is failing.",
|
|
814
|
+
{
|
|
815
|
+
type: z.array(DivergenceTypeSchema).optional().describe(
|
|
816
|
+
"Filter by divergence type. One or more of: missing-observed, missing-extracted, version-mismatch, host-mismatch, compat-violation. Omit for all."
|
|
817
|
+
),
|
|
818
|
+
minConfidence: z.number().min(0).max(1).optional().describe("Drop divergences below this confidence threshold (0.0 - 1.0)."),
|
|
819
|
+
node: z.string().optional().describe("Scope to divergences involving this node id (as source or target)."),
|
|
820
|
+
project: projectField
|
|
821
|
+
},
|
|
822
|
+
async (input) => getDivergences(client, { ...input, project: projectFor(input) })
|
|
823
|
+
);
|
|
741
824
|
server.tool(
|
|
742
825
|
"check_policies",
|
|
743
826
|
"Inspect or dry-run the project's policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).",
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/resources.ts","../src/tools.ts","../src/format.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { CheckPoliciesScopeSchema, HypotheticalActionSchema } from '@neat.is/types'\nimport { createHttpClient } from './client.js'\nimport { registerResources } from './resources.js'\nimport {\n checkPolicies,\n getBlastRadius,\n getDependencies,\n getGraphDiff,\n getIncidentHistory,\n getObservedDependencies,\n getRecentStaleEdges,\n getRootCause,\n semanticSearch,\n} from './tools.js'\n\nconst baseUrl = process.env.NEAT_CORE_URL ?? 'http://localhost:8080'\nconst client = createHttpClient(baseUrl)\n\n// `NEAT_DEFAULT_PROJECT` is the implicit project for tool calls that don't\n// pass a `project` arg. Unset means \"use the core's `default` project\" — we\n// route those calls through the legacy unprefixed URL so an older core (one\n// that predates #83) still gets the request it expects.\nconst defaultProject = process.env.NEAT_DEFAULT_PROJECT\nconst projectFor = (input: { project?: string }): string | undefined =>\n input.project ?? defaultProject\n\nconst projectField = z\n .string()\n .optional()\n .describe(\n 'Project name when the core hosts more than one (set NEAT_PROJECTS=...). Omit to use the default project.',\n )\n\nconst server = new McpServer({\n name: 'neat',\n version: '0.1.0',\n})\n\nserver.tool(\n 'get_root_cause',\n 'Trace a failing node up its dependency graph to find the underlying cause. Use this when something is breaking and you want to know which upstream component is the actual culprit.',\n {\n errorNode: z\n .string()\n .describe('Graph node id where the error surfaced, e.g. \"database:payments-db\"'),\n errorId: z\n .string()\n .optional()\n .describe('Specific error event id from incident history; if set, the result is coloured with that error message'),\n project: projectField,\n },\n async (input) => getRootCause(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_blast_radius',\n 'List every node downstream of the given node — what would break if this node failed or was redeployed.',\n {\n nodeId: z.string().describe('Graph node id to compute blast radius from'),\n depth: z\n .number()\n .int()\n .nonnegative()\n .max(20)\n .optional()\n .describe('Max BFS depth (default 10)'),\n project: projectField,\n },\n async (input) => getBlastRadius(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_dependencies',\n 'List the transitive outgoing dependencies of a node, BFS to depth N (default 3, max 10). Each result carries distance, edge type, and provenance — both static (EXTRACTED) and runtime (OBSERVED). Pass depth=1 for direct-only.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n depth: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('BFS depth (default 3, max 10). depth=1 returns direct dependencies only.'),\n project: projectField,\n },\n async (input) => getDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_observed_dependencies',\n 'List only the runtime (OBSERVED via OTel) outgoing dependencies of a node. Use this to compare what code SAYS the service depends on vs what production actually does.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n project: projectField,\n },\n async (input) => getObservedDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_incident_history',\n 'Return recent OTel error events recorded against a node, most recent first.',\n {\n nodeId: z.string().describe('Graph node id to query'),\n limit: z.number().int().positive().max(100).optional().describe('Max events to return (default 20)'),\n project: projectField,\n },\n async (input) => getIncidentHistory(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'semantic_search',\n 'Search nodes by natural-language query. Uses embedding vectors when an embedder is available (Ollama nomic-embed-text → in-process MiniLM → substring fallback) — phrase the query the way you would describe what you want.',\n {\n query: z.string().describe('Free-text query, e.g. \"service handling checkout payments\"'),\n project: projectField,\n },\n async (input) => semanticSearch(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_graph_diff',\n 'Diff a saved graph snapshot against the current live graph. Useful for change reviews and post-incidents — answers \"what changed in the architecture between then and now.\" Returns added/removed/changed nodes and edges with both snapshot timestamps.',\n {\n againstSnapshot: z\n .string()\n .describe(\n 'Path or http(s) URL of the snapshot to diff against (the \"before\" state). The current graph is the \"after\".',\n ),\n project: projectField,\n },\n async (input) => getGraphDiff(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_recent_stale_edges',\n 'List the most recent OBSERVED → STALE edge transitions. Use this to spot integrations that have gone quiet — a CALLS edge that just went stale typically means an upstream stopped calling, not that the link is healthy.',\n {\n limit: z\n .number()\n .int()\n .positive()\n .max(200)\n .optional()\n .describe('Max events to return (default 50)'),\n edgeType: z\n .string()\n .optional()\n .describe('Filter by edge type — e.g. \"CALLS\" or \"CONNECTS_TO\"'),\n project: projectField,\n },\n async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'check_policies',\n 'Inspect or dry-run the project\\'s policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).',\n {\n scope: CheckPoliciesScopeSchema.optional().describe(\n 'Narrow to a subset. Default \"all\".',\n ),\n hypotheticalAction: HypotheticalActionSchema.optional().describe(\n 'Dry-run mode: simulate the action and return resulting violations. Omit for current state.',\n ),\n project: projectField,\n },\n async (input) =>\n checkPolicies(client, {\n ...input,\n project: projectFor(input),\n } as Parameters<typeof checkPolicies>[1]),\n)\n\n// Resources sit alongside tools — same data, different access pattern. Read\n// the per-node resource for raw attrs+edges JSON; subscribe to the incidents\n// resource to be notified when new errors land. The eight tools above are\n// unchanged.\nconst incidentsPollMs = process.env.NEAT_RESOURCE_POLL_MS\n ? Number(process.env.NEAT_RESOURCE_POLL_MS)\n : undefined\nconst resourceRegistration = registerResources(server, client, {\n ...(incidentsPollMs !== undefined ? { incidentsPollMs } : {}),\n ...(defaultProject ? { project: defaultProject } : {}),\n})\n\nasync function main(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nconst stopPolling = (): void => {\n resourceRegistration.stop()\n}\nprocess.on('SIGTERM', stopPolling)\nprocess.on('SIGINT', stopPolling)\n\nmain().catch((err) => {\n console.error(err)\n process.exit(1)\n})\n","// Thin HTTP client for the neat-core REST surface. Tools call out via this\n// instead of fetch() directly so tests can swap in a stub implementation\n// without monkey-patching globals.\n\nexport interface HttpClient {\n get<T>(path: string): Promise<T>\n // POST is optional on the interface so test stubs that only need GET don't\n // have to implement it. Production createHttpClient always provides it.\n post?<T>(path: string, body: unknown): Promise<T>\n}\n\nexport function createHttpClient(baseUrl: string): HttpClient {\n const root = baseUrl.replace(/\\/$/, '')\n return {\n async get<T>(path: string): Promise<T> {\n const res = await fetch(`${root}${path}`)\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on GET ${path}: ${body}`)\n }\n return (await res.json()) as T\n },\n async post<T>(path: string, body: unknown): Promise<T> {\n const res = await fetch(`${root}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on POST ${path}: ${text}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n","// MCP Resources — additive surface alongside the eight tools. Two resources:\n//\n// neat://node/<id> — one resource per graph node. Read returns the\n// node attributes plus its outbound edges.\n// neat://incidents/recent — most recent error events. Pollable by the SDK\n// via subscribe; we send `notifications/resources/\n// updated` when /incidents grows.\n//\n// Pure read helpers are exported so tests can exercise them without spinning up\n// an MCP transport. `registerResources()` does the SDK wiring + the poll loop.\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type {\n ListResourcesResult,\n ReadResourceResult,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { ErrorEvent, GraphEdge, GraphNode, PolicyViolation } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\ninterface SerializedGraph {\n nodes: GraphNode[]\n edges: GraphEdge[]\n}\n\nconst NODE_RESOURCE_MIME = 'application/json'\nconst INCIDENTS_URI = 'neat://incidents/recent'\nconst INCIDENTS_DEFAULT_LIMIT = 50\nconst POLICY_VIOLATIONS_URI = 'neat://policies/violations'\nconst POLICY_VIOLATIONS_DEFAULT_LIMIT = 100\n\nfunction nodeUri(id: string): string {\n // Node ids contain `:` which RFC 6570 percent-encodes; doing it explicitly\n // here keeps the URI we hand the SDK identical to what `list` produces.\n return `neat://node/${encodeURIComponent(id)}`\n}\n\n// Project-aware URL prefix for the underlying core. When unset, hit the\n// legacy unprefixed routes (which the core resolves to project=`default`).\nfunction corePrefix(project: string | undefined): string {\n return project ? `/projects/${encodeURIComponent(project)}` : ''\n}\n\nfunction nameFromAttrs(attrs: GraphNode): string {\n return (attrs as { name?: string }).name ?? attrs.id\n}\n\nexport async function listNodeResources(\n client: HttpClient,\n project?: string,\n): Promise<ListResourcesResult> {\n const graph = await client.get<SerializedGraph>(`${corePrefix(project)}/graph`)\n return {\n resources: graph.nodes.map((n) => ({\n uri: nodeUri(n.id),\n name: nameFromAttrs(n),\n description: `${n.type} — ${nameFromAttrs(n)}`,\n mimeType: NODE_RESOURCE_MIME,\n })),\n }\n}\n\nexport async function readNodeResource(\n client: HttpClient,\n id: string,\n project?: string,\n): Promise<ReadResourceResult> {\n const uri = nodeUri(id)\n const prefix = corePrefix(project)\n try {\n const [attrs, edges] = await Promise.all([\n client.get<GraphNode>(`${prefix}/graph/node/${encodeURIComponent(id)}`),\n client.get<EdgesResponse>(`${prefix}/graph/edges/${encodeURIComponent(id)}`),\n ])\n const body = {\n node: attrs,\n // Outbound only — the issue spec says \"attrs + outbound edges\". Inbound\n // edges are still reachable via the other endpoint and would double the\n // payload for hub nodes (e.g. a shared database).\n outboundEdges: edges.outbound,\n }\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(body, null, 2),\n },\n ],\n }\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify({ error: 'node not found', id }),\n },\n ],\n }\n }\n throw err\n }\n}\n\nexport async function readPolicyViolationsResource(\n client: HttpClient,\n limit: number = POLICY_VIOLATIONS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const violations = await client.get<PolicyViolation[]>(\n `${corePrefix(project)}/policies/violations`,\n )\n // Latest first; cap at limit so an exploding violations log doesn't blow\n // up the resource read. The full file is still on disk for forensic use.\n const ordered = [...violations].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: POLICY_VIOLATIONS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: violations.length, violations: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\nexport async function readRecentIncidentsResource(\n client: HttpClient,\n limit: number = INCIDENTS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const events = await client.get<ErrorEvent[]>(`${corePrefix(project)}/incidents`)\n // ndjson order is append-time = oldest first. Reverse so most-recent leads.\n const ordered = [...events].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: INCIDENTS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: events.length, events: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\n// Pure helper so the poll loop can be tested without timers. Returns true when\n// the visible state of /incidents has changed in a way subscribers should hear\n// about. Compares total count + the id of the newest event — either is enough\n// on its own, but the pair makes deletes (if they ever happen) survive a\n// missed update.\nexport function incidentsChanged(\n prev: { total: number; lastId?: string } | null,\n next: { total: number; lastId?: string },\n): boolean {\n if (!prev) return false // first observation seeds, doesn't notify\n if (prev.total !== next.total) return true\n if (prev.lastId !== next.lastId) return true\n return false\n}\n\nexport interface RegisterResourcesOptions {\n // Poll interval for /incidents in ms. 5s by default; 0 disables polling.\n incidentsPollMs?: number\n // Project this MCP instance reports against. Unset → core's `default`\n // project via the legacy unprefixed URLs.\n project?: string\n}\n\nexport interface ResourceRegistration {\n // Stops the poll loop. The SDK keeps the registered resources around as\n // long as the server is alive — calling stop() doesn't unregister them.\n stop: () => void\n}\n\nexport function registerResources(\n server: McpServer,\n client: HttpClient,\n options: RegisterResourcesOptions = {},\n): ResourceRegistration {\n const pollMs = options.incidentsPollMs ?? 5000\n const project = options.project\n\n // neat://node/<id> — templated. The list callback enumerates current nodes;\n // the read callback resolves a specific id.\n server.registerResource(\n 'graph-node',\n new ResourceTemplate('neat://node/{id}', {\n list: async () => listNodeResources(client, project),\n }),\n {\n description:\n 'A single graph node by id. Reading returns the node attributes plus its outbound edges as JSON.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async (_uri, variables) => {\n const raw = variables.id\n const id = Array.isArray(raw) ? raw[0] : raw\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error('neat://node/{id} requires an id')\n }\n const decoded = id.includes('%') ? decodeURIComponent(id) : id\n return readNodeResource(client, decoded, project)\n },\n )\n\n // neat://incidents/recent — static. Subscribers get notifications/resources/\n // updated on each tick where /incidents has changed.\n server.registerResource(\n 'incidents-recent',\n INCIDENTS_URI,\n {\n description:\n 'Most recent error events recorded by neat-core, newest first. JSON: { count, total, events[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readRecentIncidentsResource(client, INCIDENTS_DEFAULT_LIMIT, project),\n )\n\n // neat://policies/violations — static. Same poll-and-notify pattern as\n // incidents. Subscribers get resource-updated notifications when the\n // policy-violations.ndjson grows. ADR-045.\n server.registerResource(\n 'policies-violations',\n POLICY_VIOLATIONS_URI,\n {\n description:\n 'Current policy violations from policy-violations.ndjson, newest first. JSON: { count, total, violations[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readPolicyViolationsResource(client, POLICY_VIOLATIONS_DEFAULT_LIMIT, project),\n )\n\n let stopped = false\n let timer: NodeJS.Timeout | null = null\n let lastIncidents: { total: number; lastId?: string } | null = null\n let lastViolations: { total: number; lastId?: string } | null = null\n\n const tick = async (): Promise<void> => {\n if (stopped) return\n // Incidents poll.\n try {\n const events = await client.get<ErrorEvent[]>(`${corePrefix(project)}/incidents`)\n const next = {\n total: events.length,\n lastId: events.length > 0 ? events[events.length - 1].id : undefined,\n }\n if (incidentsChanged(lastIncidents, next)) {\n await server.server.sendResourceUpdated({ uri: INCIDENTS_URI }).catch(() => {})\n }\n lastIncidents = next\n } catch {\n // Core down — keep polling, next tick will catch up.\n }\n // Policy-violations poll. Fires the alert action's notifications/\n // resources/updated for neat://policies/violations subscribers per\n // ADR-044 §alert. Same change-detection shape as incidents.\n try {\n const violations = await client.get<PolicyViolation[]>(\n `${corePrefix(project)}/policies/violations`,\n )\n const next = {\n total: violations.length,\n lastId:\n violations.length > 0 ? violations[violations.length - 1].id : undefined,\n }\n if (incidentsChanged(lastViolations, next)) {\n await server.server\n .sendResourceUpdated({ uri: POLICY_VIOLATIONS_URI })\n .catch(() => {})\n }\n lastViolations = next\n } catch {\n // Core down or no policies yet — keep polling.\n }\n }\n\n if (pollMs > 0) {\n // Seed `last` on first tick so we don't fire an \"updated\" notification\n // when the server first comes up.\n timer = setInterval(() => {\n void tick()\n }, pollMs)\n if (typeof timer.unref === 'function') timer.unref()\n }\n\n return {\n stop: (): void => {\n stopped = true\n if (timer) clearInterval(timer)\n timer = null\n },\n }\n}\n","// Tool implementations. Each one takes an HttpClient + the validated input and\n// returns an MCP CallToolResult routed through formatToolResponse for the\n// three-part shape (NL + structured + footer) per ADR-039 / contract #12.\n// Keeping these as pure functions of (client, input) means tests don't need a\n// running server — just a stub client that returns canned JSON.\n\nimport type {\n BlastRadiusAffectedNode,\n BlastRadiusResult,\n ErrorEvent,\n GraphEdge,\n GraphNode,\n HypotheticalAction,\n PolicyViolation,\n RootCauseResult,\n TransitiveDependenciesResult,\n} from '@neat.is/types'\nimport { Provenance } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\nimport {\n formatEmptyResponse,\n formatErrorResponse,\n formatToolResponse,\n type ToolResponse,\n} from './format.js'\n\nexport type { ToolResponse } from './format.js'\n\n// Project-aware path builder. When `project` is set, route through\n// /projects/<name>/...; otherwise hit the legacy root URL (which the core\n// resolves to project=`default`). Keeping the legacy path means callers\n// running an older core still talk to a known route.\nfunction projectPath(project: string | undefined, suffix: string): string {\n if (!project) return suffix\n return `/projects/${encodeURIComponent(project)}${suffix}`\n}\n\n// Most tools want \"node missing → friendly message, anything else → real error\".\nasync function withMissingNodeFallback(\n fn: () => Promise<ToolResponse>,\n notFoundMessage: string,\n): Promise<ToolResponse> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return formatEmptyResponse(notFoundMessage)\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface RootCauseInput {\n errorNode: string\n errorId?: string\n project?: string\n}\n\nexport async function getRootCause(client: HttpClient, input: RootCauseInput): Promise<ToolResponse> {\n const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : ''\n const path = projectPath(\n input.project,\n `/traverse/root-cause/${encodeURIComponent(input.errorNode)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<RootCauseResult>(path)\n const arrowPath = result.traversalPath.join(' ← ')\n const provenances = result.edgeProvenances.length\n ? result.edgeProvenances.join(', ')\n : '(direct, no edges traversed)'\n const summary =\n `Root cause for ${input.errorNode} is ${result.rootCauseNode}. ` +\n result.rootCauseReason +\n (result.fixRecommendation ? ` Recommended fix: ${result.fixRecommendation}.` : '')\n const blockLines = [\n `Traversal path: ${arrowPath}`,\n `Edge provenances: ${provenances}`,\n ]\n if (result.fixRecommendation) {\n blockLines.push(`Recommended fix: ${result.fixRecommendation}`)\n }\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: result.confidence,\n provenance: result.edgeProvenances.length ? result.edgeProvenances : undefined,\n })\n }, `No root cause found for ${input.errorNode}. The node may be healthy, or it may not exist in the graph.`)\n}\n\nexport interface BlastRadiusInput {\n nodeId: string\n depth?: number\n project?: string\n}\n\nexport async function getBlastRadius(\n client: HttpClient,\n input: BlastRadiusInput,\n): Promise<ToolResponse> {\n const qs = input.depth !== undefined ? `?depth=${input.depth}` : ''\n const path = projectPath(\n input.project,\n `/traverse/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<BlastRadiusResult>(path)\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n `${result.origin} has no downstream dependencies. Nothing else would break if it failed.`,\n )\n }\n const sorted = [...result.affectedNodes].sort(\n (a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId),\n )\n const blockLines = sorted.map(formatBlastEntry)\n // Worst-case confidence — the path with the lowest cascaded confidence\n // is the headline number; agents should treat this as \"what's the\n // weakest reachability NEAT actually knows about?\"\n const minConfidence = sorted.reduce(\n (m, n) => Math.min(m, n.confidence),\n Number.POSITIVE_INFINITY,\n )\n const provenances = [...new Set(sorted.map((n) => n.edgeProvenance))]\n return formatToolResponse({\n summary: `Blast radius for ${result.origin}: ${result.totalAffected} affected node${result.totalAffected === 1 ? '' : 's'} reachable downstream.`,\n block: blockLines.join('\\n'),\n confidence: Number.isFinite(minConfidence) ? minConfidence : undefined,\n provenance: provenances.length ? provenances : undefined,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction formatBlastEntry(n: BlastRadiusAffectedNode): string {\n const tag = n.edgeProvenance === Provenance.STALE ? ' [STALE — last seen too long ago]' : ''\n return ` • ${n.nodeId} (distance ${n.distance}, ${n.edgeProvenance})${tag}`\n}\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\nexport interface DependenciesInput {\n nodeId: string\n // BFS depth. Default 3; max 10. Direct-only consumers pass 1.\n depth?: number\n project?: string\n}\n\n// Transitive get_dependencies (issue #144). Calls the new core endpoint\n// /graph/node/:id/dependencies?depth=N which BFS-walks outbound. The output\n// groups results by hop so direct dependencies stand out from transitives —\n// agents asked \"what does X depend on?\" usually want the direct list with\n// transitives as context.\nexport async function getDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n const depth = input.depth ?? 3\n const path = projectPath(\n input.project,\n `/graph/node/${encodeURIComponent(input.nodeId)}/dependencies?depth=${depth}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<TransitiveDependenciesResult>(path)\n if (result.total === 0) {\n return formatEmptyResponse(\n depth === 1\n ? `${input.nodeId} has no direct dependencies in the graph.`\n : `${input.nodeId} has no dependencies (BFS to depth ${depth}).`,\n )\n }\n // Group by distance so the structured block reads as concentric rings.\n const byDistance = new Map<number, typeof result.dependencies>()\n for (const dep of result.dependencies) {\n const ring = byDistance.get(dep.distance) ?? []\n ring.push(dep)\n byDistance.set(dep.distance, ring)\n }\n const blockLines: string[] = []\n for (const distance of [...byDistance.keys()].sort((a, b) => a - b)) {\n const label = distance === 1 ? 'Direct (distance 1)' : `Distance ${distance}`\n blockLines.push(`${label}:`)\n for (const dep of byDistance.get(distance)!) {\n blockLines.push(` • ${dep.nodeId} — ${dep.edgeType} (${dep.provenance})`)\n }\n }\n const provenances = [...new Set(result.dependencies.map((d) => d.provenance))]\n const directCount = byDistance.get(1)?.length ?? 0\n const summary =\n depth === 1\n ? `${input.nodeId} has ${directCount} direct dependenc${directCount === 1 ? 'y' : 'ies'}.`\n : `${input.nodeId} has ${result.total} dependenc${result.total === 1 ? 'y' : 'ies'} reachable to depth ${depth} (${directCount} direct).`\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n provenance: provenances,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport async function getObservedDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const edges = await client.get<EdgesResponse>(\n projectPath(input.project, `/graph/edges/${encodeURIComponent(input.nodeId)}`),\n )\n const observed = edges.outbound.filter((e) => e.provenance === Provenance.OBSERVED)\n if (observed.length === 0) {\n const hasExtracted = edges.outbound.some((e) => e.provenance === Provenance.EXTRACTED)\n const note = hasExtracted\n ? ' Static (EXTRACTED) dependencies exist but no runtime traffic has been seen — is OTel running?'\n : ''\n return formatEmptyResponse(`No OBSERVED dependencies for ${input.nodeId}.${note}`)\n }\n const blockLines = observed.map((e) => ` • ${e.target} — ${e.type}${edgeMeta(e)}`)\n return formatToolResponse({\n summary: `${input.nodeId} has ${observed.length} runtime dependenc${observed.length === 1 ? 'y' : 'ies'} confirmed by OTel.`,\n block: blockLines.join('\\n'),\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction edgeMeta(e: GraphEdge): string {\n const bits: string[] = []\n if (e.signal) {\n // Prefer the runtime signal numbers — \"saw 1,247 calls, 3 errors\" reads\n // better than a derived 0.94 confidence.\n bits.push(`spans=${e.signal.spanCount}`)\n if (e.signal.errorCount > 0) bits.push(`errors=${e.signal.errorCount}`)\n if (e.signal.lastObservedAgeMs !== undefined) {\n bits.push(`age=${formatDuration(e.signal.lastObservedAgeMs)}`)\n }\n } else if (e.callCount !== undefined) {\n bits.push(`callCount=${e.callCount}`)\n }\n if (e.lastObserved) bits.push(`lastObserved=${e.lastObserved}`)\n if (e.confidence !== undefined) bits.push(`confidence=${e.confidence}`)\n return bits.length ? ` [${bits.join(', ')}]` : ''\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n const s = Math.round(ms / 1000)\n if (s < 60) return `${s}s`\n const m = Math.round(s / 60)\n if (m < 60) return `${m}m`\n const h = Math.round(m / 60)\n if (h < 48) return `${h}h`\n return `${Math.round(h / 24)}d`\n}\n\nexport interface IncidentHistoryInput {\n nodeId: string\n limit?: number\n project?: string\n}\n\nexport async function getIncidentHistory(\n client: HttpClient,\n input: IncidentHistoryInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const events = await client.get<ErrorEvent[]>(\n projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`),\n )\n if (events.length === 0) {\n return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`)\n }\n // ndjson order is append-time = oldest first. Reverse so the most recent\n // event leads, then trim to the requested limit.\n const ordered = [...events].reverse().slice(0, input.limit ?? 20)\n const blockLines: string[] = []\n for (const ev of ordered) {\n blockLines.push(` ${ev.timestamp} — ${ev.service}: ${ev.errorMessage}`)\n blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`)\n }\n return formatToolResponse({\n summary: `${input.nodeId} has ${events.length} recorded incident${events.length === 1 ? '' : 's'}; showing the ${ordered.length} most recent.`,\n block: blockLines.join('\\n'),\n // ErrorEvents are observation records, not graph edges — provenance is\n // OBSERVED by definition (the OTel span happened).\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport interface SemanticSearchInput {\n query: string\n project?: string\n}\n\ninterface SearchResponse {\n query: string\n provider?: 'ollama' | 'transformers' | 'substring'\n matches: (GraphNode & { score?: number })[]\n}\n\nexport async function semanticSearch(\n client: HttpClient,\n input: SemanticSearchInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<SearchResponse>(\n projectPath(input.project, `/search?q=${encodeURIComponent(input.query)}`),\n )\n if (result.matches.length === 0) {\n return formatEmptyResponse(`No matches for \"${input.query}\".`)\n }\n const provider = result.provider ?? 'substring'\n const blockLines: string[] = []\n let topScore: number | undefined\n for (const n of result.matches) {\n // Embedding tiers attach a cosine score in [0,1]; substring fallback\n // doesn't, so we elide the score when it's the placeholder 1.\n const score = provider !== 'substring' && typeof n.score === 'number' ? n.score : undefined\n const scoreBit = score !== undefined ? ` [score=${score.toFixed(2)}]` : ''\n if (score !== undefined && (topScore === undefined || score > topScore)) topScore = score\n blockLines.push(\n ` • ${n.id} (${n.type}) — ${(n as { name?: string }).name ?? n.id}${scoreBit}`,\n )\n }\n return formatToolResponse({\n summary: `Found ${result.matches.length} match${result.matches.length === 1 ? '' : 'es'} for \"${input.query}\" via ${provider} provider.`,\n block: blockLines.join('\\n'),\n // Top similarity score doubles as a \"how confident is the embedder\n // about the best match\" signal. Substring provider returns no score —\n // the footer shows n/a in that case.\n confidence: topScore,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface GraphDiffInput {\n againstSnapshot: string\n project?: string\n}\n\ninterface GraphDiffResponse {\n base: { exportedAt?: string }\n current: { exportedAt: string }\n added: { nodes: GraphNode[]; edges: GraphEdge[] }\n removed: { nodes: GraphNode[]; edges: GraphEdge[] }\n changed: {\n nodes: { id: string; before: GraphNode; after: GraphNode }[]\n edges: { id: string; before: GraphEdge; after: GraphEdge }[]\n }\n}\n\nexport async function getGraphDiff(\n client: HttpClient,\n input: GraphDiffInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<GraphDiffResponse>(\n projectPath(\n input.project,\n `/graph/diff?against=${encodeURIComponent(input.againstSnapshot)}`,\n ),\n )\n const total =\n result.added.nodes.length +\n result.added.edges.length +\n result.removed.nodes.length +\n result.removed.edges.length +\n result.changed.nodes.length +\n result.changed.edges.length\n const baseLabel = result.base.exportedAt ?? 'unknown'\n if (total === 0) {\n return formatEmptyResponse(\n `No differences between the current graph and ${input.againstSnapshot} (base exportedAt=${baseLabel}).`,\n )\n }\n const blockLines: string[] = [\n ` base exportedAt: ${baseLabel}`,\n ` current exportedAt: ${result.current.exportedAt}`,\n '',\n ]\n if (result.added.nodes.length || result.added.edges.length) {\n blockLines.push('Added:')\n for (const n of result.added.nodes) blockLines.push(` + node ${n.id} (${n.type})`)\n for (const e of result.added.edges)\n blockLines.push(` + edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.removed.nodes.length || result.removed.edges.length) {\n blockLines.push('Removed:')\n for (const n of result.removed.nodes) blockLines.push(` - node ${n.id} (${n.type})`)\n for (const e of result.removed.edges)\n blockLines.push(` - edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.changed.nodes.length || result.changed.edges.length) {\n blockLines.push('Changed:')\n for (const c of result.changed.nodes) {\n blockLines.push(` ~ node ${c.id} — ${summariseAttrDiff(c.before, c.after)}`)\n }\n for (const c of result.changed.edges) {\n const provBit =\n c.before.provenance !== c.after.provenance\n ? `provenance ${c.before.provenance} → ${c.after.provenance}`\n : summariseAttrDiff(c.before, c.after)\n blockLines.push(` ~ edge ${c.id} — ${provBit}`)\n }\n }\n return formatToolResponse({\n summary: `Diff against ${input.againstSnapshot}: ${total} change${total === 1 ? '' : 's'} between the snapshot and the live graph.`,\n block: blockLines.join('\\n').trimEnd(),\n // Diff results don't have a per-result provenance — the diff spans\n // every edge type and provenance kind. Footer shows n/a.\n })\n } catch (err) {\n if (err instanceof HttpError && err.status === 400) {\n return formatErrorResponse(\n `Could not load snapshot ${input.againstSnapshot}: ${err.message}`,\n )\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nfunction summariseAttrDiff(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): string {\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n const changed: string[] = []\n for (const k of keys) {\n if (JSON.stringify(before[k]) !== JSON.stringify(after[k])) changed.push(k)\n }\n return changed.length === 0\n ? 'attributes differ'\n : `fields changed: ${changed.sort().join(', ')}`\n}\n\nexport interface RecentStaleEdgesInput {\n limit?: number\n edgeType?: string\n project?: string\n}\n\ninterface StaleEventResponse {\n edgeId: string\n source: string\n target: string\n edgeType: string\n thresholdMs: number\n ageMs: number\n lastObserved: string\n transitionedAt: string\n}\n\nexport async function getRecentStaleEdges(\n client: HttpClient,\n input: RecentStaleEdgesInput,\n): Promise<ToolResponse> {\n const params = new URLSearchParams()\n if (input.limit !== undefined) params.set('limit', String(input.limit))\n if (input.edgeType) params.set('edgeType', input.edgeType)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n\n try {\n const events = await client.get<StaleEventResponse[]>(\n projectPath(input.project, `/incidents/stale${qs}`),\n )\n if (events.length === 0) {\n return formatEmptyResponse(\n input.edgeType\n ? `No stale ${input.edgeType} edges recorded.`\n : 'No stale-edge transitions recorded yet.',\n )\n }\n const blockLines = events.map(\n (e) =>\n ` ${e.transitionedAt} — ${e.source} -[${e.edgeType}]-> ${e.target}` +\n ` (last seen ${e.lastObserved}, threshold ${formatDuration(e.thresholdMs)})`,\n )\n return formatToolResponse({\n summary: `${events.length} stale-edge transition${events.length === 1 ? '' : 's'} recorded${input.edgeType ? ` for ${input.edgeType}` : ''}.`,\n block: blockLines.join('\\n'),\n // STALE by definition — every event is a transition into STALE.\n provenance: Provenance.STALE,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface CheckPoliciesInput {\n // 'all' (default) returns every current violation. 'unresolved' is reserved\n // for future resolution tracking — for the MVP it behaves the same as 'all'.\n // { policyId } narrows to violations of one named policy.\n scope?: 'all' | 'unresolved' | { policyId: string }\n // When provided, dry-run evaluation: return violations that *would* result\n // if the action were applied. Without it, return current violations.\n hypotheticalAction?: HypotheticalAction\n project?: string\n}\n\ninterface PoliciesCheckResponse {\n allowed: boolean\n hypotheticalAction?: HypotheticalAction\n violations: PolicyViolation[]\n}\n\n// check_policies — single MCP tool covering both state-read and dry-run modes\n// per ADR-045. The contract explicitly rejects the audit's two-tool split\n// (evaluate_policy + get_policy_violations); both modes route through here.\nexport async function checkPolicies(\n client: HttpClient,\n input: CheckPoliciesInput,\n): Promise<ToolResponse> {\n try {\n let violations: PolicyViolation[]\n let allowed = true\n let hypothetical: HypotheticalAction | undefined\n\n if (input.hypotheticalAction) {\n // Dry-run via POST /policies/check.\n const body = await postJson<PoliciesCheckResponse>(\n client,\n projectPath(input.project, '/policies/check'),\n { hypotheticalAction: input.hypotheticalAction },\n )\n violations = body.violations\n allowed = body.allowed\n hypothetical = body.hypotheticalAction\n } else {\n // State read via GET /policies/violations. Optional scope filters via\n // ?policyId=, severity isn't surfaced in the tool input today.\n const qsParams = new URLSearchParams()\n if (typeof input.scope === 'object' && 'policyId' in input.scope) {\n qsParams.set('policyId', input.scope.policyId)\n }\n const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : ''\n violations = await client.get<PolicyViolation[]>(\n projectPath(input.project, `/policies/violations${qs}`),\n )\n allowed = violations.every((v) => v.onViolation !== 'block')\n }\n\n if (violations.length === 0) {\n return formatEmptyResponse(\n hypothetical\n ? `No violations would result from the hypothetical action (${hypothetical.kind}).`\n : 'No policy violations recorded.',\n )\n }\n\n const blockCount = violations.filter((v) => v.onViolation === 'block').length\n const summaryParts: string[] = []\n if (hypothetical) {\n summaryParts.push(\n `Hypothetical ${hypothetical.kind} would surface ${violations.length} violation${violations.length === 1 ? '' : 's'}`,\n )\n } else {\n summaryParts.push(\n `${violations.length} policy violation${violations.length === 1 ? '' : 's'} currently recorded`,\n )\n }\n if (blockCount > 0) {\n summaryParts.push(`${blockCount} of which block`)\n }\n if (!allowed && hypothetical) {\n summaryParts.push('action denied')\n }\n const summary = summaryParts.join('; ') + '.'\n\n const blockLines = violations.map((v) => {\n const subject = v.subject.nodeId ?? v.subject.edgeId ?? v.subject.path?.[0] ?? '(global)'\n return ` • [${v.severity}/${v.onViolation}] ${v.policyName}: ${v.message} — ${subject}`\n })\n const severities = [...new Set(violations.map((v) => v.severity))]\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n // Confidence: hypothetical results inherit a 0.7 cap (the engine\n // can't fully simulate every action shape in MVP); confirmed\n // violations report 1.00 since the engine ran against current state.\n confidence: hypothetical ? 0.7 : 1,\n provenance: severities.join(' '),\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nasync function postJson<T>(\n client: HttpClient,\n path: string,\n body: unknown,\n): Promise<T> {\n // The base HttpClient interface only exposes get(). For POST we need to\n // reach into the underlying transport. Most callers pass the client built\n // by createHttpClient which has post; types are kept minimal so test\n // stubs don't have to implement post unless the tool needs it.\n const c = client as HttpClient & { post?: <U>(p: string, b: unknown) => Promise<U> }\n if (typeof c.post !== 'function') {\n throw new Error('HttpClient does not support POST — required for check_policies dry-run')\n }\n return c.post<T>(path, body)\n}\n","// Standardized three-part response format for every MCP tool (ADR-039,\n// issue #143). Output shape:\n//\n// {summary — NL paragraph: what was found, why it matters}\n//\n// {block — typed payload, formatted}\n//\n// confidence: 0.94 · provenance: OBSERVED\n//\n// Empty result → footer reads \"confidence: n/a · provenance: n/a\". Every tool\n// in packages/mcp/src/tools.ts routes through this helper so consumers get a\n// consistent shape — agents can pattern-match on the footer to know how much\n// to trust the answer.\n\nexport interface ToolResponse {\n [x: string]: unknown\n content: { type: 'text'; text: string }[]\n isError?: boolean\n}\n\nexport interface FormatToolResponseInput {\n // NL paragraph. One or two sentences. What was found and why it matters.\n summary: string\n // Structured block. The formatted typed payload — usually a bullet list,\n // sometimes a multi-section breakdown. May be empty when the summary\n // already conveys everything.\n block?: string\n // Per-result confidence in [0, 1]. Undefined → footer reads \"n/a\".\n confidence?: number\n // Per-result provenance. Single value, or an array if the result spans\n // mixed provenances (e.g. a path of OBSERVED + EXTRACTED edges). Undefined\n // → footer reads \"n/a\".\n provenance?: string | string[]\n // Set on transport / 5xx errors. Routes through ToolResponse.isError so\n // MCP clients can surface a non-\"normal\" return.\n isError?: boolean\n}\n\nfunction formatFooter(\n confidence: number | undefined,\n provenance: string | string[] | undefined,\n): string {\n const c = confidence === undefined ? 'n/a' : confidence.toFixed(2)\n const p =\n provenance === undefined\n ? 'n/a'\n : Array.isArray(provenance)\n ? [...new Set(provenance)].join(', ')\n : provenance\n return `confidence: ${c} · provenance: ${p}`\n}\n\nexport function formatToolResponse(input: FormatToolResponseInput): ToolResponse {\n const sections: string[] = [input.summary.trim()]\n if (input.block && input.block.trim().length > 0) {\n sections.push(input.block.trimEnd())\n }\n sections.push(formatFooter(input.confidence, input.provenance))\n const text = sections.join('\\n\\n')\n return {\n content: [{ type: 'text', text }],\n ...(input.isError ? { isError: true } : {}),\n }\n}\n\n// Convenience for the \"node not found / empty graph\" path. Keeps the\n// three-part shape (summary still landed) but sets the footer to n/a / n/a\n// since there's nothing to confidence-tag or provenance-tag.\nexport function formatEmptyResponse(summary: string): ToolResponse {\n return formatToolResponse({ summary })\n}\n\n// Convenience for transport / 5xx errors at the MCP boundary. isError set\n// so MCP clients route the response into their error path.\nexport function formatErrorResponse(message: string): ToolResponse {\n return formatToolResponse({ summary: message, isError: true })\n}\n"],"mappings":";;;AAEA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;AAClB,SAAS,0BAA0B,gCAAgC;;;ACM5D,SAAS,iBAAiBA,UAA6B;AAC5D,QAAM,OAAOA,SAAQ,QAAQ,OAAO,EAAE;AACtC,SAAO;AAAA,IACL,MAAM,IAAO,MAA0B;AACrC,YAAM,MAAM,MAAM,MAAM,GAAG,IAAI,GAAG,IAAI,EAAE;AACxC,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,cAAM,IAAI,UAAU,IAAI,QAAQ,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,WAAW,IAAI,KAAK,IAAI,EAAE;AAAA,MAC3F;AACA,aAAQ,MAAM,IAAI,KAAK;AAAA,IACzB;AAAA,IACA,MAAM,KAAQ,MAAc,MAA2B;AACrD,YAAM,MAAM,MAAM,MAAM,GAAG,IAAI,GAAG,IAAI,IAAI;AAAA,QACxC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAC9C,MAAM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AY,EAAE,gBAAgB,IAAI,CAAC;AAAA,EAC3D,GAAI,iBAAiB,EAAE,SAAS,eAAe,IAAI,CAAC;AACtD,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,IAAM,cAAc,MAAY;AAC9B,uBAAqB,KAAK;AAC5B;AACA,QAAQ,GAAG,WAAW,WAAW;AACjC,QAAQ,GAAG,UAAU,WAAW;AAEhC,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["baseUrl","client","server","client"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/client.ts","../src/resources.ts","../src/tools.ts","../src/format.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport { CheckPoliciesScopeSchema, HypotheticalActionSchema } from '@neat.is/types'\nimport { createHttpClient } from './client.js'\nimport { registerResources } from './resources.js'\nimport { DivergenceTypeSchema } from '@neat.is/types'\nimport {\n checkPolicies,\n getBlastRadius,\n getDependencies,\n getDivergences,\n getGraphDiff,\n getIncidentHistory,\n getObservedDependencies,\n getRecentStaleEdges,\n getRootCause,\n semanticSearch,\n} from './tools.js'\n\nconst baseUrl = process.env.NEAT_CORE_URL ?? 'http://localhost:8080'\nconst client = createHttpClient(baseUrl)\n\n// `NEAT_DEFAULT_PROJECT` is the implicit project for tool calls that don't\n// pass a `project` arg. Unset means \"use the core's `default` project\" — we\n// route those calls through the legacy unprefixed URL so an older core (one\n// that predates #83) still gets the request it expects.\nconst defaultProject = process.env.NEAT_DEFAULT_PROJECT\nconst projectFor = (input: { project?: string }): string | undefined =>\n input.project ?? defaultProject\n\nconst projectField = z\n .string()\n .optional()\n .describe(\n 'Project name when the core hosts more than one (set NEAT_PROJECTS=...). Omit to use the default project.',\n )\n\nconst server = new McpServer({\n name: 'neat',\n version: '0.1.0',\n})\n\nserver.tool(\n 'get_root_cause',\n 'Trace a failing node up its dependency graph to find the underlying cause. Use this when something is breaking and you want to know which upstream component is the actual culprit.',\n {\n errorNode: z\n .string()\n .describe('Graph node id where the error surfaced, e.g. \"database:payments-db\"'),\n errorId: z\n .string()\n .optional()\n .describe('Specific error event id from incident history; if set, the result is coloured with that error message'),\n project: projectField,\n },\n async (input) => getRootCause(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_blast_radius',\n 'List every node downstream of the given node — what would break if this node failed or was redeployed.',\n {\n nodeId: z.string().describe('Graph node id to compute blast radius from'),\n depth: z\n .number()\n .int()\n .nonnegative()\n .max(20)\n .optional()\n .describe('Max BFS depth (default 10)'),\n project: projectField,\n },\n async (input) => getBlastRadius(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_dependencies',\n 'List the transitive outgoing dependencies of a node, BFS to depth N (default 3, max 10). Each result carries distance, edge type, and provenance — both static (EXTRACTED) and runtime (OBSERVED). Pass depth=1 for direct-only.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n depth: z\n .number()\n .int()\n .min(1)\n .max(10)\n .optional()\n .describe('BFS depth (default 3, max 10). depth=1 returns direct dependencies only.'),\n project: projectField,\n },\n async (input) => getDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_observed_dependencies',\n 'List only the runtime (OBSERVED via OTel) outgoing dependencies of a node. Use this to compare what code SAYS the service depends on vs what production actually does.',\n {\n nodeId: z.string().describe('Graph node id to inspect'),\n project: projectField,\n },\n async (input) => getObservedDependencies(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_incident_history',\n 'Return recent OTel error events recorded against a node, most recent first.',\n {\n nodeId: z.string().describe('Graph node id to query'),\n limit: z.number().int().positive().max(100).optional().describe('Max events to return (default 20)'),\n project: projectField,\n },\n async (input) => getIncidentHistory(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'semantic_search',\n 'Search nodes by natural-language query. Uses embedding vectors when an embedder is available (Ollama nomic-embed-text → in-process MiniLM → substring fallback) — phrase the query the way you would describe what you want.',\n {\n query: z.string().describe('Free-text query, e.g. \"service handling checkout payments\"'),\n project: projectField,\n },\n async (input) => semanticSearch(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_graph_diff',\n 'Diff a saved graph snapshot against the current live graph. Useful for change reviews and post-incidents — answers \"what changed in the architecture between then and now.\" Returns added/removed/changed nodes and edges with both snapshot timestamps.',\n {\n againstSnapshot: z\n .string()\n .describe(\n 'Path or http(s) URL of the snapshot to diff against (the \"before\" state). The current graph is the \"after\".',\n ),\n project: projectField,\n },\n async (input) => getGraphDiff(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_recent_stale_edges',\n 'List the most recent OBSERVED → STALE edge transitions. Use this to spot integrations that have gone quiet — a CALLS edge that just went stale typically means an upstream stopped calling, not that the link is healthy.',\n {\n limit: z\n .number()\n .int()\n .positive()\n .max(200)\n .optional()\n .describe('Max events to return (default 50)'),\n edgeType: z\n .string()\n .optional()\n .describe('Filter by edge type — e.g. \"CALLS\" or \"CONNECTS_TO\"'),\n project: projectField,\n },\n async (input) => getRecentStaleEdges(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'get_divergences',\n \"Returns places where what the code declares (EXTRACTED) doesn't match what production observed (OBSERVED). The single most NEAT-shaped query — the one that justifies the whole graph. Use when the user asks 'is anything weird?' or 'what does production do that the code doesn't?' or 'find me a bug' on an unfamiliar codebase. Returns divergences ranked by confidence × severity. Prefer this over `get_root_cause` when no specific node is failing.\",\n {\n type: z\n .array(DivergenceTypeSchema)\n .optional()\n .describe(\n 'Filter by divergence type. One or more of: missing-observed, missing-extracted, version-mismatch, host-mismatch, compat-violation. Omit for all.',\n ),\n minConfidence: z\n .number()\n .min(0)\n .max(1)\n .optional()\n .describe('Drop divergences below this confidence threshold (0.0 - 1.0).'),\n node: z\n .string()\n .optional()\n .describe('Scope to divergences involving this node id (as source or target).'),\n project: projectField,\n },\n async (input) =>\n getDivergences(client, { ...input, project: projectFor(input) }),\n)\n\nserver.tool(\n 'check_policies',\n 'Inspect or dry-run the project\\'s policy.json. Without hypotheticalAction, returns currently-recorded violations. With hypotheticalAction, returns violations that would result if the action were applied. Architectural assertions in five shapes (structural / compatibility / provenance / ownership / blast-radius).',\n {\n scope: CheckPoliciesScopeSchema.optional().describe(\n 'Narrow to a subset. Default \"all\".',\n ),\n hypotheticalAction: HypotheticalActionSchema.optional().describe(\n 'Dry-run mode: simulate the action and return resulting violations. Omit for current state.',\n ),\n project: projectField,\n },\n async (input) =>\n checkPolicies(client, {\n ...input,\n project: projectFor(input),\n } as Parameters<typeof checkPolicies>[1]),\n)\n\n// Resources sit alongside tools — same data, different access pattern. Read\n// the per-node resource for raw attrs+edges JSON; subscribe to the incidents\n// resource to be notified when new errors land. The eight tools above are\n// unchanged.\nconst incidentsPollMs = process.env.NEAT_RESOURCE_POLL_MS\n ? Number(process.env.NEAT_RESOURCE_POLL_MS)\n : undefined\nconst resourceRegistration = registerResources(server, client, {\n ...(incidentsPollMs !== undefined ? { incidentsPollMs } : {}),\n ...(defaultProject ? { project: defaultProject } : {}),\n})\n\nasync function main(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nconst stopPolling = (): void => {\n resourceRegistration.stop()\n}\nprocess.on('SIGTERM', stopPolling)\nprocess.on('SIGINT', stopPolling)\n\nmain().catch((err) => {\n console.error(err)\n process.exit(1)\n})\n","// Thin HTTP client for the neat-core REST surface. Tools call out via this\n// instead of fetch() directly so tests can swap in a stub implementation\n// without monkey-patching globals.\n\nexport interface HttpClient {\n get<T>(path: string): Promise<T>\n // POST is optional on the interface so test stubs that only need GET don't\n // have to implement it. Production createHttpClient always provides it.\n post?<T>(path: string, body: unknown): Promise<T>\n}\n\nexport function createHttpClient(baseUrl: string): HttpClient {\n const root = baseUrl.replace(/\\/$/, '')\n return {\n async get<T>(path: string): Promise<T> {\n const res = await fetch(`${root}${path}`)\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on GET ${path}: ${body}`)\n }\n return (await res.json()) as T\n },\n async post<T>(path: string, body: unknown): Promise<T> {\n const res = await fetch(`${root}${path}`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n throw new HttpError(res.status, `${res.status} ${res.statusText} on POST ${path}: ${text}`)\n }\n return (await res.json()) as T\n },\n }\n}\n\nexport class HttpError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message)\n this.name = 'HttpError'\n }\n}\n","// MCP Resources — additive surface alongside the eight tools. Two resources:\n//\n// neat://node/<id> — one resource per graph node. Read returns the\n// node attributes plus its outbound edges.\n// neat://incidents/recent — most recent error events. Pollable by the SDK\n// via subscribe; we send `notifications/resources/\n// updated` when /incidents grows.\n//\n// Pure read helpers are exported so tests can exercise them without spinning up\n// an MCP transport. `registerResources()` does the SDK wiring + the poll loop.\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport {\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type {\n ListResourcesResult,\n ReadResourceResult,\n} from '@modelcontextprotocol/sdk/types.js'\nimport type { ErrorEvent, GraphEdge, GraphNode, PolicyViolation } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\ninterface SerializedGraph {\n nodes: GraphNode[]\n edges: GraphEdge[]\n}\n\nconst NODE_RESOURCE_MIME = 'application/json'\nconst INCIDENTS_URI = 'neat://incidents/recent'\nconst INCIDENTS_DEFAULT_LIMIT = 50\nconst POLICY_VIOLATIONS_URI = 'neat://policies/violations'\nconst POLICY_VIOLATIONS_DEFAULT_LIMIT = 100\n\nfunction nodeUri(id: string): string {\n // Node ids contain `:` which RFC 6570 percent-encodes; doing it explicitly\n // here keeps the URI we hand the SDK identical to what `list` produces.\n return `neat://node/${encodeURIComponent(id)}`\n}\n\n// Project-aware URL prefix for the underlying core. When unset, hit the\n// legacy unprefixed routes (which the core resolves to project=`default`).\nfunction corePrefix(project: string | undefined): string {\n return project ? `/projects/${encodeURIComponent(project)}` : ''\n}\n\nfunction nameFromAttrs(attrs: GraphNode): string {\n return (attrs as { name?: string }).name ?? attrs.id\n}\n\nexport async function listNodeResources(\n client: HttpClient,\n project?: string,\n): Promise<ListResourcesResult> {\n const graph = await client.get<SerializedGraph>(`${corePrefix(project)}/graph`)\n return {\n resources: graph.nodes.map((n) => ({\n uri: nodeUri(n.id),\n name: nameFromAttrs(n),\n description: `${n.type} — ${nameFromAttrs(n)}`,\n mimeType: NODE_RESOURCE_MIME,\n })),\n }\n}\n\nexport async function readNodeResource(\n client: HttpClient,\n id: string,\n project?: string,\n): Promise<ReadResourceResult> {\n const uri = nodeUri(id)\n const prefix = corePrefix(project)\n try {\n const [nodeBody, edges] = await Promise.all([\n client.get<{ node: GraphNode }>(`${prefix}/graph/node/${encodeURIComponent(id)}`),\n client.get<EdgesResponse>(`${prefix}/graph/edges/${encodeURIComponent(id)}`),\n ])\n const body = {\n node: nodeBody.node,\n // Outbound only — the issue spec says \"attrs + outbound edges\". Inbound\n // edges are still reachable via the other endpoint and would double the\n // payload for hub nodes (e.g. a shared database).\n outboundEdges: edges.outbound,\n }\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(body, null, 2),\n },\n ],\n }\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return {\n contents: [\n {\n uri,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify({ error: 'node not found', id }),\n },\n ],\n }\n }\n throw err\n }\n}\n\nexport async function readPolicyViolationsResource(\n client: HttpClient,\n limit: number = POLICY_VIOLATIONS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const body = await client.get<{ violations: PolicyViolation[] }>(\n `${corePrefix(project)}/policies/violations`,\n )\n const violations = body.violations\n // Latest first; cap at limit so an exploding violations log doesn't blow\n // up the resource read. The full file is still on disk for forensic use.\n const ordered = [...violations].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: POLICY_VIOLATIONS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: violations.length, violations: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\nexport async function readRecentIncidentsResource(\n client: HttpClient,\n limit: number = INCIDENTS_DEFAULT_LIMIT,\n project?: string,\n): Promise<ReadResourceResult> {\n const body = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n `${corePrefix(project)}/incidents`,\n )\n const events = body.events\n // ndjson order is append-time = oldest first. Reverse so most-recent leads.\n const ordered = [...events].reverse().slice(0, limit)\n return {\n contents: [\n {\n uri: INCIDENTS_URI,\n mimeType: NODE_RESOURCE_MIME,\n text: JSON.stringify(\n { count: ordered.length, total: events.length, events: ordered },\n null,\n 2,\n ),\n },\n ],\n }\n}\n\n// Pure helper so the poll loop can be tested without timers. Returns true when\n// the visible state of /incidents has changed in a way subscribers should hear\n// about. Compares total count + the id of the newest event — either is enough\n// on its own, but the pair makes deletes (if they ever happen) survive a\n// missed update.\nexport function incidentsChanged(\n prev: { total: number; lastId?: string } | null,\n next: { total: number; lastId?: string },\n): boolean {\n if (!prev) return false // first observation seeds, doesn't notify\n if (prev.total !== next.total) return true\n if (prev.lastId !== next.lastId) return true\n return false\n}\n\nexport interface RegisterResourcesOptions {\n // Poll interval for /incidents in ms. 5s by default; 0 disables polling.\n incidentsPollMs?: number\n // Project this MCP instance reports against. Unset → core's `default`\n // project via the legacy unprefixed URLs.\n project?: string\n}\n\nexport interface ResourceRegistration {\n // Stops the poll loop. The SDK keeps the registered resources around as\n // long as the server is alive — calling stop() doesn't unregister them.\n stop: () => void\n}\n\nexport function registerResources(\n server: McpServer,\n client: HttpClient,\n options: RegisterResourcesOptions = {},\n): ResourceRegistration {\n const pollMs = options.incidentsPollMs ?? 5000\n const project = options.project\n\n // neat://node/<id> — templated. The list callback enumerates current nodes;\n // the read callback resolves a specific id.\n server.registerResource(\n 'graph-node',\n new ResourceTemplate('neat://node/{id}', {\n list: async () => listNodeResources(client, project),\n }),\n {\n description:\n 'A single graph node by id. Reading returns the node attributes plus its outbound edges as JSON.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async (_uri, variables) => {\n const raw = variables.id\n const id = Array.isArray(raw) ? raw[0] : raw\n if (typeof id !== 'string' || id.length === 0) {\n throw new Error('neat://node/{id} requires an id')\n }\n const decoded = id.includes('%') ? decodeURIComponent(id) : id\n return readNodeResource(client, decoded, project)\n },\n )\n\n // neat://incidents/recent — static. Subscribers get notifications/resources/\n // updated on each tick where /incidents has changed.\n server.registerResource(\n 'incidents-recent',\n INCIDENTS_URI,\n {\n description:\n 'Most recent error events recorded by neat-core, newest first. JSON: { count, total, events[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readRecentIncidentsResource(client, INCIDENTS_DEFAULT_LIMIT, project),\n )\n\n // neat://policies/violations — static. Same poll-and-notify pattern as\n // incidents. Subscribers get resource-updated notifications when the\n // policy-violations.ndjson grows. ADR-045.\n server.registerResource(\n 'policies-violations',\n POLICY_VIOLATIONS_URI,\n {\n description:\n 'Current policy violations from policy-violations.ndjson, newest first. JSON: { count, total, violations[] }.',\n mimeType: NODE_RESOURCE_MIME,\n },\n async () => readPolicyViolationsResource(client, POLICY_VIOLATIONS_DEFAULT_LIMIT, project),\n )\n\n let stopped = false\n let timer: NodeJS.Timeout | null = null\n let lastIncidents: { total: number; lastId?: string } | null = null\n let lastViolations: { total: number; lastId?: string } | null = null\n\n const tick = async (): Promise<void> => {\n if (stopped) return\n // Incidents poll.\n try {\n const incidents = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n `${corePrefix(project)}/incidents`,\n )\n const events = incidents.events\n const next = {\n total: incidents.total,\n lastId: events.length > 0 ? events[events.length - 1].id : undefined,\n }\n if (incidentsChanged(lastIncidents, next)) {\n await server.server.sendResourceUpdated({ uri: INCIDENTS_URI }).catch(() => {})\n }\n lastIncidents = next\n } catch {\n // Core down — keep polling, next tick will catch up.\n }\n // Policy-violations poll. Fires the alert action's notifications/\n // resources/updated for neat://policies/violations subscribers per\n // ADR-044 §alert. Same change-detection shape as incidents.\n try {\n const polBody = await client.get<{ violations: PolicyViolation[] }>(\n `${corePrefix(project)}/policies/violations`,\n )\n const violations = polBody.violations\n const next = {\n total: violations.length,\n lastId:\n violations.length > 0 ? violations[violations.length - 1].id : undefined,\n }\n if (incidentsChanged(lastViolations, next)) {\n await server.server\n .sendResourceUpdated({ uri: POLICY_VIOLATIONS_URI })\n .catch(() => {})\n }\n lastViolations = next\n } catch {\n // Core down or no policies yet — keep polling.\n }\n }\n\n if (pollMs > 0) {\n // Seed `last` on first tick so we don't fire an \"updated\" notification\n // when the server first comes up.\n timer = setInterval(() => {\n void tick()\n }, pollMs)\n if (typeof timer.unref === 'function') timer.unref()\n }\n\n return {\n stop: (): void => {\n stopped = true\n if (timer) clearInterval(timer)\n timer = null\n },\n }\n}\n","// Tool implementations. Each one takes an HttpClient + the validated input and\n// returns an MCP CallToolResult routed through formatToolResponse for the\n// three-part shape (NL + structured + footer) per ADR-039 / contract #12.\n// Keeping these as pure functions of (client, input) means tests don't need a\n// running server — just a stub client that returns canned JSON.\n\nimport type {\n BlastRadiusAffectedNode,\n BlastRadiusResult,\n Divergence,\n DivergenceResult,\n DivergenceType,\n ErrorEvent,\n GraphEdge,\n GraphNode,\n HypotheticalAction,\n PolicyViolation,\n RootCauseResult,\n TransitiveDependenciesResult,\n} from '@neat.is/types'\nimport { Provenance } from '@neat.is/types'\nimport { HttpError, type HttpClient } from './client.js'\nimport {\n formatEmptyResponse,\n formatErrorResponse,\n formatToolResponse,\n type ToolResponse,\n} from './format.js'\n\nexport type { ToolResponse } from './format.js'\n\n// Project-aware path builder. When `project` is set, route through\n// /projects/<name>/...; otherwise hit the legacy root URL (which the core\n// resolves to project=`default`). Keeping the legacy path means callers\n// running an older core still talk to a known route.\nfunction projectPath(project: string | undefined, suffix: string): string {\n if (!project) return suffix\n return `/projects/${encodeURIComponent(project)}${suffix}`\n}\n\n// Most tools want \"node missing → friendly message, anything else → real error\".\nasync function withMissingNodeFallback(\n fn: () => Promise<ToolResponse>,\n notFoundMessage: string,\n): Promise<ToolResponse> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof HttpError && err.status === 404) {\n return formatEmptyResponse(notFoundMessage)\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface RootCauseInput {\n errorNode: string\n errorId?: string\n project?: string\n}\n\nexport async function getRootCause(client: HttpClient, input: RootCauseInput): Promise<ToolResponse> {\n const qs = input.errorId ? `?errorId=${encodeURIComponent(input.errorId)}` : ''\n const path = projectPath(\n input.project,\n `/graph/root-cause/${encodeURIComponent(input.errorNode)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<RootCauseResult>(path)\n const arrowPath = result.traversalPath.join(' ← ')\n const provenances = result.edgeProvenances.length\n ? result.edgeProvenances.join(', ')\n : '(direct, no edges traversed)'\n const summary =\n `Root cause for ${input.errorNode} is ${result.rootCauseNode}. ` +\n result.rootCauseReason +\n (result.fixRecommendation ? ` Recommended fix: ${result.fixRecommendation}.` : '')\n const blockLines = [\n `Traversal path: ${arrowPath}`,\n `Edge provenances: ${provenances}`,\n ]\n if (result.fixRecommendation) {\n blockLines.push(`Recommended fix: ${result.fixRecommendation}`)\n }\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: result.confidence,\n provenance: result.edgeProvenances.length ? result.edgeProvenances : undefined,\n })\n }, `No root cause found for ${input.errorNode}. The node may be healthy, or it may not exist in the graph.`)\n}\n\nexport interface BlastRadiusInput {\n nodeId: string\n depth?: number\n project?: string\n}\n\nexport async function getBlastRadius(\n client: HttpClient,\n input: BlastRadiusInput,\n): Promise<ToolResponse> {\n const qs = input.depth !== undefined ? `?depth=${input.depth}` : ''\n const path = projectPath(\n input.project,\n `/graph/blast-radius/${encodeURIComponent(input.nodeId)}${qs}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<BlastRadiusResult>(path)\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n `${result.origin} has no downstream dependencies. Nothing else would break if it failed.`,\n )\n }\n const sorted = [...result.affectedNodes].sort(\n (a, b) => a.distance - b.distance || a.nodeId.localeCompare(b.nodeId),\n )\n const blockLines = sorted.map(formatBlastEntry)\n // Worst-case confidence — the path with the lowest cascaded confidence\n // is the headline number; agents should treat this as \"what's the\n // weakest reachability NEAT actually knows about?\"\n const minConfidence = sorted.reduce(\n (m, n) => Math.min(m, n.confidence),\n Number.POSITIVE_INFINITY,\n )\n const provenances = [...new Set(sorted.map((n) => n.edgeProvenance))]\n return formatToolResponse({\n summary: `Blast radius for ${result.origin}: ${result.totalAffected} affected node${result.totalAffected === 1 ? '' : 's'} reachable downstream.`,\n block: blockLines.join('\\n'),\n confidence: Number.isFinite(minConfidence) ? minConfidence : undefined,\n provenance: provenances.length ? provenances : undefined,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction formatBlastEntry(n: BlastRadiusAffectedNode): string {\n const tag = n.edgeProvenance === Provenance.STALE ? ' [STALE — last seen too long ago]' : ''\n return ` • ${n.nodeId} (distance ${n.distance}, ${n.edgeProvenance})${tag}`\n}\n\ninterface EdgesResponse {\n inbound: GraphEdge[]\n outbound: GraphEdge[]\n}\n\nexport interface DependenciesInput {\n nodeId: string\n // BFS depth. Default 3; max 10. Direct-only consumers pass 1.\n depth?: number\n project?: string\n}\n\n// Transitive get_dependencies (issue #144). Calls the core endpoint\n// /graph/dependencies/:nodeId?depth=N which BFS-walks outbound. The output\n// groups results by hop so direct dependencies stand out from transitives —\n// agents asked \"what does X depend on?\" usually want the direct list with\n// transitives as context.\nexport async function getDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n const depth = input.depth ?? 3\n const path = projectPath(\n input.project,\n `/graph/dependencies/${encodeURIComponent(input.nodeId)}?depth=${depth}`,\n )\n\n return withMissingNodeFallback(async () => {\n const result = await client.get<TransitiveDependenciesResult>(path)\n if (result.total === 0) {\n return formatEmptyResponse(\n depth === 1\n ? `${input.nodeId} has no direct dependencies in the graph.`\n : `${input.nodeId} has no dependencies (BFS to depth ${depth}).`,\n )\n }\n // Group by distance so the structured block reads as concentric rings.\n const byDistance = new Map<number, typeof result.dependencies>()\n for (const dep of result.dependencies) {\n const ring = byDistance.get(dep.distance) ?? []\n ring.push(dep)\n byDistance.set(dep.distance, ring)\n }\n const blockLines: string[] = []\n for (const distance of [...byDistance.keys()].sort((a, b) => a - b)) {\n const label = distance === 1 ? 'Direct (distance 1)' : `Distance ${distance}`\n blockLines.push(`${label}:`)\n for (const dep of byDistance.get(distance)!) {\n blockLines.push(` • ${dep.nodeId} — ${dep.edgeType} (${dep.provenance})`)\n }\n }\n const provenances = [...new Set(result.dependencies.map((d) => d.provenance))]\n const directCount = byDistance.get(1)?.length ?? 0\n const summary =\n depth === 1\n ? `${input.nodeId} has ${directCount} direct dependenc${directCount === 1 ? 'y' : 'ies'}.`\n : `${input.nodeId} has ${result.total} dependenc${result.total === 1 ? 'y' : 'ies'} reachable to depth ${depth} (${directCount} direct).`\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n provenance: provenances,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport async function getObservedDependencies(\n client: HttpClient,\n input: DependenciesInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const edges = await client.get<EdgesResponse>(\n projectPath(input.project, `/graph/edges/${encodeURIComponent(input.nodeId)}`),\n )\n const observed = edges.outbound.filter((e) => e.provenance === Provenance.OBSERVED)\n if (observed.length === 0) {\n const hasExtracted = edges.outbound.some((e) => e.provenance === Provenance.EXTRACTED)\n const note = hasExtracted\n ? ' Static (EXTRACTED) dependencies exist but no runtime traffic has been seen — is OTel running?'\n : ''\n return formatEmptyResponse(`No OBSERVED dependencies for ${input.nodeId}.${note}`)\n }\n const blockLines = observed.map((e) => ` • ${e.target} — ${e.type}${edgeMeta(e)}`)\n return formatToolResponse({\n summary: `${input.nodeId} has ${observed.length} runtime dependenc${observed.length === 1 ? 'y' : 'ies'} confirmed by OTel.`,\n block: blockLines.join('\\n'),\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nfunction edgeMeta(e: GraphEdge): string {\n const bits: string[] = []\n if (e.signal) {\n // Prefer the runtime signal numbers — \"saw 1,247 calls, 3 errors\" reads\n // better than a derived 0.94 confidence.\n bits.push(`spans=${e.signal.spanCount}`)\n if (e.signal.errorCount > 0) bits.push(`errors=${e.signal.errorCount}`)\n if (e.signal.lastObservedAgeMs !== undefined) {\n bits.push(`age=${formatDuration(e.signal.lastObservedAgeMs)}`)\n }\n } else if (e.callCount !== undefined) {\n bits.push(`callCount=${e.callCount}`)\n }\n if (e.lastObserved) bits.push(`lastObserved=${e.lastObserved}`)\n if (e.confidence !== undefined) bits.push(`confidence=${e.confidence}`)\n return bits.length ? ` [${bits.join(', ')}]` : ''\n}\n\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n const s = Math.round(ms / 1000)\n if (s < 60) return `${s}s`\n const m = Math.round(s / 60)\n if (m < 60) return `${m}m`\n const h = Math.round(m / 60)\n if (h < 48) return `${h}h`\n return `${Math.round(h / 24)}d`\n}\n\nexport interface IncidentHistoryInput {\n nodeId: string\n limit?: number\n project?: string\n}\n\nexport async function getIncidentHistory(\n client: HttpClient,\n input: IncidentHistoryInput,\n): Promise<ToolResponse> {\n return withMissingNodeFallback(async () => {\n const body = await client.get<{ count: number; total: number; events: ErrorEvent[] }>(\n projectPath(input.project, `/incidents/${encodeURIComponent(input.nodeId)}`),\n )\n const events = body.events\n if (events.length === 0) {\n return formatEmptyResponse(`No incidents recorded against ${input.nodeId}.`)\n }\n // ndjson order is append-time = oldest first. Reverse so the most recent\n // event leads, then trim to the requested limit.\n const ordered = [...events].reverse().slice(0, input.limit ?? 20)\n const blockLines: string[] = []\n for (const ev of ordered) {\n blockLines.push(` ${ev.timestamp} — ${ev.service}: ${ev.errorMessage}`)\n blockLines.push(` trace=${ev.traceId} span=${ev.spanId}`)\n }\n return formatToolResponse({\n summary: `${input.nodeId} has ${body.total} recorded incident${body.total === 1 ? '' : 's'}; showing the ${ordered.length} most recent.`,\n block: blockLines.join('\\n'),\n // ErrorEvents are observation records, not graph edges — provenance is\n // OBSERVED by definition (the OTel span happened).\n provenance: Provenance.OBSERVED,\n })\n }, `Node ${input.nodeId} not found in the graph.`)\n}\n\nexport interface SemanticSearchInput {\n query: string\n project?: string\n}\n\ninterface SearchResponse {\n query: string\n provider?: 'ollama' | 'transformers' | 'substring'\n matches: (GraphNode & { score?: number })[]\n}\n\nexport async function semanticSearch(\n client: HttpClient,\n input: SemanticSearchInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<SearchResponse>(\n projectPath(input.project, `/search?q=${encodeURIComponent(input.query)}`),\n )\n if (result.matches.length === 0) {\n return formatEmptyResponse(`No matches for \"${input.query}\".`)\n }\n const provider = result.provider ?? 'substring'\n const blockLines: string[] = []\n let topScore: number | undefined\n for (const n of result.matches) {\n // Embedding tiers attach a cosine score in [0,1]; substring fallback\n // doesn't, so we elide the score when it's the placeholder 1.\n const score = provider !== 'substring' && typeof n.score === 'number' ? n.score : undefined\n const scoreBit = score !== undefined ? ` [score=${score.toFixed(2)}]` : ''\n if (score !== undefined && (topScore === undefined || score > topScore)) topScore = score\n blockLines.push(\n ` • ${n.id} (${n.type}) — ${(n as { name?: string }).name ?? n.id}${scoreBit}`,\n )\n }\n return formatToolResponse({\n summary: `Found ${result.matches.length} match${result.matches.length === 1 ? '' : 'es'} for \"${input.query}\" via ${provider} provider.`,\n block: blockLines.join('\\n'),\n // Top similarity score doubles as a \"how confident is the embedder\n // about the best match\" signal. Substring provider returns no score —\n // the footer shows n/a in that case.\n confidence: topScore,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface GraphDiffInput {\n againstSnapshot: string\n project?: string\n}\n\ninterface GraphDiffResponse {\n base: { exportedAt?: string }\n current: { exportedAt: string }\n added: { nodes: GraphNode[]; edges: GraphEdge[] }\n removed: { nodes: GraphNode[]; edges: GraphEdge[] }\n changed: {\n nodes: { id: string; before: GraphNode; after: GraphNode }[]\n edges: { id: string; before: GraphEdge; after: GraphEdge }[]\n }\n}\n\nexport async function getGraphDiff(\n client: HttpClient,\n input: GraphDiffInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<GraphDiffResponse>(\n projectPath(\n input.project,\n `/graph/diff?against=${encodeURIComponent(input.againstSnapshot)}`,\n ),\n )\n const total =\n result.added.nodes.length +\n result.added.edges.length +\n result.removed.nodes.length +\n result.removed.edges.length +\n result.changed.nodes.length +\n result.changed.edges.length\n const baseLabel = result.base.exportedAt ?? 'unknown'\n if (total === 0) {\n return formatEmptyResponse(\n `No differences between the current graph and ${input.againstSnapshot} (base exportedAt=${baseLabel}).`,\n )\n }\n const blockLines: string[] = [\n ` base exportedAt: ${baseLabel}`,\n ` current exportedAt: ${result.current.exportedAt}`,\n '',\n ]\n if (result.added.nodes.length || result.added.edges.length) {\n blockLines.push('Added:')\n for (const n of result.added.nodes) blockLines.push(` + node ${n.id} (${n.type})`)\n for (const e of result.added.edges)\n blockLines.push(` + edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.removed.nodes.length || result.removed.edges.length) {\n blockLines.push('Removed:')\n for (const n of result.removed.nodes) blockLines.push(` - node ${n.id} (${n.type})`)\n for (const e of result.removed.edges)\n blockLines.push(` - edge ${e.id} — ${e.source} -> ${e.target} (${e.type}, ${e.provenance})`)\n blockLines.push('')\n }\n if (result.changed.nodes.length || result.changed.edges.length) {\n blockLines.push('Changed:')\n for (const c of result.changed.nodes) {\n blockLines.push(` ~ node ${c.id} — ${summariseAttrDiff(c.before, c.after)}`)\n }\n for (const c of result.changed.edges) {\n const provBit =\n c.before.provenance !== c.after.provenance\n ? `provenance ${c.before.provenance} → ${c.after.provenance}`\n : summariseAttrDiff(c.before, c.after)\n blockLines.push(` ~ edge ${c.id} — ${provBit}`)\n }\n }\n return formatToolResponse({\n summary: `Diff against ${input.againstSnapshot}: ${total} change${total === 1 ? '' : 's'} between the snapshot and the live graph.`,\n block: blockLines.join('\\n').trimEnd(),\n // Diff results don't have a per-result provenance — the diff spans\n // every edge type and provenance kind. Footer shows n/a.\n })\n } catch (err) {\n if (err instanceof HttpError && err.status === 400) {\n return formatErrorResponse(\n `Could not load snapshot ${input.againstSnapshot}: ${err.message}`,\n )\n }\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nfunction summariseAttrDiff(\n before: Record<string, unknown>,\n after: Record<string, unknown>,\n): string {\n const keys = new Set([...Object.keys(before), ...Object.keys(after)])\n const changed: string[] = []\n for (const k of keys) {\n if (JSON.stringify(before[k]) !== JSON.stringify(after[k])) changed.push(k)\n }\n return changed.length === 0\n ? 'attributes differ'\n : `fields changed: ${changed.sort().join(', ')}`\n}\n\nexport interface RecentStaleEdgesInput {\n limit?: number\n edgeType?: string\n project?: string\n}\n\ninterface StaleEventResponse {\n edgeId: string\n source: string\n target: string\n edgeType: string\n thresholdMs: number\n ageMs: number\n lastObserved: string\n transitionedAt: string\n}\n\nexport async function getRecentStaleEdges(\n client: HttpClient,\n input: RecentStaleEdgesInput,\n): Promise<ToolResponse> {\n const params = new URLSearchParams()\n if (input.limit !== undefined) params.set('limit', String(input.limit))\n if (input.edgeType) params.set('edgeType', input.edgeType)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n\n try {\n const body = await client.get<{ count: number; total: number; events: StaleEventResponse[] }>(\n projectPath(input.project, `/stale-events${qs}`),\n )\n const events = body.events\n if (events.length === 0) {\n return formatEmptyResponse(\n input.edgeType\n ? `No stale ${input.edgeType} edges recorded.`\n : 'No stale-edge transitions recorded yet.',\n )\n }\n const blockLines = events.map(\n (e) =>\n ` ${e.transitionedAt} — ${e.source} -[${e.edgeType}]-> ${e.target}` +\n ` (last seen ${e.lastObserved}, threshold ${formatDuration(e.thresholdMs)})`,\n )\n return formatToolResponse({\n summary: `${events.length} stale-edge transition${events.length === 1 ? '' : 's'} recorded${input.edgeType ? ` for ${input.edgeType}` : ''}.`,\n block: blockLines.join('\\n'),\n // STALE by definition — every event is a transition into STALE.\n provenance: Provenance.STALE,\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nexport interface CheckPoliciesInput {\n // 'all' (default) returns every current violation. 'unresolved' is reserved\n // for future resolution tracking — for the MVP it behaves the same as 'all'.\n // { policyId } narrows to violations of one named policy.\n scope?: 'all' | 'unresolved' | { policyId: string }\n // When provided, dry-run evaluation: return violations that *would* result\n // if the action were applied. Without it, return current violations.\n hypotheticalAction?: HypotheticalAction\n project?: string\n}\n\ninterface PoliciesCheckResponse {\n allowed: boolean\n hypotheticalAction?: HypotheticalAction\n violations: PolicyViolation[]\n}\n\n// check_policies — single MCP tool covering both state-read and dry-run modes\n// per ADR-045. The contract explicitly rejects the audit's two-tool split\n// (evaluate_policy + get_policy_violations); both modes route through here.\nexport async function checkPolicies(\n client: HttpClient,\n input: CheckPoliciesInput,\n): Promise<ToolResponse> {\n try {\n let violations: PolicyViolation[]\n let allowed = true\n let hypothetical: HypotheticalAction | undefined\n\n if (input.hypotheticalAction) {\n // Dry-run via POST /policies/check.\n const body = await postJson<PoliciesCheckResponse>(\n client,\n projectPath(input.project, '/policies/check'),\n { hypotheticalAction: input.hypotheticalAction },\n )\n violations = body.violations\n allowed = body.allowed\n hypothetical = body.hypotheticalAction\n } else {\n // State read via GET /policies/violations. Optional scope filters via\n // ?policyId=, severity isn't surfaced in the tool input today.\n const qsParams = new URLSearchParams()\n if (typeof input.scope === 'object' && 'policyId' in input.scope) {\n qsParams.set('policyId', input.scope.policyId)\n }\n const qs = qsParams.size > 0 ? `?${qsParams.toString()}` : ''\n const body = await client.get<{ violations: PolicyViolation[] }>(\n projectPath(input.project, `/policies/violations${qs}`),\n )\n violations = body.violations\n allowed = violations.every((v) => v.onViolation !== 'block')\n }\n\n if (violations.length === 0) {\n return formatEmptyResponse(\n hypothetical\n ? `No violations would result from the hypothetical action (${hypothetical.kind}).`\n : 'No policy violations recorded.',\n )\n }\n\n const blockCount = violations.filter((v) => v.onViolation === 'block').length\n const summaryParts: string[] = []\n if (hypothetical) {\n summaryParts.push(\n `Hypothetical ${hypothetical.kind} would surface ${violations.length} violation${violations.length === 1 ? '' : 's'}`,\n )\n } else {\n summaryParts.push(\n `${violations.length} policy violation${violations.length === 1 ? '' : 's'} currently recorded`,\n )\n }\n if (blockCount > 0) {\n summaryParts.push(`${blockCount} of which block`)\n }\n if (!allowed && hypothetical) {\n summaryParts.push('action denied')\n }\n const summary = summaryParts.join('; ') + '.'\n\n const blockLines = violations.map((v) => {\n const subject = v.subject.nodeId ?? v.subject.edgeId ?? v.subject.path?.[0] ?? '(global)'\n return ` • [${v.severity}/${v.onViolation}] ${v.policyName}: ${v.message} — ${subject}`\n })\n const severities = [...new Set(violations.map((v) => v.severity))]\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n // Confidence: hypothetical results inherit a 0.7 cap (the engine\n // can't fully simulate every action shape in MVP); confirmed\n // violations report 1.00 since the engine ran against current state.\n confidence: hypothetical ? 0.7 : 1,\n provenance: severities.join(' '),\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// get_divergences (ADR-060) — the thesis surface\n// ──────────────────────────────────────────────────────────────────────────\n\nexport interface DivergencesInput {\n type?: ReadonlyArray<DivergenceType>\n minConfidence?: number\n node?: string\n project?: string\n}\n\nfunction buildDivergencesPath(input: DivergencesInput): string {\n const params = new URLSearchParams()\n if (input.type && input.type.length > 0) params.set('type', input.type.join(','))\n if (input.minConfidence !== undefined) {\n params.set('minConfidence', String(input.minConfidence))\n }\n if (input.node) params.set('node', input.node)\n const qs = params.size > 0 ? `?${params.toString()}` : ''\n return projectPath(input.project, `/graph/divergences${qs}`)\n}\n\nfunction formatDivergenceLine(d: Divergence): string {\n switch (d.type) {\n case 'missing-observed':\n return ` • [${d.type}] ${d.source} → ${d.target} (${d.edgeType}) — confidence ${d.confidence.toFixed(2)}`\n case 'missing-extracted':\n return ` • [${d.type}] ${d.source} → ${d.target} (${d.edgeType}) — confidence ${d.confidence.toFixed(2)}`\n case 'version-mismatch':\n return ` • [${d.type}] ${d.source} → ${d.target} — declared ${d.extractedVersion}, observed engine ${d.observedVersion} (${d.compatibility})`\n case 'host-mismatch':\n return ` • [${d.type}] ${d.source} → ${d.target} — declared host ${d.extractedHost}, observed host ${d.observedHost}`\n case 'compat-violation':\n return ` • [${d.type}] ${d.source} → ${d.target} — ${d.rule.kind}${d.rule.package ? ` (${d.rule.package})` : ''}`\n }\n}\n\nexport async function getDivergences(\n client: HttpClient,\n input: DivergencesInput,\n): Promise<ToolResponse> {\n try {\n const result = await client.get<DivergenceResult>(buildDivergencesPath(input))\n if (result.totalAffected === 0) {\n return formatEmptyResponse(\n 'No divergences found between the declared (EXTRACTED) and observed (OBSERVED) views of the graph.',\n )\n }\n // Sorted by confidence descending already; first entry is the headline.\n const headline = result.divergences[0]!\n const summary =\n `Found ${result.totalAffected} divergence${result.totalAffected === 1 ? '' : 's'} between code and production. ` +\n `Highest-confidence: ${headline.type} on ${headline.source} → ${headline.target}. ${headline.reason}`\n const blockLines: string[] = []\n for (const d of result.divergences) {\n blockLines.push(formatDivergenceLine(d))\n blockLines.push(` reason: ${d.reason}`)\n blockLines.push(` recommendation: ${d.recommendation}`)\n }\n const maxConfidence = result.divergences.reduce(\n (m, d) => Math.max(m, d.confidence),\n 0,\n )\n return formatToolResponse({\n summary,\n block: blockLines.join('\\n'),\n confidence: maxConfidence,\n // Composite provenance — divergences sit between EXTRACTED and\n // OBSERVED by construction; that's what makes them divergences.\n provenance: 'composite (EXTRACTED + OBSERVED)',\n })\n } catch (err) {\n return formatErrorResponse(`Error talking to neat-core: ${(err as Error).message}`)\n }\n}\n\nasync function postJson<T>(\n client: HttpClient,\n path: string,\n body: unknown,\n): Promise<T> {\n // The base HttpClient interface only exposes get(). For POST we need to\n // reach into the underlying transport. Most callers pass the client built\n // by createHttpClient which has post; types are kept minimal so test\n // stubs don't have to implement post unless the tool needs it.\n const c = client as HttpClient & { post?: <U>(p: string, b: unknown) => Promise<U> }\n if (typeof c.post !== 'function') {\n throw new Error('HttpClient does not support POST — required for check_policies dry-run')\n }\n return c.post<T>(path, body)\n}\n","// Standardized three-part response format for every MCP tool (ADR-039,\n// issue #143). Output shape:\n//\n// {summary — NL paragraph: what was found, why it matters}\n//\n// {block — typed payload, formatted}\n//\n// confidence: 0.94 · provenance: OBSERVED\n//\n// Empty result → footer reads \"confidence: n/a · provenance: n/a\". Every tool\n// in packages/mcp/src/tools.ts routes through this helper so consumers get a\n// consistent shape — agents can pattern-match on the footer to know how much\n// to trust the answer.\n\nexport interface ToolResponse {\n [x: string]: unknown\n content: { type: 'text'; text: string }[]\n isError?: boolean\n}\n\nexport interface FormatToolResponseInput {\n // NL paragraph. One or two sentences. What was found and why it matters.\n summary: string\n // Structured block. The formatted typed payload — usually a bullet list,\n // sometimes a multi-section breakdown. May be empty when the summary\n // already conveys everything.\n block?: string\n // Per-result confidence in [0, 1]. Undefined → footer reads \"n/a\".\n confidence?: number\n // Per-result provenance. Single value, or an array if the result spans\n // mixed provenances (e.g. a path of OBSERVED + EXTRACTED edges). Undefined\n // → footer reads \"n/a\".\n provenance?: string | string[]\n // Set on transport / 5xx errors. Routes through ToolResponse.isError so\n // MCP clients can surface a non-\"normal\" return.\n isError?: boolean\n}\n\nfunction formatFooter(\n confidence: number | undefined,\n provenance: string | string[] | undefined,\n): string {\n const c = confidence === undefined ? 'n/a' : confidence.toFixed(2)\n const p =\n provenance === undefined\n ? 'n/a'\n : Array.isArray(provenance)\n ? [...new Set(provenance)].join(', ')\n : provenance\n return `confidence: ${c} · provenance: ${p}`\n}\n\nexport function formatToolResponse(input: FormatToolResponseInput): ToolResponse {\n const sections: string[] = [input.summary.trim()]\n if (input.block && input.block.trim().length > 0) {\n sections.push(input.block.trimEnd())\n }\n sections.push(formatFooter(input.confidence, input.provenance))\n const text = sections.join('\\n\\n')\n return {\n content: [{ type: 'text', text }],\n ...(input.isError ? { isError: true } : {}),\n }\n}\n\n// Convenience for the \"node not found / empty graph\" path. Keeps the\n// three-part shape (summary still landed) but sets the footer to n/a / n/a\n// since there's nothing to confidence-tag or provenance-tag.\nexport function formatEmptyResponse(summary: string): ToolResponse {\n return formatToolResponse({ summary })\n}\n\n// Convenience for transport / 5xx errors at the MCP boundary. isError set\n// so MCP clients route the response into their error path.\nexport function formatErrorResponse(message: string): ToolResponse {\n return formatToolResponse({ summary: message, isError: true })\n}\n"],"mappings":";;;AAEA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;AAClB,SAAS,0BAA0B,gCAAgC;;;ACM5D,SAAS,iBAAiBA,UAA6B;AAC5D,QAAM,OAAOA,SAAQ,QAAQ,OAAO,EAAE;AACtC,SAAO;AAAA,IACL,MAAM,IAAO,MAA0B;AACrC,YAAM,MAAM,MAAM,MAAM,GAAG,IAAI,GAAG,IAAI,EAAE;AACxC,UAAI,CAAC,IAAI,IAAI;AACX,cAAM,OAAO,MAAM,IAAI,KAAK,EAAE,MAAM,MAAM,EAAE;AAC5C,cAAM,IAAI,UAAU,IAAI,QAAQ,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU,WAAW,I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AAO,UACL,eAAe,QAAQ,EAAE,GAAG,OAAO,SAAS,WAAW,KAAK,EAAE,CAAC;AACnE;AAEA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,IACE,OAAO,yBAAyB,SAAS,EAAE;AAAA,MACzC;AAAA,IACF;AAAA,IACA,oBAAoB,yBAAyB,SAAS,EAAE;AAAA,MACtD;AAAA,IACF;AAAA,IACA,SAAS;AAAA,EACX;AAAA,EACA,OAAO,UACL,cAAc,QAAQ;AAAA,IACpB,GAAG;AAAA,IACH,SAAS,WAAW,KAAK;AAAA,EAC3B,CAAwC;AAC5C;AAMA,IAAM,kBAAkB,QAAQ,IAAI,wBAChC,OAAO,QAAQ,IAAI,qBAAqB,IACxC;AACJ,IAAM,uBAAuB,kBAAkB,QAAQ,QAAQ;AAAA,EAC7D,GAAI,oBAAoB,SAAY,EAAE,gBAAgB,IAAI,CAAC;AAAA,EAC3D,GAAI,iBAAiB,EAAE,SAAS,eAAe,IAAI,CAAC;AACtD,CAAC;AAED,eAAe,OAAsB;AACnC,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,IAAM,cAAc,MAAY;AAC9B,uBAAqB,KAAK;AAC5B;AACA,QAAQ,GAAG,WAAW,WAAW;AACjC,QAAQ,GAAG,UAAU,WAAW;AAEhC,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["baseUrl","client","server","client"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neat.is/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "NEAT MCP server: exposes graph queries to AI agents over stdio",
|
|
5
5
|
"license": "BUSL-1.1",
|
|
6
6
|
"homepage": "https://neat.is",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
44
|
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
45
|
-
"@neat.is/types": "^0.
|
|
45
|
+
"@neat.is/types": "^0.3.0",
|
|
46
46
|
"zod": "^3.23.8"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|