@daogee/mdgraph 1.0.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/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README-ZH.md +203 -0
- package/README.md +203 -0
- package/agent-pack/README.md +26 -0
- package/agent-pack/host-examples.md +71 -0
- package/agent-pack/mcp-config.example.json +14 -0
- package/agent-pack/mdgraph-agent-instructions.md +21 -0
- package/agent-pack/prompts/relationship-trace.md +12 -0
- package/agent-pack/prompts/status-doctor.md +13 -0
- package/agent-pack/prompts/task-start-context.md +15 -0
- package/dist/analysis/doctor-scope.d.ts +8 -0
- package/dist/analysis/doctor-scope.js +109 -0
- package/dist/analysis/doctor.d.ts +148 -0
- package/dist/analysis/doctor.js +919 -0
- package/dist/analysis/status-freshness.d.ts +13 -0
- package/dist/analysis/status-freshness.js +55 -0
- package/dist/benchmark/benchmark.d.ts +118 -0
- package/dist/benchmark/benchmark.js +357 -0
- package/dist/bin/mdgraph.d.ts +2 -0
- package/dist/bin/mdgraph.js +877 -0
- package/dist/bundle/bundle.d.ts +66 -0
- package/dist/bundle/bundle.js +320 -0
- package/dist/config/limits.d.ts +24 -0
- package/dist/config/limits.js +24 -0
- package/dist/config/load-config.d.ts +14 -0
- package/dist/config/load-config.js +177 -0
- package/dist/db/connection.d.ts +15 -0
- package/dist/db/connection.js +145 -0
- package/dist/db/repositories.d.ts +159 -0
- package/dist/db/repositories.js +929 -0
- package/dist/db/schema.sql +110 -0
- package/dist/db/sqlite-adapter.d.ts +18 -0
- package/dist/db/sqlite-adapter.js +60 -0
- package/dist/diff/graph-diff.d.ts +41 -0
- package/dist/diff/graph-diff.js +334 -0
- package/dist/evaluation/retrieval-eval.d.ts +115 -0
- package/dist/evaluation/retrieval-eval.js +399 -0
- package/dist/export/diagram.d.ts +11 -0
- package/dist/export/diagram.js +41 -0
- package/dist/export/graphjson.d.ts +89 -0
- package/dist/export/graphjson.js +299 -0
- package/dist/export/markdown-index.d.ts +21 -0
- package/dist/export/markdown-index.js +89 -0
- package/dist/export/source-bridge.d.ts +22 -0
- package/dist/export/source-bridge.js +83 -0
- package/dist/extraction/entity-extractor.d.ts +12 -0
- package/dist/extraction/entity-extractor.js +153 -0
- package/dist/extraction/graph-builder.d.ts +2 -0
- package/dist/extraction/graph-builder.js +168 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.js +28 -0
- package/dist/indexer.d.ts +19 -0
- package/dist/indexer.js +100 -0
- package/dist/mcp/debug.d.ts +7 -0
- package/dist/mcp/debug.js +41 -0
- package/dist/mcp/server-instructions.d.ts +2 -0
- package/dist/mcp/server-instructions.js +40 -0
- package/dist/mcp/server.d.ts +28 -0
- package/dist/mcp/server.js +232 -0
- package/dist/mcp/tools.d.ts +31 -0
- package/dist/mcp/tools.js +506 -0
- package/dist/mcp/transport.d.ts +50 -0
- package/dist/mcp/transport.js +88 -0
- package/dist/parser/frontmatter.d.ts +10 -0
- package/dist/parser/frontmatter.js +191 -0
- package/dist/parser/links.d.ts +6 -0
- package/dist/parser/links.js +9 -0
- package/dist/parser/markdown-parser.d.ts +2 -0
- package/dist/parser/markdown-parser.js +267 -0
- package/dist/query/context-builder.d.ts +85 -0
- package/dist/query/context-builder.js +413 -0
- package/dist/query/search.d.ts +32 -0
- package/dist/query/search.js +237 -0
- package/dist/query/trace.d.ts +10 -0
- package/dist/query/trace.js +55 -0
- package/dist/reporting/report.d.ts +49 -0
- package/dist/reporting/report.js +143 -0
- package/dist/resolution/link-resolver.d.ts +17 -0
- package/dist/resolution/link-resolver.js +113 -0
- package/dist/scanner/file-scanner.d.ts +4 -0
- package/dist/scanner/file-scanner.js +144 -0
- package/dist/semantic/local-embedding.d.ts +4 -0
- package/dist/semantic/local-embedding.js +30 -0
- package/dist/semantic/status.d.ts +19 -0
- package/dist/semantic/status.js +70 -0
- package/dist/semantic/vector-codec.d.ts +3 -0
- package/dist/semantic/vector-codec.js +35 -0
- package/dist/types.d.ts +198 -0
- package/dist/types.js +15 -0
- package/dist/utils/bounded-json.d.ts +9 -0
- package/dist/utils/bounded-json.js +57 -0
- package/dist/utils/content-risk.d.ts +5 -0
- package/dist/utils/content-risk.js +20 -0
- package/dist/utils/fts.d.ts +3 -0
- package/dist/utils/fts.js +52 -0
- package/dist/utils/id.d.ts +2 -0
- package/dist/utils/id.js +8 -0
- package/dist/utils/path-safety.d.ts +4 -0
- package/dist/utils/path-safety.js +25 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.js +36 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +11 -0
- package/dist/watcher/file-watcher.d.ts +11 -0
- package/dist/watcher/file-watcher.js +127 -0
- package/docs/EN/Agent_Integration.md +129 -0
- package/docs/EN/Architecture.md +135 -0
- package/docs/EN/Evaluation_Questions.md +68 -0
- package/docs/EN/Output_Contracts.md +274 -0
- package/docs/EN/Public_Contracts.md +88 -0
- package/docs/EN/Public_Contracts_1.0.md +234 -0
- package/docs/EN/Release_Checklist.md +82 -0
- package/docs/ZH/Agent_Integration.md +105 -0
- package/docs/ZH/Architecture.md +124 -0
- package/docs/ZH/Evaluation_Questions.md +66 -0
- package/docs/ZH/Output_Contracts.md +269 -0
- package/docs/ZH/Public_Contracts.md +81 -0
- package/docs/ZH/Public_Contracts_1.0.md +202 -0
- package/docs/ZH/Release_Checklist.md +83 -0
- package/package.json +94 -0
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { computeStatusFreshness } from "../analysis/status-freshness.js";
|
|
4
|
+
import { MCP_LIMITS } from "../config/limits.js";
|
|
5
|
+
import { databasePath, loadConfig } from "../config/load-config.js";
|
|
6
|
+
import { openExistingDatabase } from "../db/connection.js";
|
|
7
|
+
import { GraphRepository } from "../db/repositories.js";
|
|
8
|
+
import { buildContext } from "../query/context-builder.js";
|
|
9
|
+
import { searchGraph } from "../query/search.js";
|
|
10
|
+
import { traceNodes } from "../query/trace.js";
|
|
11
|
+
import { isPathInsideOrEqual } from "../utils/path-safety.js";
|
|
12
|
+
export class McpInputError extends Error {
|
|
13
|
+
name = "McpInputError";
|
|
14
|
+
}
|
|
15
|
+
export const tools = [
|
|
16
|
+
{
|
|
17
|
+
name: "mdgraph_search",
|
|
18
|
+
description: "Search indexed Markdown documents, sections, and entities. Use before grep/read_file for docs keyword, entity, path, command, config key, API route, or error-code lookup. Fall back to raw search only for exact text not found in MDGraph or when the index is unavailable/stale for the task.",
|
|
19
|
+
inputSchema: {
|
|
20
|
+
type: "object",
|
|
21
|
+
additionalProperties: false,
|
|
22
|
+
required: ["query"],
|
|
23
|
+
properties: {
|
|
24
|
+
query: { type: "string", description: "Search query, keyword, or entity name." },
|
|
25
|
+
limit: { type: "number", description: "Maximum result count." },
|
|
26
|
+
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: "mdgraph_context",
|
|
32
|
+
description: "PRIMARY documentation tool. Build an explainable task-start documentation brief for architecture, roadmap, CLI/MCP contract, release, runbook, ADR, source-ref, or other cross-document questions. Use first before reading multiple Markdown docs manually.",
|
|
33
|
+
inputSchema: {
|
|
34
|
+
type: "object",
|
|
35
|
+
additionalProperties: false,
|
|
36
|
+
required: ["query"],
|
|
37
|
+
properties: {
|
|
38
|
+
query: { type: "string", description: "Question or topic to gather document context for." },
|
|
39
|
+
knownFiles: {
|
|
40
|
+
type: "array",
|
|
41
|
+
items: { type: "string" },
|
|
42
|
+
description: "Optional known project-relative document or source paths to seed the task-start brief."
|
|
43
|
+
},
|
|
44
|
+
maxChars: { type: "number", description: "Optional character budget for the returned context package." },
|
|
45
|
+
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
name: "mdgraph_node",
|
|
51
|
+
description: "Show details for a known document, section anchor, entity, source reference, chunk, or graph id after search/context narrows the target.",
|
|
52
|
+
inputSchema: {
|
|
53
|
+
type: "object",
|
|
54
|
+
additionalProperties: false,
|
|
55
|
+
required: ["query"],
|
|
56
|
+
properties: {
|
|
57
|
+
query: { type: "string", description: "Document title/path, entity name, source path, or graph node id." },
|
|
58
|
+
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
name: "mdgraph_trace",
|
|
64
|
+
description: "Trace an explainable relationship path between two indexed documents, entities, or source references.",
|
|
65
|
+
inputSchema: {
|
|
66
|
+
type: "object",
|
|
67
|
+
additionalProperties: false,
|
|
68
|
+
required: ["from", "to"],
|
|
69
|
+
properties: {
|
|
70
|
+
from: { type: "string", description: "Start document, entity, source path, or node id." },
|
|
71
|
+
to: { type: "string", description: "End document, entity, source path, or node id." },
|
|
72
|
+
depth: { type: "number", description: "Maximum graph depth. Defaults to 6." },
|
|
73
|
+
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
name: "mdgraph_status",
|
|
79
|
+
description: "Show whether the MDGraph index is available, plus graph counts and database path. Use first when index availability is unclear.",
|
|
80
|
+
inputSchema: {
|
|
81
|
+
type: "object",
|
|
82
|
+
additionalProperties: false,
|
|
83
|
+
properties: {
|
|
84
|
+
projectPath: { type: "string", description: "Optional project root inside the served root. Defaults to server cwd." }
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
];
|
|
89
|
+
export class ToolHandler {
|
|
90
|
+
defaultProjectRoot;
|
|
91
|
+
boundProjectRoot;
|
|
92
|
+
constructor(defaultProjectRoot = process.cwd(), boundProjectRoot = defaultProjectRoot) {
|
|
93
|
+
this.boundProjectRoot = validatedProjectRoot(path.resolve(boundProjectRoot));
|
|
94
|
+
this.defaultProjectRoot = validatedProjectRoot(path.resolve(defaultProjectRoot));
|
|
95
|
+
if (!isPathInsideOrEqual(this.boundProjectRoot, this.defaultProjectRoot)) {
|
|
96
|
+
throw new McpInputError(`Default project root must stay inside served root: ${this.boundProjectRoot}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
getTools() {
|
|
100
|
+
return tools;
|
|
101
|
+
}
|
|
102
|
+
execute(name, args = {}) {
|
|
103
|
+
const projectRoot = resolveProjectRoot(args.projectPath, this.defaultProjectRoot, this.boundProjectRoot);
|
|
104
|
+
if (name === "mdgraph_status") {
|
|
105
|
+
if (!hasIndex(projectRoot)) {
|
|
106
|
+
return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
|
|
107
|
+
}
|
|
108
|
+
return this.withRepository(projectRoot, (repository) => {
|
|
109
|
+
const counts = repository.counts();
|
|
110
|
+
const freshness = safeFreshness(projectRoot, repository);
|
|
111
|
+
return textResult(formatStatus(projectRoot, counts, freshness), { projectRoot, indexed: true, counts, freshness });
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
if (!hasIndex(projectRoot)) {
|
|
115
|
+
return textResult(unindexedMessage(projectRoot), { projectRoot, indexed: false });
|
|
116
|
+
}
|
|
117
|
+
switch (name) {
|
|
118
|
+
case "mdgraph_search":
|
|
119
|
+
return this.withRepository(projectRoot, (repository) => {
|
|
120
|
+
const config = loadConfig(projectRoot);
|
|
121
|
+
const query = requiredString(args.query, "query");
|
|
122
|
+
const counts = repository.counts();
|
|
123
|
+
const hasManualLimit = args.limit !== undefined && args.limit !== null;
|
|
124
|
+
const autoMode = agentSearchMode(config, counts, query);
|
|
125
|
+
const limit = hasManualLimit ? optionalBoundedPositiveInteger(args.limit, config.search.defaultLimit, "limit", MCP_LIMITS.searchLimit) : autoMode.limit;
|
|
126
|
+
const results = searchGraph(repository, config, query, limit);
|
|
127
|
+
const mode = hasManualLimit ? { name: "manual", limit, reason: "explicit limit argument" } : autoMode;
|
|
128
|
+
const freshness = safeFreshness(projectRoot, repository, config);
|
|
129
|
+
return withFreshnessNotice(textResult(formatSearch(results), { projectRoot, query, mode, results }), freshness);
|
|
130
|
+
});
|
|
131
|
+
case "mdgraph_context":
|
|
132
|
+
return this.withRepository(projectRoot, (repository) => {
|
|
133
|
+
const config = loadConfig(projectRoot);
|
|
134
|
+
const query = requiredString(args.query, "query");
|
|
135
|
+
const knownFiles = optionalStringArray(args.knownFiles, "knownFiles");
|
|
136
|
+
const hasManualMaxChars = args.maxChars !== undefined && args.maxChars !== null;
|
|
137
|
+
const requestedMaxChars = optionalBoundedPositiveInteger(args.maxChars, config.search.maxContextChars, "maxChars", MCP_LIMITS.contextMaxChars);
|
|
138
|
+
const mode = agentContextMode(config, repository.counts(), query, knownFiles, hasManualMaxChars ? requestedMaxChars : undefined);
|
|
139
|
+
const context = buildContext(repository, config, query, {
|
|
140
|
+
knownFiles,
|
|
141
|
+
maxChars: mode.maxChars,
|
|
142
|
+
searchLimit: mode.searchLimit,
|
|
143
|
+
maxDepth: mode.maxDepth,
|
|
144
|
+
mode
|
|
145
|
+
});
|
|
146
|
+
const freshness = safeFreshness(projectRoot, repository, config);
|
|
147
|
+
return withFreshnessNotice(textResult(formatContext(context), { projectRoot, context }), freshness);
|
|
148
|
+
});
|
|
149
|
+
case "mdgraph_node":
|
|
150
|
+
return this.withRepository(projectRoot, (repository) => {
|
|
151
|
+
const query = requiredString(args.query, "query");
|
|
152
|
+
const resolution = repository.resolveNodeDetailed(query);
|
|
153
|
+
const freshness = safeFreshness(projectRoot, repository);
|
|
154
|
+
if (resolution.status === "not_found") {
|
|
155
|
+
return withFreshnessNotice(textResult(`Node not found: ${query}`, { projectRoot, query, error: resolution.error, node: null }), freshness);
|
|
156
|
+
}
|
|
157
|
+
if (resolution.status === "ambiguous") {
|
|
158
|
+
return withFreshnessNotice(textResult(formatAmbiguousNodeQuery(resolution), { projectRoot, query, error: resolution.error, candidates: resolution.candidates, node: null }), freshness);
|
|
159
|
+
}
|
|
160
|
+
return withFreshnessNotice(textResult(formatNode(resolution.node, repository), { projectRoot, node: resolution.node }), freshness);
|
|
161
|
+
});
|
|
162
|
+
case "mdgraph_trace":
|
|
163
|
+
return this.withRepository(projectRoot, (repository) => {
|
|
164
|
+
const from = requiredString(args.from, "from");
|
|
165
|
+
const to = requiredString(args.to, "to");
|
|
166
|
+
const depth = optionalBoundedPositiveInteger(args.depth, 6, "depth", MCP_LIMITS.traceDepth);
|
|
167
|
+
const trace = traceNodes(repository, from, to, depth);
|
|
168
|
+
const freshness = safeFreshness(projectRoot, repository);
|
|
169
|
+
return withFreshnessNotice(textResult(formatTrace(trace), { projectRoot, trace }), freshness);
|
|
170
|
+
});
|
|
171
|
+
default:
|
|
172
|
+
return { ...textResult(`Unknown MDGraph tool: ${name}`, { name }), isError: true };
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
withRepository(projectRoot, fn) {
|
|
176
|
+
const repository = new GraphRepository(openExistingDatabase(projectRoot));
|
|
177
|
+
try {
|
|
178
|
+
return fn(repository);
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
repository.close();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export function hasIndex(projectRoot) {
|
|
186
|
+
return fs.existsSync(databasePath(projectRoot));
|
|
187
|
+
}
|
|
188
|
+
function textResult(text, structuredContent) {
|
|
189
|
+
return {
|
|
190
|
+
content: [{ type: "text", text }],
|
|
191
|
+
structuredContent
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
function formatStatus(projectRoot, counts, freshness) {
|
|
195
|
+
const database = databasePath(projectRoot);
|
|
196
|
+
return [
|
|
197
|
+
"MDGraph index status: active",
|
|
198
|
+
`Project: ${projectRoot}`,
|
|
199
|
+
`Database: ${database}`,
|
|
200
|
+
`Freshness: ${freshness.state} - ${freshness.recommendation}`,
|
|
201
|
+
freshness.lastIndexedAt ? `Last indexed: ${freshness.lastIndexedAt}` : "Last indexed: unavailable",
|
|
202
|
+
freshness.issues?.length ? `Stale issues: ${freshness.issues.slice(0, 5).map((issue) => `${issue.path}:${issue.reason}`).join(", ")}` : "Stale issues: none",
|
|
203
|
+
`Documents: ${counts.documents}`,
|
|
204
|
+
`Sections: ${counts.sections}`,
|
|
205
|
+
`Entities: ${counts.entities}`,
|
|
206
|
+
`Source refs: ${counts.sourceRefs}`,
|
|
207
|
+
`Edges: ${counts.edges}`,
|
|
208
|
+
`Chunks: ${counts.chunks}`,
|
|
209
|
+
`Vectors: ${counts.vectors}`
|
|
210
|
+
].join("\n");
|
|
211
|
+
}
|
|
212
|
+
function safeFreshness(projectRoot, repository, config = tryLoadConfig(projectRoot)) {
|
|
213
|
+
if (!config) {
|
|
214
|
+
return {
|
|
215
|
+
state: "unknown",
|
|
216
|
+
checkedAt: new Date().toISOString(),
|
|
217
|
+
recommendation: "freshness check failed while loading .mdgraph/config.json; run `mdgraph status --freshness --json` or `mdgraph index` before relying on results"
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
return computeStatusFreshness(projectRoot, config, repository);
|
|
221
|
+
}
|
|
222
|
+
function tryLoadConfig(projectRoot) {
|
|
223
|
+
try {
|
|
224
|
+
return loadConfig(projectRoot);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
function withFreshnessNotice(result, freshness) {
|
|
231
|
+
const structuredContent = appendFreshnessStructuredContent(result.structuredContent, freshness);
|
|
232
|
+
if (freshness.state === "fresh") {
|
|
233
|
+
return structuredContent === result.structuredContent ? result : { ...result, structuredContent };
|
|
234
|
+
}
|
|
235
|
+
const relevantIssues = freshness.state === "stale"
|
|
236
|
+
? relevantFreshnessIssues(freshness.issues, structuredContent)
|
|
237
|
+
: [];
|
|
238
|
+
const [first, ...rest] = result.content;
|
|
239
|
+
const warning = formatFreshnessNotice(freshness, relevantIssues);
|
|
240
|
+
if (!first) {
|
|
241
|
+
return {
|
|
242
|
+
...result,
|
|
243
|
+
content: [{ type: "text", text: warning }],
|
|
244
|
+
structuredContent
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
return {
|
|
248
|
+
...result,
|
|
249
|
+
content: [{ type: "text", text: `${warning}\n\n${first.text}` }, ...rest],
|
|
250
|
+
structuredContent
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
function appendFreshnessStructuredContent(structuredContent, freshness) {
|
|
254
|
+
if (!structuredContent || typeof structuredContent !== "object" || Array.isArray(structuredContent)) {
|
|
255
|
+
return structuredContent;
|
|
256
|
+
}
|
|
257
|
+
return { ...structuredContent, freshness };
|
|
258
|
+
}
|
|
259
|
+
function formatFreshnessNotice(freshness, relevantIssues) {
|
|
260
|
+
if (freshness.state === "unknown") {
|
|
261
|
+
return [
|
|
262
|
+
`⚠️ MDGraph freshness warning — ${freshness.recommendation}.`,
|
|
263
|
+
"Run `mdgraph status --freshness --json` or `mdgraph index` before relying on these results."
|
|
264
|
+
].join(" ").replace(/\.\./g, ".");
|
|
265
|
+
}
|
|
266
|
+
const relevantSummary = relevantIssues.length
|
|
267
|
+
? ` Returned paths touched after indexing: ${relevantIssues.slice(0, 5).map((issue) => `${issue.path}:${issue.reason}`).join(", ")}.`
|
|
268
|
+
: "";
|
|
269
|
+
const globalSummary = !relevantIssues.length && freshness.issues?.length
|
|
270
|
+
? ` Markdown changed elsewhere in the workspace: ${freshness.issues.slice(0, 5).map((issue) => `${issue.path}:${issue.reason}`).join(", ")}.`
|
|
271
|
+
: "";
|
|
272
|
+
const guidance = relevantIssues.length
|
|
273
|
+
? "Read those docs directly for live prose, or run `mdgraph index` / prefer default `mdgraph serve --mcp`."
|
|
274
|
+
: "Run `mdgraph index` or prefer default `mdgraph serve --mcp` for live sessions before relying on relationship/ranking details.";
|
|
275
|
+
return `⚠️ MDGraph freshness warning — ${freshness.recommendation}.${relevantSummary}${globalSummary} ${guidance}`.replace(/\.\./g, ".");
|
|
276
|
+
}
|
|
277
|
+
function relevantFreshnessIssues(issues, structuredContent) {
|
|
278
|
+
if (!issues?.length) {
|
|
279
|
+
return [];
|
|
280
|
+
}
|
|
281
|
+
const paths = referencedPaths(structuredContent);
|
|
282
|
+
if (!paths.length) {
|
|
283
|
+
return [];
|
|
284
|
+
}
|
|
285
|
+
const pathSet = new Set(paths);
|
|
286
|
+
return issues.filter((issue) => pathSet.has(issue.path));
|
|
287
|
+
}
|
|
288
|
+
function referencedPaths(structuredContent) {
|
|
289
|
+
if (!structuredContent || typeof structuredContent !== "object" || Array.isArray(structuredContent)) {
|
|
290
|
+
return [];
|
|
291
|
+
}
|
|
292
|
+
const record = structuredContent;
|
|
293
|
+
if (Array.isArray(record.results)) {
|
|
294
|
+
return [...new Set(record.results.flatMap((result) => {
|
|
295
|
+
const documentPath = typeof result.document?.path === "string"
|
|
296
|
+
? result.document.path
|
|
297
|
+
: undefined;
|
|
298
|
+
return documentPath ? [documentPath] : [];
|
|
299
|
+
}))];
|
|
300
|
+
}
|
|
301
|
+
const contextItems = record.context?.items;
|
|
302
|
+
if (Array.isArray(contextItems)) {
|
|
303
|
+
return [...new Set(contextItems.flatMap((item) => typeof item.path === "string" ? [item.path] : []))];
|
|
304
|
+
}
|
|
305
|
+
const nodePath = record.node?.data?.path;
|
|
306
|
+
if (typeof nodePath === "string") {
|
|
307
|
+
return [nodePath];
|
|
308
|
+
}
|
|
309
|
+
return [];
|
|
310
|
+
}
|
|
311
|
+
function agentSearchMode(config, counts, query) {
|
|
312
|
+
const wordCount = query.split(/\s+/).filter(Boolean).length;
|
|
313
|
+
const reasons = ["config default"];
|
|
314
|
+
let limit = config.search.defaultLimit;
|
|
315
|
+
if (wordCount > 6 || query.length > 80) {
|
|
316
|
+
limit += Math.ceil(config.search.defaultLimit / 2);
|
|
317
|
+
reasons.push("multi-term task query");
|
|
318
|
+
}
|
|
319
|
+
if (counts.documents >= 1000) {
|
|
320
|
+
limit += config.search.defaultLimit;
|
|
321
|
+
reasons.push("large index");
|
|
322
|
+
}
|
|
323
|
+
else if (counts.documents >= 100) {
|
|
324
|
+
limit += Math.ceil(config.search.defaultLimit / 2);
|
|
325
|
+
reasons.push("medium index");
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
name: "auto",
|
|
329
|
+
limit: Math.min(24, Math.max(4, limit)),
|
|
330
|
+
reason: reasons.join("; ")
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
function agentContextMode(config, counts, query, knownFiles, requestedMaxChars) {
|
|
334
|
+
const searchMode = agentSearchMode(config, counts, query);
|
|
335
|
+
const wordCount = query.split(/\s+/).filter(Boolean).length;
|
|
336
|
+
const needsMoreDepth = knownFiles.length > 0 || wordCount > 6 || counts.documents >= 100;
|
|
337
|
+
const maxDepth = Math.min(4, config.search.maxDepth + (needsMoreDepth ? 1 : 0));
|
|
338
|
+
const maxChars = requestedMaxChars ?? Math.min(config.search.maxContextChars, needsMoreDepth ? config.search.maxContextChars : 16_000);
|
|
339
|
+
return {
|
|
340
|
+
name: "auto",
|
|
341
|
+
searchLimit: searchMode.limit,
|
|
342
|
+
maxDepth,
|
|
343
|
+
maxChars,
|
|
344
|
+
reason: [searchMode.reason, requestedMaxChars ? "explicit character budget" : "auto character budget"].join("; ")
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
function formatSearch(results) {
|
|
348
|
+
if (!results.length) {
|
|
349
|
+
return "No MDGraph search results.";
|
|
350
|
+
}
|
|
351
|
+
return results.map((result, index) => {
|
|
352
|
+
const location = result.section
|
|
353
|
+
? `${result.document.path}#${result.section.anchor}:${result.section.startLine}`
|
|
354
|
+
: result.document.path;
|
|
355
|
+
const entities = result.matchedEntities.length
|
|
356
|
+
? `\nMatched entities: ${result.matchedEntities.map((entity) => `${entity.name} (${entity.kind})`).join(", ")}`
|
|
357
|
+
: "";
|
|
358
|
+
return `${index + 1}. ${location}\nReason: ${result.reason}${entities}\n${trimBlock(result.content, 1200)}`;
|
|
359
|
+
}).join("\n\n");
|
|
360
|
+
}
|
|
361
|
+
function formatContext(context) {
|
|
362
|
+
if (!context.items.length) {
|
|
363
|
+
return "No MDGraph context found.";
|
|
364
|
+
}
|
|
365
|
+
const header = `Context for: ${context.query}\nBudget: ${context.usedChars}/${context.maxChars} chars`;
|
|
366
|
+
const items = context.items.map((item, index) => {
|
|
367
|
+
const line = item.lines ? `:${item.lines.start}` : "";
|
|
368
|
+
const heading = item.heading ? `# ${item.heading}` : `# ${item.title}`;
|
|
369
|
+
const entities = item.matchedEntities.length ? `\nMatched entities: ${item.matchedEntities.join(", ")}` : "";
|
|
370
|
+
const sourceRefs = item.sourceRefs?.length ? `\nSource refs: ${item.sourceRefs.map((sourceRef) => `${sourceRef.path} (${sourceRef.edgeKind}/${sourceRef.provenance}, confidence ${sourceRef.confidence})`).join(", ")}` : "";
|
|
371
|
+
const riskNotes = item.riskNotes?.length ? `\nRisk notes: ${item.riskNotes.join("; ")}` : "";
|
|
372
|
+
return `## ${index + 1}. ${item.path}${line}\nReason: ${item.reason}${entities}${sourceRefs}${riskNotes}\n${heading}\n${item.content}`;
|
|
373
|
+
});
|
|
374
|
+
const hints = [
|
|
375
|
+
context.mode ? `Mode: ${context.mode.name} (searchLimit ${context.mode.searchLimit}, maxDepth ${context.mode.maxDepth}; ${context.mode.reason})` : "",
|
|
376
|
+
context.knownFiles?.length ? `Known files: ${context.knownFiles.join(", ")}` : "",
|
|
377
|
+
context.suggestedNextQueries?.length ? `Suggested next queries:\n${context.suggestedNextQueries.map((query) => `- ${query}`).join("\n")}` : ""
|
|
378
|
+
].filter(Boolean);
|
|
379
|
+
return [header, ...hints, ...items].join("\n\n");
|
|
380
|
+
}
|
|
381
|
+
function formatNode(node, repository) {
|
|
382
|
+
const edges = repository.edgesForNode(node.id).slice(0, 12);
|
|
383
|
+
const related = edges.map((edge) => {
|
|
384
|
+
const otherId = edge.fromId === node.id ? edge.toId : edge.fromId;
|
|
385
|
+
const other = repository.getNode(otherId);
|
|
386
|
+
return `- ${edge.kind} ${edge.fromId === node.id ? "->" : "<-"} ${other?.label ?? otherId} (${edge.provenance}, confidence ${edge.confidence})`;
|
|
387
|
+
});
|
|
388
|
+
return [
|
|
389
|
+
`${node.kind}: ${node.label}`,
|
|
390
|
+
JSON.stringify(node.data, null, 2),
|
|
391
|
+
related.length ? `Related edges:\n${related.join("\n")}` : "Related edges: none"
|
|
392
|
+
].join("\n\n");
|
|
393
|
+
}
|
|
394
|
+
function formatAmbiguousNodeQuery(resolution) {
|
|
395
|
+
const candidates = resolution.candidates
|
|
396
|
+
.map((candidate) => `- ${candidate.documentPath}#${candidate.anchor}:${candidate.line} (${candidate.heading})`)
|
|
397
|
+
.join("\n");
|
|
398
|
+
return `Ambiguous section query: ${resolution.query}\n${candidates}`;
|
|
399
|
+
}
|
|
400
|
+
function formatTrace(trace) {
|
|
401
|
+
if (!trace.found) {
|
|
402
|
+
return trace.message ?? "No MDGraph trace path found.";
|
|
403
|
+
}
|
|
404
|
+
if (!trace.steps.length) {
|
|
405
|
+
return `Trace found: ${trace.from} is ${trace.to}`;
|
|
406
|
+
}
|
|
407
|
+
const steps = trace.steps.map((step, index) => (`${index + 1}. ${formatTraceStep(step)}`));
|
|
408
|
+
return [`Trace: ${trace.from} -> ${trace.to}`, ...steps].join("\n");
|
|
409
|
+
}
|
|
410
|
+
function formatTraceStep(step) {
|
|
411
|
+
const edge = `${step.edgeKind} (${step.provenance}, confidence ${step.confidence})`;
|
|
412
|
+
return step.traversalDirection === "forward"
|
|
413
|
+
? `${step.fromLabel} --${edge}--> ${step.toLabel}`
|
|
414
|
+
: `${step.fromLabel} <--${edge}-- ${step.toLabel}`;
|
|
415
|
+
}
|
|
416
|
+
function resolveProjectRoot(rawProjectPath, fallback, boundProjectRoot) {
|
|
417
|
+
if (rawProjectPath === undefined || rawProjectPath === null || rawProjectPath === "") {
|
|
418
|
+
return validatedBoundProjectRoot(path.resolve(fallback), boundProjectRoot);
|
|
419
|
+
}
|
|
420
|
+
if (typeof rawProjectPath !== "string") {
|
|
421
|
+
throw new McpInputError("projectPath must be a string when provided");
|
|
422
|
+
}
|
|
423
|
+
return validatedBoundProjectRoot(path.resolve(rawProjectPath), boundProjectRoot);
|
|
424
|
+
}
|
|
425
|
+
function validatedProjectRoot(projectRoot) {
|
|
426
|
+
if (!fs.existsSync(projectRoot)) {
|
|
427
|
+
throw new McpInputError(`Project root does not exist: ${projectRoot}`);
|
|
428
|
+
}
|
|
429
|
+
const stat = fs.statSync(projectRoot);
|
|
430
|
+
if (!stat.isDirectory()) {
|
|
431
|
+
throw new McpInputError(`Project root is not a directory: ${projectRoot}`);
|
|
432
|
+
}
|
|
433
|
+
return projectRoot;
|
|
434
|
+
}
|
|
435
|
+
function validatedBoundProjectRoot(projectRoot, boundProjectRoot) {
|
|
436
|
+
const resolved = validatedProjectRoot(projectRoot);
|
|
437
|
+
if (!isPathInsideOrEqual(boundProjectRoot, resolved)) {
|
|
438
|
+
throw new McpInputError(`projectPath must stay inside served project root: ${boundProjectRoot}`);
|
|
439
|
+
}
|
|
440
|
+
return resolved;
|
|
441
|
+
}
|
|
442
|
+
function requiredString(value, field) {
|
|
443
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
444
|
+
throw new McpInputError(`Missing required string argument: ${field}`);
|
|
445
|
+
}
|
|
446
|
+
if (value.length > 10_000) {
|
|
447
|
+
throw new McpInputError(`Argument too long: ${field}`);
|
|
448
|
+
}
|
|
449
|
+
return value.trim();
|
|
450
|
+
}
|
|
451
|
+
function optionalPositiveInteger(value, fallback) {
|
|
452
|
+
if (value === undefined || value === null) {
|
|
453
|
+
return fallback;
|
|
454
|
+
}
|
|
455
|
+
const parsed = typeof value === "number" ? value : Number(value);
|
|
456
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
457
|
+
throw new McpInputError(`Expected positive integer, got ${String(value)}`);
|
|
458
|
+
}
|
|
459
|
+
return parsed;
|
|
460
|
+
}
|
|
461
|
+
function optionalBoundedPositiveInteger(value, fallback, field, max) {
|
|
462
|
+
const parsed = optionalPositiveInteger(value, fallback);
|
|
463
|
+
if (parsed > max) {
|
|
464
|
+
throw new McpInputError(`${field} must be at most ${max}`);
|
|
465
|
+
}
|
|
466
|
+
return parsed;
|
|
467
|
+
}
|
|
468
|
+
function optionalStringArray(value, field) {
|
|
469
|
+
if (value === undefined || value === null) {
|
|
470
|
+
return [];
|
|
471
|
+
}
|
|
472
|
+
if (!Array.isArray(value)) {
|
|
473
|
+
throw new McpInputError(`${field} must be an array of strings when provided`);
|
|
474
|
+
}
|
|
475
|
+
if (value.length > 20) {
|
|
476
|
+
throw new McpInputError(`${field} must include at most 20 entries`);
|
|
477
|
+
}
|
|
478
|
+
const result = [];
|
|
479
|
+
for (const item of value) {
|
|
480
|
+
if (typeof item !== "string") {
|
|
481
|
+
throw new McpInputError(`${field} must contain only strings`);
|
|
482
|
+
}
|
|
483
|
+
const trimmed = item.trim();
|
|
484
|
+
if (trimmed.length > 1_000) {
|
|
485
|
+
throw new McpInputError(`${field} entry is too long`);
|
|
486
|
+
}
|
|
487
|
+
if (trimmed) {
|
|
488
|
+
result.push(trimmed);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
return [...new Set(result)];
|
|
492
|
+
}
|
|
493
|
+
function trimBlock(content, maxChars) {
|
|
494
|
+
if (content.length <= maxChars) {
|
|
495
|
+
return content;
|
|
496
|
+
}
|
|
497
|
+
return `${content.slice(0, maxChars).trimEnd()}\n...`;
|
|
498
|
+
}
|
|
499
|
+
function unindexedMessage(projectRoot) {
|
|
500
|
+
return [
|
|
501
|
+
"MDGraph index status: inactive",
|
|
502
|
+
`Project: ${projectRoot}`,
|
|
503
|
+
"No .mdgraph/graph.db index was found.",
|
|
504
|
+
"Use normal file tools for this session, or run `mdgraph index` when the user asks to create/update the index."
|
|
505
|
+
].join("\n");
|
|
506
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Readable, Writable } from "node:stream";
|
|
2
|
+
export interface JsonRpcRequest {
|
|
3
|
+
jsonrpc: "2.0";
|
|
4
|
+
id: string | number;
|
|
5
|
+
method: string;
|
|
6
|
+
params?: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface JsonRpcNotification {
|
|
9
|
+
jsonrpc: "2.0";
|
|
10
|
+
method: string;
|
|
11
|
+
params?: unknown;
|
|
12
|
+
}
|
|
13
|
+
export interface JsonRpcError {
|
|
14
|
+
code: number;
|
|
15
|
+
message: string;
|
|
16
|
+
data?: unknown;
|
|
17
|
+
}
|
|
18
|
+
export interface JsonRpcResponse {
|
|
19
|
+
jsonrpc: "2.0";
|
|
20
|
+
id: string | number | null;
|
|
21
|
+
result?: unknown;
|
|
22
|
+
error?: JsonRpcError;
|
|
23
|
+
}
|
|
24
|
+
export declare const ErrorCodes: {
|
|
25
|
+
readonly ParseError: -32700;
|
|
26
|
+
readonly InvalidRequest: -32600;
|
|
27
|
+
readonly MethodNotFound: -32601;
|
|
28
|
+
readonly InvalidParams: -32602;
|
|
29
|
+
readonly InternalError: -32603;
|
|
30
|
+
};
|
|
31
|
+
export type MessageHandler = (message: JsonRpcRequest | JsonRpcNotification) => Promise<void> | void;
|
|
32
|
+
export interface JsonRpcTransport {
|
|
33
|
+
start(handler: MessageHandler): void;
|
|
34
|
+
stop(): void;
|
|
35
|
+
sendResult(id: string | number, result: unknown): void;
|
|
36
|
+
sendError(id: string | number | null, code: number, message: string, data?: unknown): void;
|
|
37
|
+
}
|
|
38
|
+
export declare class StdioTransport implements JsonRpcTransport {
|
|
39
|
+
private readonly input;
|
|
40
|
+
private readonly output;
|
|
41
|
+
private reader;
|
|
42
|
+
private handler;
|
|
43
|
+
constructor(input?: Readable, output?: Writable);
|
|
44
|
+
start(handler: MessageHandler): void;
|
|
45
|
+
stop(): void;
|
|
46
|
+
sendResult(id: string | number, result: unknown): void;
|
|
47
|
+
sendError(id: string | number | null, code: number, message: string, data?: unknown): void;
|
|
48
|
+
private handleLine;
|
|
49
|
+
private write;
|
|
50
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import readline from "node:readline";
|
|
2
|
+
import { MCP_LIMITS } from "../config/limits.js";
|
|
3
|
+
import { errorMessage, mcpDebug, mcpErrorData } from "./debug.js";
|
|
4
|
+
export const ErrorCodes = {
|
|
5
|
+
ParseError: -32700,
|
|
6
|
+
InvalidRequest: -32600,
|
|
7
|
+
MethodNotFound: -32601,
|
|
8
|
+
InvalidParams: -32602,
|
|
9
|
+
InternalError: -32603
|
|
10
|
+
};
|
|
11
|
+
export class StdioTransport {
|
|
12
|
+
input;
|
|
13
|
+
output;
|
|
14
|
+
reader;
|
|
15
|
+
handler;
|
|
16
|
+
constructor(input = process.stdin, output = process.stdout) {
|
|
17
|
+
this.input = input;
|
|
18
|
+
this.output = output;
|
|
19
|
+
}
|
|
20
|
+
start(handler) {
|
|
21
|
+
this.handler = handler;
|
|
22
|
+
this.reader = readline.createInterface({ input: this.input });
|
|
23
|
+
this.reader.on("line", (line) => {
|
|
24
|
+
void this.handleLine(line);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
stop() {
|
|
28
|
+
this.reader?.close();
|
|
29
|
+
this.reader = undefined;
|
|
30
|
+
}
|
|
31
|
+
sendResult(id, result) {
|
|
32
|
+
this.write({ jsonrpc: "2.0", id, result });
|
|
33
|
+
}
|
|
34
|
+
sendError(id, code, message, data) {
|
|
35
|
+
this.write({ jsonrpc: "2.0", id, error: { code, message, data } });
|
|
36
|
+
}
|
|
37
|
+
async handleLine(line) {
|
|
38
|
+
if (Buffer.byteLength(line, "utf8") > MCP_LIMITS.jsonRpcLineBytes) {
|
|
39
|
+
mcpDebug("transport parse rejection", { reason: "line_too_large", bytes: Buffer.byteLength(line, "utf8") });
|
|
40
|
+
this.sendError(null, ErrorCodes.ParseError, `Parse error: JSON-RPC line exceeds ${MCP_LIMITS.jsonRpcLineBytes} bytes`, mcpErrorData("transport.parse", { reason: "line_too_large" }));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const trimmed = line.trim();
|
|
44
|
+
if (!trimmed) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = JSON.parse(trimmed);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
mcpDebug("transport parse rejection", { reason: "invalid_json" });
|
|
53
|
+
this.sendError(null, ErrorCodes.ParseError, "Parse error: invalid JSON", mcpErrorData("transport.parse", { reason: "invalid_json" }));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
if (!isValidMessage(parsed)) {
|
|
57
|
+
mcpDebug("transport parse rejection", { reason: "invalid_request_shape" });
|
|
58
|
+
this.sendError(null, ErrorCodes.InvalidRequest, "Invalid Request: not a JSON-RPC 2.0 request or notification", mcpErrorData("transport.validate", { reason: "invalid_request_shape" }));
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
mcpDebug("transport received", {
|
|
62
|
+
method: parsed.method,
|
|
63
|
+
isRequest: "id" in parsed
|
|
64
|
+
});
|
|
65
|
+
try {
|
|
66
|
+
await this.handler?.(parsed);
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
mcpDebug("transport handler failure", {
|
|
70
|
+
method: parsed.method,
|
|
71
|
+
error: errorMessage(error)
|
|
72
|
+
});
|
|
73
|
+
if ("id" in parsed) {
|
|
74
|
+
this.sendError(parsed.id, ErrorCodes.InternalError, error instanceof Error ? error.message : String(error), mcpErrorData("transport.dispatch", { method: parsed.method }));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
write(response) {
|
|
79
|
+
this.output.write(`${JSON.stringify(response)}\n`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function isValidMessage(value) {
|
|
83
|
+
if (!value || typeof value !== "object") {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
const message = value;
|
|
87
|
+
return message.jsonrpc === "2.0" && typeof message.method === "string";
|
|
88
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DocumentFrontmatter, FrontmatterDiagnostic } from "../types.js";
|
|
2
|
+
export interface ParsedFrontmatterBlock {
|
|
3
|
+
data: Record<string, unknown>;
|
|
4
|
+
body: string;
|
|
5
|
+
bodyLineOffset: number;
|
|
6
|
+
diagnostics: FrontmatterDiagnostic[];
|
|
7
|
+
}
|
|
8
|
+
export declare function parseFrontmatterBlock(raw: string): ParsedFrontmatterBlock;
|
|
9
|
+
export declare function normalizeFrontmatter(input: Record<string, unknown>): DocumentFrontmatter;
|
|
10
|
+
export declare function diagnoseFrontmatterFields(input: Record<string, unknown>, fieldLines?: Map<string, number>): FrontmatterDiagnostic[];
|