@getchomp/mcp 0.0.0-stage → 0.2.42
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/README.md +15 -2
- package/dist/conventionsReference.d.ts +84 -0
- package/dist/conventionsReference.js +313 -0
- package/dist/designSystem/astScanner.d.ts +153 -0
- package/dist/designSystem/astScanner.js +2014 -0
- package/dist/designSystem/baseline.d.ts +65 -0
- package/dist/designSystem/baseline.js +136 -0
- package/dist/designSystem/color.d.ts +35 -0
- package/dist/designSystem/color.js +265 -0
- package/dist/designSystem/config.d.ts +183 -0
- package/dist/designSystem/config.js +469 -0
- package/dist/designSystem/contrast.d.ts +55 -0
- package/dist/designSystem/contrast.js +377 -0
- package/dist/designSystem/cssParser.d.ts +63 -0
- package/dist/designSystem/cssParser.js +469 -0
- package/dist/designSystem/merges.d.ts +57 -0
- package/dist/designSystem/merges.js +94 -0
- package/dist/designSystem/preprocessors.d.ts +46 -0
- package/dist/designSystem/preprocessors.js +1108 -0
- package/dist/designSystem/presentation.d.ts +45 -0
- package/dist/designSystem/presentation.js +796 -0
- package/dist/designSystem/styleVectors.d.ts +27 -0
- package/dist/designSystem/styleVectors.js +484 -0
- package/dist/designSystem/tokens.d.ts +39 -0
- package/dist/designSystem/tokens.js +409 -0
- package/dist/designSystem/topology.d.ts +64 -0
- package/dist/designSystem/topology.js +254 -0
- package/dist/designSystem/types.d.ts +857 -0
- package/dist/designSystem/types.js +113 -0
- package/dist/designSystem/typography.d.ts +25 -0
- package/dist/designSystem/typography.js +244 -0
- package/dist/designSystem/uiShapes.d.ts +74 -0
- package/dist/designSystem/uiShapes.js +285 -0
- package/dist/designSystem/valueClusters.d.ts +76 -0
- package/dist/designSystem/valueClusters.js +281 -0
- package/dist/designSystemPlugin.d.ts +321 -0
- package/dist/designSystemPlugin.js +4730 -0
- package/dist/enrichNodesPlugin.d.ts +160 -0
- package/dist/enrichNodesPlugin.js +957 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1298 -0
- package/dist/intelligence.d.ts +502 -0
- package/dist/intelligence.js +3058 -0
- package/dist/pluginRunner.d.ts +364 -0
- package/dist/pluginRunner.js +1096 -0
- package/dist/plugins/design-system/index.d.ts +14 -0
- package/dist/plugins/design-system/index.js +241 -0
- package/dist/plugins/enrich-nodes/index.d.ts +388 -0
- package/dist/plugins/enrich-nodes/index.js +697 -0
- package/dist/plugins/index.d.ts +15 -0
- package/dist/plugins/index.js +20 -0
- package/dist/plugins/local-shims/index.d.ts +121 -0
- package/dist/plugins/local-shims/index.js +237 -0
- package/dist/shimsPlugin.d.ts +134 -0
- package/dist/shimsPlugin.js +1392 -0
- package/package.json +38 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1298 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { createSQLiteStorage } from "@getchomp/db";
|
|
5
|
+
import { basename, resolve, dirname, join, relative } from "node:path";
|
|
6
|
+
import { homedir, tmpdir } from "node:os";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { execFileSync, execSync } from "node:child_process";
|
|
10
|
+
import { CORE_EXTRACTOR_VERSION, SHIM_OVERLAY_LAYER, analyzeTarget, compareGraphs, } from "@getchomp/core";
|
|
11
|
+
import { auditGraphHealth, buildActiveViewUrl, checkGraphBoundaries, computeBlastRadius, filterNodesForMcp, findGraphRedundancies, hydrateNodeOverlays, resolveViewNodeIds, resolveViewTargetAltitude, } from "./intelligence.js";
|
|
12
|
+
import { applyActivePluginProjections, discoverPluginsInDir, listChompPlugins, loadPluginSettings, readRepoOverlayLayerToggles, resolveActiveUiBaseUrl, resolvePluginSecret, resolveRepoGitBranch, resolveRepoName, runChompPlugin, writePluginActiveView, } from "./pluginRunner.js";
|
|
13
|
+
import "./plugins/index.js";
|
|
14
|
+
import { SEMANTIC_OVERLAY_LAYER, classifySemanticOverlayMap, isEnrichmentTargetNode, } from "./enrichNodesPlugin.js";
|
|
15
|
+
import { getConventionsReference } from "./conventionsReference.js";
|
|
16
|
+
export { auditGraphHealth, buildActiveViewUrl, checkGraphBoundaries, computeBlastRadius, filterNodesForMcp, findGraphRedundancies, formatEnrichNodesSummary, hydrateNodeOverlays, packageMatchesFilter, resolveViewNodeIds, resolveViewTargetAltitude, } from "./intelligence.js";
|
|
17
|
+
export { PLUGINS_STATE_DIR_REL, PLUGIN_LAST_RUN_FILENAME, applyActivePluginProjections, buildOverlayEvidence, collectPluginRepoFiles, collectPluginStateFiles, computeFileOverlayHash, defineChompPlugin, discoverPluginsInDir, getChompPlugin, getPluginEnvStatus, getPluginLastRunPath, getPluginMcpToolSummaries, getPluginSettingsPath, getPluginStateDir, getPluginStateDirRel, getRegisteredPluginDefaultLayers, isPluginLayerEnabled, isRegisteredStructuralPluginOverlay, listChompPlugins, loadPluginSettings, readPluginLastRun, readRepoOverlayLayerToggles, registerChompPlugin, resolveActiveUiBaseUrl, resolvePluginSecret, resolveRepoGitBranch, resolveRepoName, runAllChompPlugins, runChompPlugin, savePluginSettings, unregisterChompPlugin, writePluginActiveView, writePluginLastRun, } from "./pluginRunner.js";
|
|
18
|
+
export { BUILTIN_PLUGINS_DIR, discoverBuiltInPlugins } from "./plugins/index.js";
|
|
19
|
+
export { analyzeRepositoryDesignSystem, auditDesignSystem, classifyTokenTier, computeRelativeLuminance, computeWcagContrastRatio, createDesignSystemPlugin, designSystemPlugin, diffDesignSystem, evaluateContrast, frontendPackageLabels, parseCssColorString, parseCssStylesheet, snapshotDesignSystemBaseline, } from "./designSystemPlugin.js";
|
|
20
|
+
export { DEFAULT_MERGE_DECISIONS_REL, buildMergeDecisionId, readMergeDecisions, removeMergeDecision, resolveMergeDecisionsPath, upsertMergeDecision, } from "./designSystem/merges.js";
|
|
21
|
+
export { LEGACY_LOCAL_SHIMS_FILE_REL, LOCAL_SHIMS_FILE_REL, LOCAL_SHIMS_PLUGIN_NAME, deriveShimId, evaluateShimsAgainstGraph, loadLocalShimsFromTexts, localShimsPlugin, manageLocalShims, } from "./shimsPlugin.js";
|
|
22
|
+
export { ENRICH_NODES_PLUGIN_NAME, SEMANTIC_OVERLAY_LAYER, SEMANTIC_SIDECAR_FILENAME, SEMANTIC_SIDECAR_FILE_REL, buildEnrichmentQueue, buildEnrichmentStatus, classifySemanticOverlayMap, enrichNodesPlugin, isEnrichmentTargetNode, mergeNodesIntoSemanticSidecar, readSemanticSidecar, writeSemanticSidecar, } from "./enrichNodesPlugin.js";
|
|
23
|
+
export { getConventionsReference, } from "./conventionsReference.js";
|
|
24
|
+
function cleanGitEnv() {
|
|
25
|
+
const env = { ...process.env };
|
|
26
|
+
delete env.GIT_DIR;
|
|
27
|
+
delete env.GIT_WORK_TREE;
|
|
28
|
+
delete env.GIT_INDEX_FILE;
|
|
29
|
+
delete env.GIT_OBJECT_DIRECTORY;
|
|
30
|
+
delete env.GIT_ALTERNATE_OBJECT_DIRECTORIES;
|
|
31
|
+
delete env.GIT_CEILING_DIRECTORIES;
|
|
32
|
+
delete env.GIT_COMMON_DIR;
|
|
33
|
+
delete env.GIT_PREFIX;
|
|
34
|
+
return env;
|
|
35
|
+
}
|
|
36
|
+
export function resolveActiveMcpRepo(fallbackTargetPath = process.cwd()) {
|
|
37
|
+
let candidatePath = fallbackTargetPath;
|
|
38
|
+
const masterRootEnv = process.env.CHOMP_MASTER_ROOT?.trim();
|
|
39
|
+
const ctxPaths = Array.from(new Set([
|
|
40
|
+
resolve(homedir(), ".chomp", "context.json"),
|
|
41
|
+
resolve(fallbackTargetPath, ".chomp", "master_context.json"),
|
|
42
|
+
...(masterRootEnv
|
|
43
|
+
? [resolve(masterRootEnv, ".chomp", "master_context.json")]
|
|
44
|
+
: []),
|
|
45
|
+
]))
|
|
46
|
+
.filter((p) => existsSync(p))
|
|
47
|
+
.sort((a, b) => {
|
|
48
|
+
try {
|
|
49
|
+
return statSync(b).mtimeMs - statSync(a).mtimeMs;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
let contextRepoName;
|
|
56
|
+
let contextRepoId;
|
|
57
|
+
for (const ctxPath of ctxPaths) {
|
|
58
|
+
try {
|
|
59
|
+
const parsed = JSON.parse(readFileSync(ctxPath, "utf8"));
|
|
60
|
+
if (parsed &&
|
|
61
|
+
typeof parsed.activeRepoPath === "string" &&
|
|
62
|
+
existsSync(parsed.activeRepoPath)) {
|
|
63
|
+
candidatePath = parsed.activeRepoPath;
|
|
64
|
+
if (typeof parsed.activeRepoName === "string" && parsed.activeRepoName.trim()) {
|
|
65
|
+
contextRepoName = parsed.activeRepoName.trim();
|
|
66
|
+
}
|
|
67
|
+
if (typeof parsed.activeRepoId === "string" && parsed.activeRepoId.trim()) {
|
|
68
|
+
contextRepoId = parsed.activeRepoId.trim();
|
|
69
|
+
}
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Fall back to next candidate or fallbackTargetPath
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
let repoPath = candidatePath;
|
|
78
|
+
try {
|
|
79
|
+
const stat = statSync(candidatePath);
|
|
80
|
+
const isDir = stat.isDirectory();
|
|
81
|
+
const startDir = isDir ? candidatePath : dirname(candidatePath);
|
|
82
|
+
if (existsSync(resolve(startDir, ".chomp")) ||
|
|
83
|
+
existsSync(resolve(startDir, ".git")) ||
|
|
84
|
+
startDir.includes("/fixtures/cloned-repos/") ||
|
|
85
|
+
startDir.includes("/fixtures/test-repos/")) {
|
|
86
|
+
repoPath = startDir;
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
repoPath = execSync("git rev-parse --show-toplevel", {
|
|
90
|
+
cwd: startDir,
|
|
91
|
+
encoding: "utf8",
|
|
92
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
93
|
+
env: cleanGitEnv(),
|
|
94
|
+
}).trim();
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
try {
|
|
99
|
+
const stat = statSync(candidatePath);
|
|
100
|
+
repoPath = stat.isDirectory() ? candidatePath : dirname(candidatePath);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
repoPath = candidatePath;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const repoName = contextRepoName ?? resolveRepoName(repoPath);
|
|
107
|
+
const repoId = contextRepoId ?? repoName.toLowerCase().replace(/[^a-z0-9_-]/g, "_");
|
|
108
|
+
const dbPath = resolve(repoPath, ".chomp", "graph.db");
|
|
109
|
+
return { repoPath, repoName, repoId, dbPath };
|
|
110
|
+
}
|
|
111
|
+
const mcpGraphCache = new Map();
|
|
112
|
+
function getDbMtimeMs(dbPath) {
|
|
113
|
+
try {
|
|
114
|
+
const mainMtime = statSync(dbPath).mtimeMs;
|
|
115
|
+
const walPath = `${dbPath}-wal`;
|
|
116
|
+
const walMtime = existsSync(walPath) ? statSync(walPath).mtimeMs : 0;
|
|
117
|
+
return Math.max(mainMtime, walMtime);
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return -1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Executes an async callback against a `ChompStorage` instance and guarantees
|
|
125
|
+
* `await storage.close()` in a `finally` block even when `fn` throws.
|
|
126
|
+
*/
|
|
127
|
+
export async function withStorage(dbPath, fn, storageFactory = createSQLiteStorage) {
|
|
128
|
+
const storage = storageFactory(dbPath);
|
|
129
|
+
try {
|
|
130
|
+
return await fn(storage);
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
await storage.close();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Invalidates the in-memory MCP `RepresentationGraph` cache (either for a
|
|
138
|
+
* specific `dbPath` or across all cached repositories).
|
|
139
|
+
*/
|
|
140
|
+
export function invalidateMcpGraphCache(dbPath) {
|
|
141
|
+
if (!dbPath) {
|
|
142
|
+
mcpGraphCache.clear();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const resolved = resolve(dbPath);
|
|
146
|
+
for (const key of mcpGraphCache.keys()) {
|
|
147
|
+
if (key.startsWith(`${resolved}::`)) {
|
|
148
|
+
mcpGraphCache.delete(key);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Loads `RepresentationGraph` for `(dbPath, repoId)` with an in-memory cache
|
|
154
|
+
* invalidated whenever `dbPath` (or `${dbPath}-wal`) mtime changes.
|
|
155
|
+
*/
|
|
156
|
+
export async function loadActiveGraphCached(dbPath, repoId, storageFactory = createSQLiteStorage) {
|
|
157
|
+
const resolvedDbPath = resolve(dbPath);
|
|
158
|
+
const cacheKey = `${resolvedDbPath}::${repoId}`;
|
|
159
|
+
const currentMtime = getDbMtimeMs(resolvedDbPath);
|
|
160
|
+
const cached = mcpGraphCache.get(cacheKey);
|
|
161
|
+
if (cached && currentMtime > 0 && cached.mtimeMs === currentMtime) {
|
|
162
|
+
return cached.graph;
|
|
163
|
+
}
|
|
164
|
+
const graph = await withStorage(resolvedDbPath, async (storage) => {
|
|
165
|
+
const direct = await storage.getRepresentationGraph(repoId);
|
|
166
|
+
if (direct)
|
|
167
|
+
return direct;
|
|
168
|
+
const repos = await storage.listRepositories();
|
|
169
|
+
return repos[0] ? storage.getRepresentationGraph(repos[0].id) : null;
|
|
170
|
+
}, storageFactory);
|
|
171
|
+
if (graph && currentMtime > 0) {
|
|
172
|
+
mcpGraphCache.set(cacheKey, {
|
|
173
|
+
mtimeMs: currentMtime,
|
|
174
|
+
graph,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
mcpGraphCache.delete(cacheKey);
|
|
179
|
+
}
|
|
180
|
+
return graph;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Checks `.chomp/rules.json` to see whether the `L1_SHIMS` plugin overlay layer is enabled
|
|
184
|
+
* (defaults to `true` when unset or when `.chomp/rules.json` does not exist).
|
|
185
|
+
*/
|
|
186
|
+
export function isShimLayerEnabled(repoPath) {
|
|
187
|
+
try {
|
|
188
|
+
const rulesPath = resolve(repoPath, ".chomp", "rules.json");
|
|
189
|
+
if (!existsSync(rulesPath))
|
|
190
|
+
return true;
|
|
191
|
+
const parsed = JSON.parse(readFileSync(rulesPath, "utf8"));
|
|
192
|
+
return parsed?.overlayLayers?.[SHIM_OVERLAY_LAYER] !== false;
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Loads the persisted `RepresentationGraph` for `(dbPath, repoId)` and runs every enabled
|
|
200
|
+
* registered plugin's `projectGraph` hook (e.g. `local-shims` `L1_SHIMS` overlays and `.chomp/plugins/<name>/` files).
|
|
201
|
+
*/
|
|
202
|
+
export async function loadActiveGraphWithShims(repoPath, dbPath, repoId, storageFactory = createSQLiteStorage) {
|
|
203
|
+
const baseGraph = await loadActiveGraphCached(dbPath, repoId, storageFactory);
|
|
204
|
+
if (!baseGraph)
|
|
205
|
+
return null;
|
|
206
|
+
const projectingLayers = listChompPlugins()
|
|
207
|
+
.filter((p) => Boolean(p.projectGraph))
|
|
208
|
+
.map((p) => p.layer);
|
|
209
|
+
const overlays = projectingLayers.length > 0
|
|
210
|
+
? await withStorage(resolve(dbPath), (storage) => storage.getEntityOverlays(repoId, { layers: projectingLayers }), storageFactory)
|
|
211
|
+
: [];
|
|
212
|
+
return applyActivePluginProjections(baseGraph, {
|
|
213
|
+
repoPath,
|
|
214
|
+
overlays,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
const MCP_THIS_DIR = dirname(fileURLToPath(import.meta.url));
|
|
218
|
+
const MONOREPO_CORE_ROOT = resolve(MCP_THIS_DIR, "../../core");
|
|
219
|
+
function collectCoreFilesSorted(dir, out = []) {
|
|
220
|
+
if (!existsSync(dir))
|
|
221
|
+
return out;
|
|
222
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
223
|
+
const abs = resolve(dir, entry.name);
|
|
224
|
+
if (entry.isDirectory()) {
|
|
225
|
+
collectCoreFilesSorted(abs, out);
|
|
226
|
+
}
|
|
227
|
+
else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
|
|
228
|
+
out.push(abs);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
function computeCoreSourceFingerprint() {
|
|
234
|
+
try {
|
|
235
|
+
const coreEntry = resolve(MONOREPO_CORE_ROOT, "src/index.ts");
|
|
236
|
+
if (!existsSync(coreEntry))
|
|
237
|
+
return null;
|
|
238
|
+
const files = [
|
|
239
|
+
resolve(MONOREPO_CORE_ROOT, "package.json"),
|
|
240
|
+
resolve(MONOREPO_CORE_ROOT, "src/version.ts"),
|
|
241
|
+
resolve(MONOREPO_CORE_ROOT, "src/utils/id.ts"),
|
|
242
|
+
...collectCoreFilesSorted(resolve(MONOREPO_CORE_ROOT, "src/differ")),
|
|
243
|
+
...collectCoreFilesSorted(resolve(MONOREPO_CORE_ROOT, "src/extractor")),
|
|
244
|
+
]
|
|
245
|
+
.filter((f) => existsSync(f))
|
|
246
|
+
.sort();
|
|
247
|
+
return files
|
|
248
|
+
.map((f) => {
|
|
249
|
+
const s = statSync(f);
|
|
250
|
+
return `${relative(MONOREPO_CORE_ROOT, f)}:${s.mtimeMs}:${s.size}`;
|
|
251
|
+
})
|
|
252
|
+
.join("|");
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const STARTUP_CORE_FINGERPRINT = computeCoreSourceFingerprint();
|
|
259
|
+
function findTsxBinary() {
|
|
260
|
+
const monoRoot = resolve(MCP_THIS_DIR, "../../..");
|
|
261
|
+
const candidates = [
|
|
262
|
+
resolve(monoRoot, "packages/mcp/node_modules/.bin/tsx"),
|
|
263
|
+
resolve(monoRoot, "packages/db/node_modules/.bin/tsx"),
|
|
264
|
+
resolve(monoRoot, "packages/cli/node_modules/.bin/tsx"),
|
|
265
|
+
resolve(monoRoot, "node_modules/.bin/tsx"),
|
|
266
|
+
];
|
|
267
|
+
return candidates.find((p) => existsSync(p)) ?? null;
|
|
268
|
+
}
|
|
269
|
+
function loadRepoExcludeWorkspaces(repoPath) {
|
|
270
|
+
try {
|
|
271
|
+
const cfgPath = resolve(repoPath, "chomp.config.json");
|
|
272
|
+
if (!existsSync(cfgPath))
|
|
273
|
+
return [];
|
|
274
|
+
const parsed = JSON.parse(readFileSync(cfgPath, "utf8"));
|
|
275
|
+
return Array.isArray(parsed?.excludeWorkspaces)
|
|
276
|
+
? parsed.excludeWorkspaces.filter((x) => typeof x === "string")
|
|
277
|
+
: [];
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
return [];
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function extractLiveUserGraph(repoPath, headCommitSha, excludeWorkspaces) {
|
|
284
|
+
const currentFp = computeCoreSourceFingerprint();
|
|
285
|
+
if (STARTUP_CORE_FINGERPRINT !== null &&
|
|
286
|
+
currentFp !== null &&
|
|
287
|
+
currentFp !== STARTUP_CORE_FINGERPRINT) {
|
|
288
|
+
const tsxBin = findTsxBinary();
|
|
289
|
+
const coreEntry = resolve(MONOREPO_CORE_ROOT, "src/index.ts");
|
|
290
|
+
if (tsxBin && existsSync(coreEntry)) {
|
|
291
|
+
try {
|
|
292
|
+
const childScript = `
|
|
293
|
+
import { pathToFileURL } from "node:url";
|
|
294
|
+
const [entryPath, targetRepo, commitArg, exclJson] = process.argv.slice(1);
|
|
295
|
+
const mod = await import(pathToFileURL(entryPath).href);
|
|
296
|
+
const g = mod.analyzeTarget(targetRepo, mod.CORE_EXTRACTOR_VERSION, commitArg || undefined, JSON.parse(exclJson));
|
|
297
|
+
const userNodes = g.nodes.filter((n) => (n.scope ?? "USER") === "USER");
|
|
298
|
+
const userNodeIds = new Set(userNodes.map((n) => n.id));
|
|
299
|
+
process.stdout.write(JSON.stringify({
|
|
300
|
+
...g,
|
|
301
|
+
nodes: userNodes,
|
|
302
|
+
edges: g.edges
|
|
303
|
+
.filter((e) => (e.scope ?? "USER") === "USER")
|
|
304
|
+
.map((e) => (e.targetId && !userNodeIds.has(e.targetId) ? { ...e, targetId: undefined } : e)),
|
|
305
|
+
}));
|
|
306
|
+
`;
|
|
307
|
+
const stdout = execFileSync(tsxBin, ["-e", childScript, coreEntry, repoPath, headCommitSha ?? "", JSON.stringify(excludeWorkspaces)], {
|
|
308
|
+
encoding: "utf8",
|
|
309
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
310
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
311
|
+
});
|
|
312
|
+
return JSON.parse(stdout);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
// Fall through to in-process extractor
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const raw = analyzeTarget(repoPath, CORE_EXTRACTOR_VERSION, headCommitSha, excludeWorkspaces);
|
|
320
|
+
const userNodes = raw.nodes.filter((n) => (n.scope ?? "USER") === "USER");
|
|
321
|
+
const userNodeIds = new Set(userNodes.map((n) => n.id));
|
|
322
|
+
return {
|
|
323
|
+
...raw,
|
|
324
|
+
nodes: userNodes,
|
|
325
|
+
edges: raw.edges
|
|
326
|
+
.filter((e) => (e.scope ?? "USER") === "USER")
|
|
327
|
+
.map((e) => e.targetId && !userNodeIds.has(e.targetId)
|
|
328
|
+
? { ...e, targetId: undefined }
|
|
329
|
+
: e),
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function readGitBlobAtCommit(repoPath, commitSha, relPath) {
|
|
333
|
+
try {
|
|
334
|
+
return execFileSync("git", ["-C", repoPath, "show", `${commitSha}:${relPath}`], {
|
|
335
|
+
encoding: "utf8",
|
|
336
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
337
|
+
env: cleanGitEnv(),
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
return null;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
function hasGitCommit(repoPath, commitSha) {
|
|
345
|
+
if (!existsSync(resolve(repoPath, ".git")))
|
|
346
|
+
return false;
|
|
347
|
+
if (!commitSha || !/^[0-9a-f]{7,40}$/i.test(commitSha.trim()))
|
|
348
|
+
return false;
|
|
349
|
+
try {
|
|
350
|
+
execFileSync("git", ["-C", repoPath, "cat-file", "-e", `${commitSha.trim()}^{commit}`], {
|
|
351
|
+
stdio: ["ignore", "ignore", "ignore"],
|
|
352
|
+
env: cleanGitEnv(),
|
|
353
|
+
});
|
|
354
|
+
return true;
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
return false;
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function readGitHeadState(repoPath) {
|
|
361
|
+
if (!existsSync(resolve(repoPath, ".git")))
|
|
362
|
+
return {};
|
|
363
|
+
const env = cleanGitEnv();
|
|
364
|
+
try {
|
|
365
|
+
const headCommitSha = execFileSync("git", ["-C", repoPath, "rev-parse", "HEAD"], {
|
|
366
|
+
encoding: "utf8",
|
|
367
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
368
|
+
env,
|
|
369
|
+
}).trim();
|
|
370
|
+
if (!headCommitSha)
|
|
371
|
+
return {};
|
|
372
|
+
let headCommitEpochMs;
|
|
373
|
+
try {
|
|
374
|
+
const ctRaw = execFileSync("git", ["-C", repoPath, "show", "-s", "--format=%ct", "HEAD"], {
|
|
375
|
+
encoding: "utf8",
|
|
376
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
377
|
+
env,
|
|
378
|
+
}).trim();
|
|
379
|
+
const secs = Number(ctRaw);
|
|
380
|
+
if (Number.isFinite(secs) && secs > 0) {
|
|
381
|
+
headCommitEpochMs = secs * 1000;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
// Ignore timestamp lookup error
|
|
386
|
+
}
|
|
387
|
+
return { headCommitSha, headCommitEpochMs };
|
|
388
|
+
}
|
|
389
|
+
catch {
|
|
390
|
+
return {};
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
function readBaseSnapshotIfMatching(dbPath, baseRaw) {
|
|
394
|
+
try {
|
|
395
|
+
const snapPath = resolve(dirname(dbPath), "base_snapshot.json");
|
|
396
|
+
if (!existsSync(snapPath))
|
|
397
|
+
return null;
|
|
398
|
+
const parsed = JSON.parse(readFileSync(snapPath, "utf8"));
|
|
399
|
+
if (!parsed || typeof parsed !== "object")
|
|
400
|
+
return null;
|
|
401
|
+
if (parsed.analyzedAt && baseRaw.analyzedAt && parsed.analyzedAt !== baseRaw.analyzedAt) {
|
|
402
|
+
return null;
|
|
403
|
+
}
|
|
404
|
+
return parsed;
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Computes structural delta between the saved base graph (projected with baseline plugin files at
|
|
412
|
+
* `baseGraph.commitSha` when available) and the live working tree (`analyzeTarget` + active plugin projections).
|
|
413
|
+
* Checks staleness (`[PAT-DB-03]`, Principle of Incomplete Truth) before reporting a delta.
|
|
414
|
+
*/
|
|
415
|
+
export async function computeGraphDeltaWithShims(repoPath, dbPath, repoId, storageFactory = createSQLiteStorage) {
|
|
416
|
+
const baseRaw = await loadActiveGraphCached(dbPath, repoId, storageFactory);
|
|
417
|
+
if (!baseRaw) {
|
|
418
|
+
throw new Error(`Base graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
419
|
+
}
|
|
420
|
+
const { headCommitSha, headCommitEpochMs } = readGitHeadState(repoPath);
|
|
421
|
+
const excludeWorkspaces = loadRepoExcludeWorkspaces(repoPath);
|
|
422
|
+
const currentRaw = extractLiveUserGraph(repoPath, headCommitSha, excludeWorkspaces);
|
|
423
|
+
const baseSnapshot = readBaseSnapshotIfMatching(dbPath, baseRaw);
|
|
424
|
+
const stalenessReasons = [];
|
|
425
|
+
if (baseRaw.extractorVersion &&
|
|
426
|
+
currentRaw.extractorVersion &&
|
|
427
|
+
baseRaw.extractorVersion !== currentRaw.extractorVersion) {
|
|
428
|
+
stalenessReasons.push({
|
|
429
|
+
code: "EXTRACTOR_VERSION_MISMATCH",
|
|
430
|
+
message: `Base graph was extracted with version '${baseRaw.extractorVersion}', while live extractor is '${currentRaw.extractorVersion}'.`,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
if (headCommitSha && baseRaw.commitSha) {
|
|
434
|
+
const baseSha = baseRaw.commitSha.trim();
|
|
435
|
+
if (!headCommitSha.startsWith(baseSha) && !baseSha.startsWith(headCommitSha)) {
|
|
436
|
+
stalenessReasons.push({
|
|
437
|
+
code: "BASE_COMMIT_BEHIND_HEAD",
|
|
438
|
+
message: `Base graph was analyzed at commit ${baseSha.slice(0, 7)}, which does not match HEAD ${headCommitSha.slice(0, 7)}.`,
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
else if (!baseRaw.commitSha && headCommitEpochMs && baseRaw.analyzedAt) {
|
|
443
|
+
const analyzedMs = Date.parse(baseRaw.analyzedAt);
|
|
444
|
+
if (Number.isFinite(analyzedMs) && analyzedMs + 1000 < headCommitEpochMs) {
|
|
445
|
+
stalenessReasons.push({
|
|
446
|
+
code: "ANALYZED_BEFORE_HEAD",
|
|
447
|
+
message: `Base graph analyzedAt (${baseRaw.analyzedAt}) precedes HEAD commit timestamp.`,
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (baseSnapshot?.workingTreeDirty === true) {
|
|
452
|
+
stalenessReasons.push({
|
|
453
|
+
code: "DIRTY_BASE_SNAPSHOT",
|
|
454
|
+
message: `Base graph was captured while the working tree had uncommitted changes${baseSnapshot.dirtyFiles?.length
|
|
455
|
+
? ` (${baseSnapshot.dirtyFiles.slice(0, 5).join(", ")})`
|
|
456
|
+
: ""}.`,
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
if (stalenessReasons.length > 0) {
|
|
460
|
+
return {
|
|
461
|
+
baseCommitSha: baseRaw.commitSha,
|
|
462
|
+
targetCommitSha: headCommitSha,
|
|
463
|
+
headCommitSha,
|
|
464
|
+
baseExtractorVersion: baseRaw.extractorVersion,
|
|
465
|
+
targetExtractorVersion: currentRaw.extractorVersion,
|
|
466
|
+
baseStatus: "STALE",
|
|
467
|
+
stalenessReasons,
|
|
468
|
+
nodes: {},
|
|
469
|
+
edges: {},
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
const overlayLayers = readRepoOverlayLayerToggles(repoPath);
|
|
473
|
+
const baseProjected = hasGitCommit(repoPath, baseRaw.commitSha)
|
|
474
|
+
? applyActivePluginProjections(baseRaw, {
|
|
475
|
+
repoPath,
|
|
476
|
+
overlayLayers,
|
|
477
|
+
readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, baseRaw.commitSha.trim(), rel),
|
|
478
|
+
})
|
|
479
|
+
: baseRaw;
|
|
480
|
+
const currentProjected = applyActivePluginProjections(currentRaw, {
|
|
481
|
+
repoPath,
|
|
482
|
+
overlayLayers,
|
|
483
|
+
});
|
|
484
|
+
const delta = compareGraphs(baseProjected, currentProjected);
|
|
485
|
+
return {
|
|
486
|
+
...delta,
|
|
487
|
+
headCommitSha,
|
|
488
|
+
baseExtractorVersion: baseRaw.extractorVersion,
|
|
489
|
+
targetExtractorVersion: currentRaw.extractorVersion,
|
|
490
|
+
baseStatus: "FRESH",
|
|
491
|
+
};
|
|
492
|
+
}
|
|
493
|
+
function resolveMcpGitCommitSha(repoPath, ref) {
|
|
494
|
+
const cleanRef = ref.trim();
|
|
495
|
+
if (!cleanRef || cleanRef.startsWith("-"))
|
|
496
|
+
return null;
|
|
497
|
+
try {
|
|
498
|
+
const sha = execFileSync("git", ["-C", repoPath, "rev-parse", "--verify", `${cleanRef}^{commit}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env: cleanGitEnv() }).trim();
|
|
499
|
+
return /^[0-9a-f]{40}$/i.test(sha) ? sha : null;
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
function extractMcpArchivedGraph(repoPath, fullCommitSha, excludeWorkspaces, dbPath) {
|
|
506
|
+
const cacheDir = dbPath
|
|
507
|
+
? join(dirname(dbPath), "cache")
|
|
508
|
+
: resolve(repoPath, ".chomp", "cache");
|
|
509
|
+
const cachePath = join(cacheDir, `ref-graph-${fullCommitSha.slice(0, 12)}.json`);
|
|
510
|
+
if (existsSync(cachePath)) {
|
|
511
|
+
try {
|
|
512
|
+
const parsed = JSON.parse(readFileSync(cachePath, "utf8"));
|
|
513
|
+
if (parsed?.extractorVersion === CORE_EXTRACTOR_VERSION &&
|
|
514
|
+
parsed?.fullCommitSha === fullCommitSha &&
|
|
515
|
+
parsed?.graph &&
|
|
516
|
+
Array.isArray(parsed.graph.nodes)) {
|
|
517
|
+
return parsed.graph;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
catch {
|
|
521
|
+
// Fall through to archive extraction
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
const tempDir = join(tmpdir(), `chomp-mcp-ref-${fullCommitSha.slice(0, 10)}-${Date.now()}-${Math.random()
|
|
525
|
+
.toString(36)
|
|
526
|
+
.slice(2, 6)}`);
|
|
527
|
+
const archiveRoot = join(tempDir, basename(resolve(repoPath)) || "repo");
|
|
528
|
+
mkdirSync(archiveRoot, { recursive: true });
|
|
529
|
+
try {
|
|
530
|
+
const archiveBuf = execFileSync("git", ["-C", repoPath, "archive", "--format=tar", fullCommitSha], { maxBuffer: 128 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"], env: cleanGitEnv() });
|
|
531
|
+
execFileSync("tar", ["-x", "-C", archiveRoot], {
|
|
532
|
+
input: archiveBuf,
|
|
533
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
534
|
+
});
|
|
535
|
+
const graph = extractLiveUserGraph(archiveRoot, fullCommitSha, excludeWorkspaces);
|
|
536
|
+
try {
|
|
537
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
538
|
+
writeFileSync(cachePath, JSON.stringify({
|
|
539
|
+
extractorVersion: CORE_EXTRACTOR_VERSION,
|
|
540
|
+
fullCommitSha,
|
|
541
|
+
savedAt: new Date().toISOString(),
|
|
542
|
+
graph,
|
|
543
|
+
}), "utf8");
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
// Non-fatal
|
|
547
|
+
}
|
|
548
|
+
return graph;
|
|
549
|
+
}
|
|
550
|
+
finally {
|
|
551
|
+
if (existsSync(tempDir)) {
|
|
552
|
+
rmSync(tempDir, { recursive: true, force: true });
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function inspectMcpRepoGitBranches(repoPath) {
|
|
557
|
+
const env = cleanGitEnv();
|
|
558
|
+
let currentBranch = "HEAD";
|
|
559
|
+
let defaultBaseBranch = "main";
|
|
560
|
+
let hasDefaultBase = false;
|
|
561
|
+
let workingTreeDirty = false;
|
|
562
|
+
try {
|
|
563
|
+
currentBranch =
|
|
564
|
+
execFileSync("git", ["-C", repoPath, "rev-parse", "--abbrev-ref", "HEAD"], {
|
|
565
|
+
encoding: "utf8",
|
|
566
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
567
|
+
env,
|
|
568
|
+
}).trim() || "HEAD";
|
|
569
|
+
const refsOut = execFileSync("git", ["-C", repoPath, "for-each-ref", "--format=%(refname:short)", "refs/heads"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env });
|
|
570
|
+
const branches = new Set(refsOut.split("\n").map((s) => s.trim()).filter(Boolean));
|
|
571
|
+
if (branches.has("main")) {
|
|
572
|
+
defaultBaseBranch = "main";
|
|
573
|
+
hasDefaultBase = true;
|
|
574
|
+
}
|
|
575
|
+
else if (branches.has("master")) {
|
|
576
|
+
defaultBaseBranch = "master";
|
|
577
|
+
hasDefaultBase = true;
|
|
578
|
+
}
|
|
579
|
+
else {
|
|
580
|
+
defaultBaseBranch = currentBranch;
|
|
581
|
+
}
|
|
582
|
+
const statusOut = execFileSync("git", ["-C", repoPath, "status", "--porcelain", "-uall"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], env });
|
|
583
|
+
for (const line of statusOut.split("\n")) {
|
|
584
|
+
if (!line || line.length < 4)
|
|
585
|
+
continue;
|
|
586
|
+
const relPath = line.slice(3).trim().replace(/\\/g, "/");
|
|
587
|
+
if ((relPath.startsWith(".chomp/") || relPath === ".chomp") &&
|
|
588
|
+
!relPath.startsWith(".chomp/plugins/") &&
|
|
589
|
+
relPath !== ".chomp/shims.json") {
|
|
590
|
+
continue;
|
|
591
|
+
}
|
|
592
|
+
workingTreeDirty = true;
|
|
593
|
+
break;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
// Ignore git inspection failures
|
|
598
|
+
}
|
|
599
|
+
return { currentBranch, defaultBaseBranch, hasDefaultBase, workingTreeDirty };
|
|
600
|
+
}
|
|
601
|
+
export async function computeGitRefDeltaWithShims(repoPath, options) {
|
|
602
|
+
const { currentBranch, defaultBaseBranch, hasDefaultBase, workingTreeDirty } = inspectMcpRepoGitBranches(repoPath);
|
|
603
|
+
const { headCommitSha } = readGitHeadState(repoPath);
|
|
604
|
+
const rawTarget = options?.targetRef?.trim();
|
|
605
|
+
const normalizedTarget = rawTarget &&
|
|
606
|
+
(rawTarget.toUpperCase() === "WORKING_TREE" ||
|
|
607
|
+
rawTarget.toLowerCase() === "working-tree")
|
|
608
|
+
? "WORKING_TREE"
|
|
609
|
+
: rawTarget || undefined;
|
|
610
|
+
const normalizedBase = options?.baseRef?.trim() || undefined;
|
|
611
|
+
const baseRef = normalizedBase ??
|
|
612
|
+
(normalizedTarget === "WORKING_TREE"
|
|
613
|
+
? currentBranch
|
|
614
|
+
: !workingTreeDirty && currentBranch !== defaultBaseBranch && hasDefaultBase
|
|
615
|
+
? defaultBaseBranch
|
|
616
|
+
: currentBranch);
|
|
617
|
+
const targetRef = normalizedTarget ??
|
|
618
|
+
(workingTreeDirty
|
|
619
|
+
? "WORKING_TREE"
|
|
620
|
+
: currentBranch !== baseRef
|
|
621
|
+
? currentBranch
|
|
622
|
+
: "WORKING_TREE");
|
|
623
|
+
const baseSha = resolveMcpGitCommitSha(repoPath, baseRef);
|
|
624
|
+
if (!baseSha) {
|
|
625
|
+
throw new Error(`Unable to resolve base git ref '${baseRef}' in ${repoPath}.`);
|
|
626
|
+
}
|
|
627
|
+
const excludeWorkspaces = loadRepoExcludeWorkspaces(repoPath);
|
|
628
|
+
const overlayLayers = readRepoOverlayLayerToggles(repoPath);
|
|
629
|
+
const baseRaw = extractMcpArchivedGraph(repoPath, baseSha, excludeWorkspaces, options?.dbPath);
|
|
630
|
+
const baseProjected = applyActivePluginProjections(baseRaw, {
|
|
631
|
+
repoPath,
|
|
632
|
+
overlayLayers,
|
|
633
|
+
readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, baseSha, rel),
|
|
634
|
+
});
|
|
635
|
+
if (targetRef !== "WORKING_TREE") {
|
|
636
|
+
const targetSha = resolveMcpGitCommitSha(repoPath, targetRef);
|
|
637
|
+
if (!targetSha) {
|
|
638
|
+
throw new Error(`Unable to resolve target git ref '${targetRef}' in ${repoPath}.`);
|
|
639
|
+
}
|
|
640
|
+
const targetRaw = extractMcpArchivedGraph(repoPath, targetSha, excludeWorkspaces, options?.dbPath);
|
|
641
|
+
const targetProjected = applyActivePluginProjections(targetRaw, {
|
|
642
|
+
repoPath,
|
|
643
|
+
overlayLayers,
|
|
644
|
+
readRepoFileOverride: (rel) => readGitBlobAtCommit(repoPath, targetSha, rel),
|
|
645
|
+
});
|
|
646
|
+
const delta = compareGraphs(baseProjected, targetProjected);
|
|
647
|
+
return {
|
|
648
|
+
...delta,
|
|
649
|
+
baseCommitSha: baseSha,
|
|
650
|
+
targetCommitSha: targetSha,
|
|
651
|
+
headCommitSha,
|
|
652
|
+
baseExtractorVersion: CORE_EXTRACTOR_VERSION,
|
|
653
|
+
targetExtractorVersion: CORE_EXTRACTOR_VERSION,
|
|
654
|
+
baseStatus: "FRESH",
|
|
655
|
+
baseRef,
|
|
656
|
+
targetRef,
|
|
657
|
+
isWorkingTreeSnapshot: false,
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
const snapshotAt = new Date().toISOString();
|
|
661
|
+
const currentRaw = extractLiveUserGraph(repoPath, headCommitSha, excludeWorkspaces);
|
|
662
|
+
const currentProjected = applyActivePluginProjections(currentRaw, {
|
|
663
|
+
repoPath,
|
|
664
|
+
overlayLayers,
|
|
665
|
+
});
|
|
666
|
+
const delta = compareGraphs(baseProjected, currentProjected);
|
|
667
|
+
return {
|
|
668
|
+
...delta,
|
|
669
|
+
baseCommitSha: baseSha,
|
|
670
|
+
headCommitSha,
|
|
671
|
+
baseExtractorVersion: CORE_EXTRACTOR_VERSION,
|
|
672
|
+
targetExtractorVersion: CORE_EXTRACTOR_VERSION,
|
|
673
|
+
baseStatus: "FRESH",
|
|
674
|
+
baseRef,
|
|
675
|
+
targetRef: "WORKING_TREE",
|
|
676
|
+
isWorkingTreeSnapshot: true,
|
|
677
|
+
snapshotAt,
|
|
678
|
+
};
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Wraps an MCP tool handler so uncaught errors return a structured
|
|
682
|
+
* `{ isError: true, content: [{ type: "text", text }] }` payload rather than
|
|
683
|
+
* crashing the stdio transport or leaking resources.
|
|
684
|
+
*/
|
|
685
|
+
export function withMcpToolErrorBoundary(handler) {
|
|
686
|
+
return async (args) => {
|
|
687
|
+
try {
|
|
688
|
+
return await handler(args);
|
|
689
|
+
}
|
|
690
|
+
catch (err) {
|
|
691
|
+
const message = err instanceof Error ? err.message : String(err ?? "Unknown MCP tool error");
|
|
692
|
+
return {
|
|
693
|
+
isError: true,
|
|
694
|
+
content: [{ type: "text", text: message }],
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
export async function runMcpServer(targetPath = process.cwd()) {
|
|
700
|
+
const initialRepo = resolveActiveMcpRepo(targetPath);
|
|
701
|
+
const repoLocalPluginsDir = resolve(initialRepo.repoPath, ".chomp", "plugins");
|
|
702
|
+
if (existsSync(repoLocalPluginsDir)) {
|
|
703
|
+
await discoverPluginsInDir(repoLocalPluginsDir);
|
|
704
|
+
}
|
|
705
|
+
const server = new McpServer({
|
|
706
|
+
name: "chomp-mcp-server",
|
|
707
|
+
version: "0.1.0",
|
|
708
|
+
});
|
|
709
|
+
server.tool("chomp_get_nodes", "MANDATORY FIRST STEP (MAP-FIRST NAVIGATION): Retrieves structural nodes from the persisted Chomp graph. Pass `search_term` and/or `packageName` BEFORE reading any files to resolve the exact node IDs of target Services, Routes, Components, and Functions. Only follow up with `chomp_create_view` when the user is asking an architectural question, querying how a flow works, or explicitly requesting a visual highlight/walkthrough (do NOT invoke `chomp_create_view` on routine coding or implementation prompts). Files and directories are not graph nodes: each node's source file and line live in its evidence records, and BOUNDARY nodes are only DEPLOYMENT_UNIT, CLASS, NAMESPACE or INIT_BLOCK.", {
|
|
710
|
+
search_term: z.string().optional().describe("Fast-path case-insensitive search term matching node name, id, humanLabel, domain, summary, or evidence filePath (use this to quickly resolve target node IDs)"),
|
|
711
|
+
searchTerm: z.string().optional().describe("Alias for search_term (camelCase)"),
|
|
712
|
+
packageName: z.string().optional().describe("Optional filter by owning package / DEPLOYMENT_UNIT name (e.g., 'mcp', '@getchomp/mcp', 'core', 'web', 'cli', 'db')"),
|
|
713
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
714
|
+
type: z.string().optional().describe("Optional filter by node type (e.g., BOUNDARY, CONTRACT, OPEN_CONNECTOR)"),
|
|
715
|
+
entityType: z.string().optional().describe("Optional filter by entity type (e.g., DEPLOYMENT_UNIT, CLASS, NAMESPACE, INIT_BLOCK, EXPORTED_FUNCTION, PUBLIC_METHOD, EXPORTED_MODULE, HTTP_ENDPOINT, MIDDLEWARE, EXTERNAL_PACKAGE)"),
|
|
716
|
+
entity_type: z.string().optional().describe("Alias for entityType (snake_case)"),
|
|
717
|
+
parent_boundary_id: z.string().optional().describe("Optional filter by parent boundary ID (the owning DEPLOYMENT_UNIT, CLASS, or NAMESPACE node ID — never a file)"),
|
|
718
|
+
parentBoundaryId: z.string().optional().describe("Alias for parent_boundary_id (camelCase)"),
|
|
719
|
+
name: z.string().optional().describe("Optional case-insensitive substring filter on node name (e.g., 'visitContract', 'SQLiteStorage', '/api/layout')"),
|
|
720
|
+
file_path: z.string().optional().describe("Optional case-insensitive substring filter on the node's evidence filePath (e.g., 'contractVisitor.ts', 'packages/core')"),
|
|
721
|
+
filePath: z.string().optional().describe("Alias for file_path (camelCase)"),
|
|
722
|
+
include_overlays: z.boolean().optional().describe("When true, attaches entity_overlays records onto each returned node. Defaults to false unless layers/layer is specified, keeping structural queries compact."),
|
|
723
|
+
includeOverlays: z.boolean().optional().describe("Alias for include_overlays (camelCase)"),
|
|
724
|
+
layers: z.array(z.string()).optional().describe("Optional list of overlay layers to hydrate on returned nodes (e.g. ['L1_SEMANTIC', 'L1_DESIGN_SYSTEM']). Implicitly enables overlay hydration for those layers."),
|
|
725
|
+
layer: z.string().optional().describe("Optional single overlay layer to hydrate on returned nodes"),
|
|
726
|
+
enrichment_status: z
|
|
727
|
+
.enum(["enriched", "unenriched", "stale"])
|
|
728
|
+
.optional()
|
|
729
|
+
.describe("Optional filter by L1_SEMANTIC enrichment status ('enriched', 'unenriched', or 'stale')"),
|
|
730
|
+
enrichmentStatus: z
|
|
731
|
+
.enum(["enriched", "unenriched", "stale"])
|
|
732
|
+
.optional()
|
|
733
|
+
.describe("Alias for enrichment_status (camelCase)")
|
|
734
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
735
|
+
const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
736
|
+
if (!existsSync(dbPath)) {
|
|
737
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please ask the user to run 'chomp analyze .' in the repository root first.`);
|
|
738
|
+
}
|
|
739
|
+
const requestedLayers = [
|
|
740
|
+
...(args.layers ?? []),
|
|
741
|
+
...(args.layer ? [args.layer] : []),
|
|
742
|
+
]
|
|
743
|
+
.map((l) => l.trim())
|
|
744
|
+
.filter(Boolean);
|
|
745
|
+
const includeOverlays = args.include_overlays ?? args.includeOverlays ?? (requestedLayers.length > 0);
|
|
746
|
+
const searchTerm = args.search_term ?? args.searchTerm;
|
|
747
|
+
const enrichmentStatus = args.enrichment_status ?? args.enrichmentStatus;
|
|
748
|
+
const needsSemanticFilter = Boolean(enrichmentStatus);
|
|
749
|
+
const overlayLayerFilter = requestedLayers.length > 0 && !searchTerm && !needsSemanticFilter
|
|
750
|
+
? requestedLayers
|
|
751
|
+
: needsSemanticFilter && !includeOverlays && !searchTerm
|
|
752
|
+
? [SEMANTIC_OVERLAY_LAYER]
|
|
753
|
+
: undefined;
|
|
754
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
755
|
+
const overlays = includeOverlays || Boolean(searchTerm) || needsSemanticFilter
|
|
756
|
+
? await withStorage(dbPath, (storage) => storage.getEntityOverlays(repoId, overlayLayerFilter ? { layers: overlayLayerFilter } : undefined))
|
|
757
|
+
: [];
|
|
758
|
+
if (!graph) {
|
|
759
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
760
|
+
}
|
|
761
|
+
const overlaysByEntityId = new Map();
|
|
762
|
+
for (const ov of overlays) {
|
|
763
|
+
let list = overlaysByEntityId.get(ov.entityId);
|
|
764
|
+
if (!list) {
|
|
765
|
+
list = [];
|
|
766
|
+
overlaysByEntityId.set(ov.entityId, list);
|
|
767
|
+
}
|
|
768
|
+
list.push(ov);
|
|
769
|
+
}
|
|
770
|
+
let matchedNodes = filterNodesForMcp(graph, {
|
|
771
|
+
type: args.type,
|
|
772
|
+
entityType: args.entityType ?? args.entity_type,
|
|
773
|
+
parentBoundaryId: args.parent_boundary_id ?? args.parentBoundaryId,
|
|
774
|
+
name: args.name,
|
|
775
|
+
filePath: args.file_path ?? args.filePath,
|
|
776
|
+
searchTerm,
|
|
777
|
+
packageName: args.packageName ?? args.package_name,
|
|
778
|
+
overlaysByEntityId,
|
|
779
|
+
});
|
|
780
|
+
if (enrichmentStatus) {
|
|
781
|
+
const semMap = classifySemanticOverlayMap(graph, overlays, true);
|
|
782
|
+
matchedNodes = matchedNodes.filter((n) => {
|
|
783
|
+
if (!isEnrichmentTargetNode(n, true))
|
|
784
|
+
return false;
|
|
785
|
+
const sem = semMap.get(n.id);
|
|
786
|
+
if (enrichmentStatus === "unenriched")
|
|
787
|
+
return !sem;
|
|
788
|
+
if (enrichmentStatus === "stale")
|
|
789
|
+
return Boolean(sem?.stale);
|
|
790
|
+
return Boolean(sem);
|
|
791
|
+
});
|
|
792
|
+
}
|
|
793
|
+
const filteredNodes = hydrateNodeOverlays(matchedNodes, overlays, {
|
|
794
|
+
includeOverlays,
|
|
795
|
+
layers: requestedLayers,
|
|
796
|
+
});
|
|
797
|
+
return {
|
|
798
|
+
content: [{ type: "text", text: JSON.stringify(filteredNodes, null, 2) }]
|
|
799
|
+
};
|
|
800
|
+
}));
|
|
801
|
+
server.tool("chomp_get_edges", "Use this tool to trace execution paths. If you need to know what a function calls, or what calls a function, pass the node ID here instead of using global text search. Edges originate from contracts, classes, public methods, or INIT_BLOCKs (top-level code run on module load) — never from files or DEPLOYMENT_UNITs — and calls into imported packages target `Package: X` OPEN_CONNECTORs.", {
|
|
802
|
+
source_id: z.string().optional().describe("Optional filter by the source node ID"),
|
|
803
|
+
sourceId: z.string().optional().describe("Alias for source_id (camelCase)"),
|
|
804
|
+
target_id: z.string().optional().describe("Optional filter by the target node ID"),
|
|
805
|
+
targetId: z.string().optional().describe("Alias for target_id (camelCase)"),
|
|
806
|
+
name: z.string().optional().describe("Optional case-insensitive substring filter on the edge name (e.g., 'visitContract', 'INTERCEPTS', 'db.prepare')"),
|
|
807
|
+
resolved_only: z.boolean().optional().describe("When true, returns only edges with a resolved targetId, suppressing unresolved LOW-confidence platform method calls"),
|
|
808
|
+
resolvedOnly: z.boolean().optional().describe("Alias for resolved_only (camelCase)"),
|
|
809
|
+
min_confidence: z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Optional minimum confidence threshold (LOW, MEDIUM, or HIGH). DETERMINISTIC edges always count as HIGH."),
|
|
810
|
+
minConfidence: z.enum(["LOW", "MEDIUM", "HIGH"]).optional().describe("Alias for min_confidence (camelCase)")
|
|
811
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
812
|
+
const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
813
|
+
if (!existsSync(dbPath)) {
|
|
814
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please ask the user to run 'chomp analyze .' in the repository root first.`);
|
|
815
|
+
}
|
|
816
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
817
|
+
if (!graph) {
|
|
818
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
819
|
+
}
|
|
820
|
+
const sourceFilter = args.source_id ?? args.sourceId;
|
|
821
|
+
const targetFilter = args.target_id ?? args.targetId;
|
|
822
|
+
const nameFilter = args.name?.toLowerCase();
|
|
823
|
+
const resolvedOnly = args.resolved_only ?? args.resolvedOnly;
|
|
824
|
+
const minConfidence = args.min_confidence ?? args.minConfidence;
|
|
825
|
+
const confidenceRank = {
|
|
826
|
+
LOW: 1,
|
|
827
|
+
MEDIUM: 2,
|
|
828
|
+
HIGH: 3,
|
|
829
|
+
};
|
|
830
|
+
let filteredEdges = graph.edges;
|
|
831
|
+
if (sourceFilter) {
|
|
832
|
+
filteredEdges = filteredEdges.filter((e) => e.sourceId === sourceFilter);
|
|
833
|
+
}
|
|
834
|
+
if (targetFilter) {
|
|
835
|
+
filteredEdges = filteredEdges.filter((e) => e.targetId === targetFilter);
|
|
836
|
+
}
|
|
837
|
+
if (nameFilter) {
|
|
838
|
+
filteredEdges = filteredEdges.filter((e) => typeof e.name === "string" && e.name.toLowerCase().includes(nameFilter));
|
|
839
|
+
}
|
|
840
|
+
if (resolvedOnly) {
|
|
841
|
+
filteredEdges = filteredEdges.filter((e) => Boolean(e.targetId));
|
|
842
|
+
}
|
|
843
|
+
if (minConfidence) {
|
|
844
|
+
const minRank = confidenceRank[minConfidence] ?? 1;
|
|
845
|
+
filteredEdges = filteredEdges.filter((e) => {
|
|
846
|
+
const edgeRank = e.entityType === "DETERMINISTIC" || e.confidence === "HIGH"
|
|
847
|
+
? 3
|
|
848
|
+
: e.confidence === "MEDIUM"
|
|
849
|
+
? 2
|
|
850
|
+
: 1;
|
|
851
|
+
return edgeRank >= minRank;
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
return {
|
|
855
|
+
content: [{ type: "text", text: JSON.stringify(filteredEdges, null, 2) }]
|
|
856
|
+
};
|
|
857
|
+
}));
|
|
858
|
+
server.tool("chomp_get_diff", "Compares two git branches/commits (baseRef -> targetRef) or a point-in-time working-tree snapshot against the saved base graph in the Chomp SQLite database. Returns a structural delta summary and the ADDED, REMOVED, and MODIFIED entities (excluding UNCHANGED and LEXICAL_SHIFT noise by default).", {
|
|
859
|
+
baseRef: z.string().optional().describe("Optional base git branch or commit SHA (e.g. 'main')"),
|
|
860
|
+
base_ref: z.string().optional().describe("Alias for baseRef (snake_case)"),
|
|
861
|
+
targetRef: z.string().optional().describe("Optional target git branch, commit SHA, or 'WORKING_TREE' (defaults to 'WORKING_TREE' when uncommitted edits exist, or current branch vs main when clean)"),
|
|
862
|
+
target_ref: z.string().optional().describe("Alias for targetRef (snake_case)"),
|
|
863
|
+
include_lexical_shift: z.boolean().optional().describe("When true, includes LEXICAL_SHIFT entries (line-number-only shifts) in nodes/edges"),
|
|
864
|
+
includeLexicalShift: z.boolean().optional().describe("Alias for include_lexical_shift (camelCase)"),
|
|
865
|
+
include_unchanged: z.boolean().optional().describe("When true, includes UNCHANGED entries in nodes/edges"),
|
|
866
|
+
includeUnchanged: z.boolean().optional().describe("Alias for include_unchanged (camelCase)")
|
|
867
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
868
|
+
const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
869
|
+
const requestedBase = args.baseRef ?? args.base_ref;
|
|
870
|
+
const requestedTarget = args.targetRef ?? args.target_ref;
|
|
871
|
+
const gitState = inspectMcpRepoGitBranches(repoPath);
|
|
872
|
+
const shouldUseRefDiff = Boolean(requestedBase || requestedTarget) ||
|
|
873
|
+
!existsSync(dbPath) ||
|
|
874
|
+
(!gitState.workingTreeDirty &&
|
|
875
|
+
gitState.currentBranch !== "HEAD" &&
|
|
876
|
+
gitState.currentBranch !== gitState.defaultBaseBranch &&
|
|
877
|
+
gitState.hasDefaultBase);
|
|
878
|
+
let delta;
|
|
879
|
+
if (shouldUseRefDiff) {
|
|
880
|
+
delta = await computeGitRefDeltaWithShims(repoPath, {
|
|
881
|
+
baseRef: requestedBase,
|
|
882
|
+
targetRef: requestedTarget,
|
|
883
|
+
dbPath,
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
else {
|
|
887
|
+
delta = await computeGraphDeltaWithShims(repoPath, dbPath, repoId);
|
|
888
|
+
}
|
|
889
|
+
if (delta.baseStatus === "STALE") {
|
|
890
|
+
return {
|
|
891
|
+
content: [
|
|
892
|
+
{
|
|
893
|
+
type: "text",
|
|
894
|
+
text: JSON.stringify({
|
|
895
|
+
status: "STALE_BASE_UNKNOWN",
|
|
896
|
+
baseStatus: "STALE",
|
|
897
|
+
stale: true,
|
|
898
|
+
baseCommitSha: delta.baseCommitSha,
|
|
899
|
+
headCommitSha: delta.headCommitSha,
|
|
900
|
+
baseExtractorVersion: delta.baseExtractorVersion,
|
|
901
|
+
targetExtractorVersion: delta.targetExtractorVersion,
|
|
902
|
+
stalenessReasons: delta.stalenessReasons ?? [],
|
|
903
|
+
remediation: "Base graph in .chomp/graph.db is stale or was captured from a dirty working tree. Run 'chomp analyze .' on a clean HEAD to refresh the baseline, or pass baseRef/targetRef to chomp_get_diff.",
|
|
904
|
+
summary: null,
|
|
905
|
+
nodes: {},
|
|
906
|
+
edges: {},
|
|
907
|
+
}, null, 2),
|
|
908
|
+
},
|
|
909
|
+
],
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
const includeLexical = Boolean(args?.include_lexical_shift ?? args?.includeLexicalShift);
|
|
913
|
+
const includeUnchanged = Boolean(args?.include_unchanged ?? args?.includeUnchanged);
|
|
914
|
+
const countStatuses = (record) => {
|
|
915
|
+
const counts = { ADDED: 0, MODIFIED: 0, REMOVED: 0, LEXICAL_SHIFT: 0, UNCHANGED: 0 };
|
|
916
|
+
for (const entry of Object.values(record)) {
|
|
917
|
+
if (entry.status in counts) {
|
|
918
|
+
counts[entry.status]++;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
return counts;
|
|
922
|
+
};
|
|
923
|
+
const filterEntries = (record) => {
|
|
924
|
+
const out = {};
|
|
925
|
+
for (const [id, entry] of Object.entries(record)) {
|
|
926
|
+
if (entry.status === "UNCHANGED" && !includeUnchanged)
|
|
927
|
+
continue;
|
|
928
|
+
if (entry.status === "LEXICAL_SHIFT" && !includeLexical)
|
|
929
|
+
continue;
|
|
930
|
+
out[id] = entry;
|
|
931
|
+
}
|
|
932
|
+
return out;
|
|
933
|
+
};
|
|
934
|
+
const compactDelta = {
|
|
935
|
+
baseStatus: delta.baseStatus ?? "FRESH",
|
|
936
|
+
...(delta.baseRef ? { baseRef: delta.baseRef } : {}),
|
|
937
|
+
baseCommitSha: delta.baseCommitSha,
|
|
938
|
+
...(delta.targetRef ? { targetRef: delta.targetRef } : {}),
|
|
939
|
+
targetCommitSha: delta.targetCommitSha,
|
|
940
|
+
headCommitSha: delta.headCommitSha,
|
|
941
|
+
...(delta.isWorkingTreeSnapshot !== undefined
|
|
942
|
+
? { isWorkingTreeSnapshot: delta.isWorkingTreeSnapshot }
|
|
943
|
+
: {}),
|
|
944
|
+
...(delta.snapshotAt ? { snapshotAt: delta.snapshotAt } : {}),
|
|
945
|
+
baseExtractorVersion: delta.baseExtractorVersion,
|
|
946
|
+
targetExtractorVersion: delta.targetExtractorVersion,
|
|
947
|
+
summary: {
|
|
948
|
+
nodes: countStatuses(delta.nodes),
|
|
949
|
+
edges: countStatuses(delta.edges),
|
|
950
|
+
},
|
|
951
|
+
nodes: filterEntries(delta.nodes),
|
|
952
|
+
edges: filterEntries(delta.edges),
|
|
953
|
+
};
|
|
954
|
+
return {
|
|
955
|
+
content: [{ type: "text", text: JSON.stringify(compactDelta, null, 2) }]
|
|
956
|
+
};
|
|
957
|
+
}));
|
|
958
|
+
server.tool("chomp_create_view", "QUERY-SCOPED SPOTLIGHT: Controls the frontend UI state by highlighting specific nodes (ACTIVE state) in the graph view, selecting the topological height (`viewLevel: 'system' | 'package'`), and returning a one-click markdown deep-link URL (`viewUrl`) that you can share directly in chat. Invoke this tool ONLY when the user is asking an architectural question, querying how a flow works, or explicitly requesting a visual highlight/walkthrough—do NOT auto-fire this tool on routine coding, refactoring, or implementation prompts. When invoked for a question or walkthrough, call it immediately after resolving target node IDs via `chomp_get_nodes` (or pass `search_term` / `packageName` directly here) before reading source files or composing explanations. Pass the IDs of CONTRACT nodes (functions, public methods, endpoints, components), CLASS / NAMESPACE / INIT_BLOCK boundary nodes, or OPEN_CONNECTOR nodes. Files and directories are not graph nodes.", {
|
|
959
|
+
title: z.string().describe("Title for the view banner"),
|
|
960
|
+
description: z.string().describe("Description for the view banner"),
|
|
961
|
+
highlightNodeIds: z.array(z.string()).optional().describe("List of node IDs to highlight (set to ACTIVE state) in the graph"),
|
|
962
|
+
highlight_node_ids: z.array(z.string()).optional().describe("Alias for highlightNodeIds (snake_case)"),
|
|
963
|
+
search_term: z.string().optional().describe("Optional fast-path search term to automatically resolve and highlight matching node IDs without a separate round-trip"),
|
|
964
|
+
searchTerm: z.string().optional().describe("Alias for search_term (camelCase)"),
|
|
965
|
+
packageName: z.string().optional().describe("Optional package filter when resolving nodes via search_term, or target package when viewLevel is 'package' (e.g., 'mcp', 'core', 'web', 'cli', 'db')"),
|
|
966
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
967
|
+
viewLevel: z.enum(["system", "package"]).optional().describe("Optional zoom level for the view ('system' = System view across packages; 'package' = Package view inside a single package). Defaults to 'system' when highlighted nodes span multiple packages, and 'package' for single-package flows."),
|
|
968
|
+
view_level: z.enum(["system", "package"]).optional().describe("Alias for viewLevel (snake_case)"),
|
|
969
|
+
layer: z.string().optional().describe("Optional overlay layer associated with this view (e.g., 'L1_DESIGN_SYSTEM', 'L2_RUNTIME', 'PLUGIN:a11y'). Automatically enables this overlay layer in the UI while the Spotlight view is open."),
|
|
970
|
+
source: z.string().optional().describe("Optional plugin/producer source label for the view banner"),
|
|
971
|
+
pills: z.array(z.string()).optional().describe("Optional summary pills/badges rendered in the Agent Spotlight banner"),
|
|
972
|
+
metrics: z.record(z.union([z.string(), z.number()])).optional().describe("Optional key-value metric summary rendered in the Agent Spotlight banner"),
|
|
973
|
+
nodeAnnotations: z.record(z.string()).optional().describe("Optional map of nodeId -> short annotation note displayed for highlighted nodes in the Agent Spotlight banner")
|
|
974
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
975
|
+
const { repoPath, repoName, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
976
|
+
const explicitIds = args.highlightNodeIds ?? args.highlight_node_ids ?? [];
|
|
977
|
+
const searchTerm = args.search_term ?? args.searchTerm;
|
|
978
|
+
const packageName = args.packageName ?? args.package_name;
|
|
979
|
+
const explicitViewLevel = args.viewLevel ?? args.view_level;
|
|
980
|
+
let resolvedGraph = null;
|
|
981
|
+
if (existsSync(dbPath)) {
|
|
982
|
+
resolvedGraph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
983
|
+
}
|
|
984
|
+
const highlightIds = resolveViewNodeIds(resolvedGraph, explicitIds, searchTerm, packageName);
|
|
985
|
+
const altitude = resolveViewTargetAltitude(resolvedGraph, highlightIds, explicitViewLevel, packageName);
|
|
986
|
+
const branchName = resolveRepoGitBranch(repoPath, resolvedGraph?.branchName);
|
|
987
|
+
const viewUrl = buildActiveViewUrl({
|
|
988
|
+
baseUrl: resolveActiveUiBaseUrl(repoPath),
|
|
989
|
+
viewLevel: altitude.viewLevel,
|
|
990
|
+
packageName: altitude.packageName,
|
|
991
|
+
});
|
|
992
|
+
const createdAt = new Date().toISOString();
|
|
993
|
+
const viewData = {
|
|
994
|
+
repoId,
|
|
995
|
+
repoName,
|
|
996
|
+
...(branchName ? { branchName } : {}),
|
|
997
|
+
createdAt,
|
|
998
|
+
viewLevel: altitude.viewLevel,
|
|
999
|
+
...(altitude.packageName ? { packageName: altitude.packageName } : {}),
|
|
1000
|
+
viewUrl,
|
|
1001
|
+
title: args.title,
|
|
1002
|
+
description: args.description,
|
|
1003
|
+
highlightNodeIds: highlightIds,
|
|
1004
|
+
...(args.layer ? { layer: args.layer } : {}),
|
|
1005
|
+
source: args.source || "custom_query",
|
|
1006
|
+
...(args.pills && args.pills.length > 0 ? { pills: args.pills } : {}),
|
|
1007
|
+
...(args.metrics && Object.keys(args.metrics).length > 0
|
|
1008
|
+
? { metrics: args.metrics }
|
|
1009
|
+
: {}),
|
|
1010
|
+
...(args.nodeAnnotations && Object.keys(args.nodeAnnotations).length > 0
|
|
1011
|
+
? { nodeAnnotations: args.nodeAnnotations }
|
|
1012
|
+
: {}),
|
|
1013
|
+
};
|
|
1014
|
+
const viewPath = resolve(repoPath, ".chomp", "current_view.json");
|
|
1015
|
+
mkdirSync(dirname(viewPath), { recursive: true });
|
|
1016
|
+
writeFileSync(viewPath, JSON.stringify(viewData, null, 2), "utf8");
|
|
1017
|
+
return {
|
|
1018
|
+
content: [
|
|
1019
|
+
{
|
|
1020
|
+
type: "text",
|
|
1021
|
+
text: `View successfully created (${highlightIds.length} node(s) highlighted, level: ${altitude.viewLevel}${altitude.packageName ? `, package: ${altitude.packageName}` : ""}).\nOpen in Chomp Map: [${args.title}](${viewUrl})`
|
|
1022
|
+
}
|
|
1023
|
+
]
|
|
1024
|
+
};
|
|
1025
|
+
}));
|
|
1026
|
+
server.tool("chomp_visualizer_audit", "Compares the raw Chomp database graph against the final visual LayoutData to identify where the visualizer is dropping data, misrepresenting packages, or failing the Circuit Board ideal.", withMcpToolErrorBoundary(async () => {
|
|
1027
|
+
const { repoPath } = resolveActiveMcpRepo(targetPath);
|
|
1028
|
+
const globalResearchBin = resolve(homedir(), ".local", "bin", "chomp-research");
|
|
1029
|
+
const monoRoot = resolve(MCP_THIS_DIR, "../../..");
|
|
1030
|
+
const researchEntry = resolve(monoRoot, "fixtures/research/research-cli/src/index.ts");
|
|
1031
|
+
const tsxBin = findTsxBinary();
|
|
1032
|
+
const cmd = existsSync(globalResearchBin)
|
|
1033
|
+
? `"${globalResearchBin}" audit-visualizer "${repoPath}"`
|
|
1034
|
+
: tsxBin && existsSync(researchEntry)
|
|
1035
|
+
? `"${tsxBin}" "${researchEntry}" audit-visualizer "${repoPath}"`
|
|
1036
|
+
: `pnpm chomp-research audit-visualizer "${repoPath}"`;
|
|
1037
|
+
try {
|
|
1038
|
+
const output = execSync(cmd, { cwd: repoPath, encoding: "utf8" });
|
|
1039
|
+
return { content: [{ type: "text", text: output }] };
|
|
1040
|
+
}
|
|
1041
|
+
catch (e) {
|
|
1042
|
+
return {
|
|
1043
|
+
isError: true,
|
|
1044
|
+
content: [{ type: "text", text: "Error running visualizer audit:\n" + (e.stdout || e.message) }]
|
|
1045
|
+
};
|
|
1046
|
+
}
|
|
1047
|
+
}));
|
|
1048
|
+
server.tool("chomp_audit_health", "ARCHITECTURAL INTELLIGENCE & AGENT-READINESS AUDIT: Synthesizes system and per-package health metrics (connectivity rate, entity type coverage, parent coverage, scope purity) and surfaces self-diagnostic graph & seam signals: (1) unresolved call hotspots (`? N unresolved` bespoke indirection candidates), (2) opaque node bodies (`astCallCount > 0 && resolvedOutDegree === 0`), (3) dead-end entry points, (4) uncalled exported functions, and (5) cross-package seam & missing-link diagnostics (`ISOLATED_DEPLOYMENT_UNITS`, `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`). Frames findings as Map Visibility opportunities with concrete refactor or Bridge guidance.", {
|
|
1049
|
+
packageName: z.string().optional().describe("Optional filter by package / DEPLOYMENT_UNIT name (e.g., 'core', 'cli', 'mcp', 'web', 'db')"),
|
|
1050
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
1051
|
+
limit: z.number().optional().describe("Maximum diagnostic entries per category (default: 25)"),
|
|
1052
|
+
create_view: z.boolean().optional().describe("When true, updates the UI active view (.chomp/current_view.json) to highlight top diagnostic hotspots. Leave false (default) during coding tasks; pass true only when answering user questions or walkthrough requests."),
|
|
1053
|
+
createView: z.boolean().optional().describe("Alias for create_view (camelCase)")
|
|
1054
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
1055
|
+
const { repoPath, repoName, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
1056
|
+
if (!existsSync(dbPath)) {
|
|
1057
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
|
|
1058
|
+
}
|
|
1059
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
1060
|
+
if (!graph) {
|
|
1061
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
1062
|
+
}
|
|
1063
|
+
const pkgName = args.packageName ?? args.package_name;
|
|
1064
|
+
const report = auditGraphHealth(graph, {
|
|
1065
|
+
packageName: pkgName,
|
|
1066
|
+
limit: args.limit,
|
|
1067
|
+
repoPath,
|
|
1068
|
+
});
|
|
1069
|
+
if ((args.create_view ?? args.createView) && report.recommendedHighlightNodeIds.length > 0) {
|
|
1070
|
+
const viewPath = resolve(repoPath, ".chomp", "current_view.json");
|
|
1071
|
+
mkdirSync(dirname(viewPath), { recursive: true });
|
|
1072
|
+
const altitude = resolveViewTargetAltitude(graph, report.recommendedHighlightNodeIds, pkgName ? "package" : undefined, pkgName);
|
|
1073
|
+
const branchName = resolveRepoGitBranch(repoPath, graph.branchName);
|
|
1074
|
+
const viewUrl = buildActiveViewUrl({
|
|
1075
|
+
baseUrl: resolveActiveUiBaseUrl(repoPath),
|
|
1076
|
+
viewLevel: altitude.viewLevel,
|
|
1077
|
+
packageName: altitude.packageName,
|
|
1078
|
+
});
|
|
1079
|
+
writeFileSync(viewPath, JSON.stringify({
|
|
1080
|
+
repoId,
|
|
1081
|
+
repoName,
|
|
1082
|
+
...(branchName ? { branchName } : {}),
|
|
1083
|
+
createdAt: new Date().toISOString(),
|
|
1084
|
+
viewLevel: altitude.viewLevel,
|
|
1085
|
+
...(altitude.packageName ? { packageName: altitude.packageName } : {}),
|
|
1086
|
+
viewUrl,
|
|
1087
|
+
title: pkgName ? `Health Audit: ${pkgName}` : "System Health & Map Visibility Audit",
|
|
1088
|
+
description: `Connectivity: ${report.healthGate.connectivityRate}% | Hotspots: ${report.healthGate.unresolvedHotspotCount} | Orphans: ${report.healthGate.orphanContractCount}`,
|
|
1089
|
+
source: "custom_query",
|
|
1090
|
+
highlightNodeIds: report.recommendedHighlightNodeIds,
|
|
1091
|
+
}, null, 2), "utf8");
|
|
1092
|
+
}
|
|
1093
|
+
return {
|
|
1094
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
|
|
1095
|
+
};
|
|
1096
|
+
}));
|
|
1097
|
+
server.tool("chomp_find_redundancies", "ARCHITECTURAL REDUNDANCY & PATTERN ALIGNMENT DETECTOR: Scans the structural graph for (1) 1-to-1 pass-through wrapper functions that add indirection without branching or side effects, (2) parallel/duplicate call flows where multiple nodes invoke the exact same downstream target set, (3) duplicate symbol names across files/packages, and (4) outlier routes/endpoints that deviate from their package's dominant canonical wiring pattern.", {
|
|
1098
|
+
packageName: z.string().optional().describe("Optional filter by package / DEPLOYMENT_UNIT name (e.g., 'core', 'cli', 'mcp', 'web', 'db')"),
|
|
1099
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
1100
|
+
limit: z.number().optional().describe("Maximum entries per redundancy category (default: 25)")
|
|
1101
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
1102
|
+
const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
1103
|
+
if (!existsSync(dbPath)) {
|
|
1104
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
|
|
1105
|
+
}
|
|
1106
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
1107
|
+
if (!graph) {
|
|
1108
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
1109
|
+
}
|
|
1110
|
+
const report = findGraphRedundancies(graph, {
|
|
1111
|
+
packageName: args.packageName ?? args.package_name,
|
|
1112
|
+
limit: args.limit,
|
|
1113
|
+
});
|
|
1114
|
+
return {
|
|
1115
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
|
|
1116
|
+
};
|
|
1117
|
+
}));
|
|
1118
|
+
server.tool("chomp_check_boundaries", "BOUNDARY & TOPOLOGICAL LAYER CHECKER: Analyzes cross-package dependency topology, assigns each DEPLOYMENT_UNIT to an architectural tier (ENTRY_APPLICATION, SERVICE_ORCHESTRATOR, INFRASTRUCTURE_ADAPTER, FOUNDATION_CORE, ISOLATED_PACKAGE), detects package-level and node-level circular dependencies and self-loops, flags boundary isolation or upward layer violations, and surfaces cross-package seam & missing-link diagnostics (`ISOLATED_DEPLOYMENT_UNITS`, `UNSTITCHED_PROTOCOL_SEAM`, `INIT_BLOCK_CONNECTOR_LEAK`).", {
|
|
1119
|
+
packageName: z.string().optional().describe("Optional filter by package / DEPLOYMENT_UNIT name (e.g., 'core', 'cli', 'mcp', 'web', 'db')"),
|
|
1120
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)")
|
|
1121
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
1122
|
+
const { repoPath, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
1123
|
+
if (!existsSync(dbPath)) {
|
|
1124
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
|
|
1125
|
+
}
|
|
1126
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
1127
|
+
if (!graph) {
|
|
1128
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
1129
|
+
}
|
|
1130
|
+
const report = checkGraphBoundaries(graph, {
|
|
1131
|
+
packageName: args.packageName ?? args.package_name,
|
|
1132
|
+
repoPath,
|
|
1133
|
+
});
|
|
1134
|
+
return {
|
|
1135
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
|
|
1136
|
+
};
|
|
1137
|
+
}));
|
|
1138
|
+
server.tool("chomp_get_blast_radius", "MANDATORY PRE-EDIT IMPACT ANALYSIS: Call this tool BEFORE modifying or refactoring a function, class, route, or package boundary to compute its upstream dependent callers, downstream dependencies, external OPEN_CONNECTOR side effects, affected entry points, affected packages, and input/output type schemas. Leave `create_view: false` (default) during coding/refactoring tasks; pass `create_view: true` only when answering user questions about impact or blast radius.", {
|
|
1139
|
+
node_id: z.string().optional().describe("Target node ID to compute the blast radius for"),
|
|
1140
|
+
nodeId: z.string().optional().describe("Alias for node_id (camelCase)"),
|
|
1141
|
+
node_ids: z.array(z.string()).optional().describe("Optional list of target node IDs to compute combined blast radius for"),
|
|
1142
|
+
nodeIds: z.array(z.string()).optional().describe("Alias for node_ids (camelCase)"),
|
|
1143
|
+
search_term: z.string().optional().describe("Case-insensitive search term to resolve target node(s) if node_id is not yet known (e.g., 'runStoryTracer', 'SQLiteStorage')"),
|
|
1144
|
+
searchTerm: z.string().optional().describe("Alias for search_term (camelCase)"),
|
|
1145
|
+
packageName: z.string().optional().describe("Optional package filter when resolving target node(s) via search_term"),
|
|
1146
|
+
package_name: z.string().optional().describe("Alias for packageName (snake_case)"),
|
|
1147
|
+
max_depth: z.number().optional().describe("Maximum BFS traversal depth upstream and downstream (default: 4)"),
|
|
1148
|
+
maxDepth: z.number().optional().describe("Alias for max_depth (camelCase)"),
|
|
1149
|
+
create_view: z.boolean().optional().describe("When true, updates .chomp/current_view.json to highlight the target node(s) and their blast radius in the UI. Leave false (default) during coding tasks; pass true only when answering user questions about impact."),
|
|
1150
|
+
createView: z.boolean().optional().describe("Alias for create_view (camelCase)")
|
|
1151
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
1152
|
+
const { repoPath, repoName, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
1153
|
+
if (!existsSync(dbPath)) {
|
|
1154
|
+
throw new Error(`Chomp database not found at ${dbPath}. Please run 'chomp analyze .' first.`);
|
|
1155
|
+
}
|
|
1156
|
+
const graph = await loadActiveGraphWithShims(repoPath, dbPath, repoId);
|
|
1157
|
+
if (!graph) {
|
|
1158
|
+
throw new Error(`Graph data for repository '${repoId}' not found in the database. Please run 'chomp analyze .' first.`);
|
|
1159
|
+
}
|
|
1160
|
+
const portOverlays = await withStorage(dbPath, (s) => s.getEntityOverlays(repoId, { layer: "L1_PORTS" })).catch(() => []);
|
|
1161
|
+
const report = computeBlastRadius(graph, {
|
|
1162
|
+
nodeId: args.node_id ?? args.nodeId,
|
|
1163
|
+
nodeIds: args.node_ids ?? args.nodeIds,
|
|
1164
|
+
searchTerm: args.search_term ?? args.searchTerm,
|
|
1165
|
+
packageName: args.packageName ?? args.package_name,
|
|
1166
|
+
maxDepth: args.max_depth ?? args.maxDepth,
|
|
1167
|
+
}, portOverlays);
|
|
1168
|
+
if ((args.create_view ?? args.createView) && report.found && report.highlightNodeIds.length > 0) {
|
|
1169
|
+
const viewPath = resolve(repoPath, ".chomp", "current_view.json");
|
|
1170
|
+
mkdirSync(dirname(viewPath), { recursive: true });
|
|
1171
|
+
const targetLabel = report.targetNodes.map((t) => t.label).slice(0, 3).join(", ");
|
|
1172
|
+
const altitude = resolveViewTargetAltitude(graph, report.highlightNodeIds, undefined, args.packageName ?? args.package_name);
|
|
1173
|
+
const branchName = resolveRepoGitBranch(repoPath, graph.branchName);
|
|
1174
|
+
const viewUrl = buildActiveViewUrl({
|
|
1175
|
+
baseUrl: resolveActiveUiBaseUrl(repoPath),
|
|
1176
|
+
viewLevel: altitude.viewLevel,
|
|
1177
|
+
packageName: altitude.packageName,
|
|
1178
|
+
});
|
|
1179
|
+
writeFileSync(viewPath, JSON.stringify({
|
|
1180
|
+
repoId,
|
|
1181
|
+
repoName,
|
|
1182
|
+
...(branchName ? { branchName } : {}),
|
|
1183
|
+
createdAt: new Date().toISOString(),
|
|
1184
|
+
viewLevel: altitude.viewLevel,
|
|
1185
|
+
...(altitude.packageName ? { packageName: altitude.packageName } : {}),
|
|
1186
|
+
viewUrl,
|
|
1187
|
+
title: `Blast Radius: ${targetLabel}`,
|
|
1188
|
+
description: `Risk: ${report.summary?.riskLevel} | ${report.summary?.totalUpstreamCallerCount} upstream caller(s) across [${report.summary?.affectedPackages.join(", ")}]`,
|
|
1189
|
+
source: "custom_query",
|
|
1190
|
+
highlightNodeIds: report.highlightNodeIds,
|
|
1191
|
+
}, null, 2), "utf8");
|
|
1192
|
+
}
|
|
1193
|
+
return {
|
|
1194
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }]
|
|
1195
|
+
};
|
|
1196
|
+
}));
|
|
1197
|
+
// Auto-register MCP tools owned by discovered plugins (`packages/mcp/src/plugins/<name>/` & `.chomp/plugins/<name>/`)
|
|
1198
|
+
const registeredToolNames = new Set();
|
|
1199
|
+
for (const plugin of listChompPlugins()) {
|
|
1200
|
+
for (const pluginTool of plugin.mcpTools ?? []) {
|
|
1201
|
+
if (registeredToolNames.has(pluginTool.name))
|
|
1202
|
+
continue;
|
|
1203
|
+
registeredToolNames.add(pluginTool.name);
|
|
1204
|
+
server.tool(pluginTool.name, pluginTool.description, pluginTool.inputSchema, withMcpToolErrorBoundary(async (args) => {
|
|
1205
|
+
const { repoPath, repoName, repoId, dbPath } = resolveActiveMcpRepo(targetPath);
|
|
1206
|
+
const settings = loadPluginSettings(repoPath, plugin);
|
|
1207
|
+
const ctx = {
|
|
1208
|
+
repoPath,
|
|
1209
|
+
repoName,
|
|
1210
|
+
repoId,
|
|
1211
|
+
dbPath,
|
|
1212
|
+
settings,
|
|
1213
|
+
resolveSecret: (key) => resolvePluginSecret(plugin, settings, key),
|
|
1214
|
+
loadRawGraph: () => loadActiveGraphCached(dbPath, repoId),
|
|
1215
|
+
loadProjectedGraph: () => loadActiveGraphWithShims(repoPath, dbPath, repoId),
|
|
1216
|
+
withStorage: (fn) => withStorage(dbPath, fn),
|
|
1217
|
+
invalidateCache: () => invalidateMcpGraphCache(dbPath),
|
|
1218
|
+
runSelf: (opts) => runChompPlugin(plugin, {
|
|
1219
|
+
repoPath,
|
|
1220
|
+
repoId,
|
|
1221
|
+
repoName,
|
|
1222
|
+
dbPath,
|
|
1223
|
+
persist: existsSync(dbPath),
|
|
1224
|
+
...opts,
|
|
1225
|
+
}),
|
|
1226
|
+
setActiveView: (spec) => writePluginActiveView({
|
|
1227
|
+
repoPath,
|
|
1228
|
+
repoId,
|
|
1229
|
+
repoName,
|
|
1230
|
+
pluginName: plugin.name,
|
|
1231
|
+
layer: plugin.layer,
|
|
1232
|
+
}, spec),
|
|
1233
|
+
};
|
|
1234
|
+
const out = await pluginTool.handler(args, ctx);
|
|
1235
|
+
if (out &&
|
|
1236
|
+
typeof out === "object" &&
|
|
1237
|
+
"content" in out &&
|
|
1238
|
+
Array.isArray(out.content)) {
|
|
1239
|
+
return out;
|
|
1240
|
+
}
|
|
1241
|
+
const text = typeof out === "string" ? out : JSON.stringify(out, null, 2);
|
|
1242
|
+
return {
|
|
1243
|
+
content: [{ type: "text", text }],
|
|
1244
|
+
};
|
|
1245
|
+
}));
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
server.tool("chomp_get_conventions", "PAVED-ROAD CONVENTION DISCOVERY & `chomp.config.json` SCHEMA REFERENCE: Pure MCP reference tool for coding agents (works even before `chomp analyze` has run). Returns: (1) Chomp's built-in framework conventions (`nextjs`, `react`, `express`, `mcp`, `drizzle`, `payload`, `core`) so new code aligns to deterministic zero-config patterns, (2) active custom conventions & validation diagnostics from `chomp.config.json#conventions`, (3) remediation playbooks mapping `chomp_audit_health` signals (`UNRESOLVED_CALL`, `ORPHAN_CONTRACT`, `OPAQUE_BODY`, `DARK_FILE`) and `sk1/...` shape keys to either paved-road code alignment, declarative `chomp.config.json#conventions` rules, or `chomp_local_shims` Bridges, and (4) the complete `NodeMatcher` / `EdgeMatcher` / `EmitTemplate` schema and copy-ready config templates.", {
|
|
1249
|
+
framework: z
|
|
1250
|
+
.string()
|
|
1251
|
+
.optional()
|
|
1252
|
+
.describe("Optional filter by framework name (e.g., 'nextjs', 'react', 'express', 'mcp', 'drizzle', 'payload', 'core')"),
|
|
1253
|
+
entity_type: z
|
|
1254
|
+
.string()
|
|
1255
|
+
.optional()
|
|
1256
|
+
.describe("Optional filter by produced entityType or primitive type (e.g., 'HTTP_ENDPOINT', 'REACT_COMPONENT', 'DB_QUERY', 'OPEN_CONNECTOR', 'RELATIONSHIP')"),
|
|
1257
|
+
entityType: z.string().optional().describe("Alias for entity_type (camelCase)"),
|
|
1258
|
+
signal_kind: z
|
|
1259
|
+
.enum(["UNRESOLVED_CALL", "ORPHAN_CONTRACT", "OPAQUE_BODY", "DARK_FILE"])
|
|
1260
|
+
.optional()
|
|
1261
|
+
.describe("Optional filter by self-diagnostic graph signal from chomp_audit_health"),
|
|
1262
|
+
signalKind: z
|
|
1263
|
+
.enum(["UNRESOLVED_CALL", "ORPHAN_CONTRACT", "OPAQUE_BODY", "DARK_FILE"])
|
|
1264
|
+
.optional()
|
|
1265
|
+
.describe("Alias for signal_kind (camelCase)"),
|
|
1266
|
+
shape_key: z
|
|
1267
|
+
.string()
|
|
1268
|
+
.optional()
|
|
1269
|
+
.describe("Optional sk1/... call shapeKey from chomp_audit_health signalClusters to receive targeted matcher vs. local-shim guidance"),
|
|
1270
|
+
shapeKey: z.string().optional().describe("Alias for shape_key (camelCase)"),
|
|
1271
|
+
search_term: z
|
|
1272
|
+
.string()
|
|
1273
|
+
.optional()
|
|
1274
|
+
.describe("Optional case-insensitive search term across rule id, description, entityType, patternId, and specRef"),
|
|
1275
|
+
searchTerm: z.string().optional().describe("Alias for search_term (camelCase)"),
|
|
1276
|
+
include_schema: z
|
|
1277
|
+
.boolean()
|
|
1278
|
+
.optional()
|
|
1279
|
+
.describe("When true (default), includes the full NodeMatcher / EdgeMatcher / EmitTemplate schema reference and config templates; pass false for compact paved-road lookups."),
|
|
1280
|
+
includeSchema: z.boolean().optional().describe("Alias for include_schema (camelCase)"),
|
|
1281
|
+
}, withMcpToolErrorBoundary(async (args) => {
|
|
1282
|
+
const { repoPath } = resolveActiveMcpRepo(targetPath);
|
|
1283
|
+
const report = getConventionsReference({
|
|
1284
|
+
repoPath,
|
|
1285
|
+
framework: args.framework,
|
|
1286
|
+
entityType: args.entity_type ?? args.entityType,
|
|
1287
|
+
signalKind: args.signal_kind ?? args.signalKind,
|
|
1288
|
+
shapeKey: args.shape_key ?? args.shapeKey,
|
|
1289
|
+
searchTerm: args.search_term ?? args.searchTerm,
|
|
1290
|
+
includeSchema: args.include_schema ?? args.includeSchema ?? true,
|
|
1291
|
+
});
|
|
1292
|
+
return {
|
|
1293
|
+
content: [{ type: "text", text: JSON.stringify(report, null, 2) }],
|
|
1294
|
+
};
|
|
1295
|
+
}));
|
|
1296
|
+
const transport = new StdioServerTransport();
|
|
1297
|
+
await server.connect(transport);
|
|
1298
|
+
}
|