feat(mcp): pare default tool surface to codegraph_explore alone + redux-thunk synthesizer

This commit is contained in:
Colby McHenry
2026-06-19 02:15:14 -05:00
parent 7ddd3fa7eb
commit f82a662ddb
14 changed files with 396 additions and 137 deletions
+4 -4
View File
@@ -17,8 +17,8 @@
* runs without this block, and consistently with it — including runs
* with zero Read/grep fallback.
* - **Non-MCP harnesses** — agents with no MCP client at all can still
* run the `codegraph explore` / `codegraph node` CLI, which prints the
* same output as the MCP tools.
* run the `codegraph explore` CLI, which prints the same output as the
* MCP tool.
*
* Keep this block SHORT. The main agent reads it every turn on top of the
* server instructions — the #529 duplication-cost argument still bounds
@@ -44,8 +44,8 @@ export const CODEGRAPH_INSTRUCTIONS_BLOCK = `${CODEGRAPH_SECTION_START}
In repositories indexed by CodeGraph (a \`.codegraph/\` directory exists at the repo root), reach for it BEFORE grep/find or reading files when you need to understand or locate code:
- **MCP tools** (when available): \`codegraph_explore\` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them. \`codegraph_node\` returns one symbol's source + callers, or reads a whole file with line numbers. If the tools are listed but deferred, load them by name via tool search.
- **Shell** (always works): \`codegraph explore "<symbol names or question>"\` and \`codegraph node <symbol-or-file>\` print the same output.
- **MCP tool** (when available): \`codegraph_explore\` answers most code questions in one call — the relevant symbols' verbatim source plus the call paths between them, including dynamic-dispatch hops grep can't follow. Name a file or symbol in the query to read its current line-numbered source. If it's listed but deferred, load it by name via tool search.
- **Shell** (always works): \`codegraph explore "<symbol names or question>"\` prints the same output.
If there is no \`.codegraph/\` directory, skip CodeGraph entirely — indexing is the user's decision.
${CODEGRAPH_SECTION_END}`;
+13 -12
View File
@@ -31,20 +31,21 @@ export function getMcpServerConfig(): { type: string; command: string; args: str
/**
* Permissions list for Claude `settings.json`. Other targets that
* have a permissions concept can compose this list directly. The
* permission strings follow Claude's `mcp__<server>__<tool>` format.
* have a permissions concept can compose this list directly.
*
* One server-scoped wildcard rather than a per-tool list. By default only
* `codegraph_explore` is even LISTED to the agent (see DEFAULT_MCP_TOOLS in
* mcp/tools.ts), so in practice explore is the only tool this auto-approves —
* but the wildcard means that if a user re-enables another tool via
* CODEGRAPH_MCP_TOOLS, it's already pre-approved (no permission prompt, no
* hand-editing settings.json), and future tools are covered too. Claude only
* honors globs after a literal `mcp__<server>__` prefix, so this exact string
* is the way to allow-all for one server; a bare `mcp__codegraph` or `*` is
* ignored. The allowlist gates PROMPTING, not visibility, so a superset here
* never makes a hidden tool appear.
*/
export function getCodeGraphPermissions(): string[] {
return [
'mcp__codegraph__codegraph_explore',
'mcp__codegraph__codegraph_search',
'mcp__codegraph__codegraph_node',
'mcp__codegraph__codegraph_callers',
'mcp__codegraph__codegraph_callees',
'mcp__codegraph__codegraph_impact',
'mcp__codegraph__codegraph_files',
'mcp__codegraph__codegraph_status',
];
return ['mcp__codegraph__*'];
}
/**
+29 -36
View File
@@ -7,13 +7,15 @@
* before it sees individual tool descriptions.
*
* Goals when editing this:
* - Tool selection by intent (which tool for which question)
* - Common chains (refactor planning = X then Y)
* - Anti-patterns (don't grep when codegraph_search is faster)
* - Lead the agent to codegraph_explore for any structural/flow question
* - Reinforce "explore instead of Read/Grep" for indexed code
* - Anti-patterns (don't re-verify with grep; don't hand-reconstruct flows)
*
* Keep it tight. The agent reads this every session — long instructions
* burn tokens. Reference only tools that exist on `main`; gate any
* conditional tools behind feature checks if/when they ship.
* burn tokens. The DEFAULT MCP surface is `codegraph_explore` ALONE (see
* DEFAULT_MCP_TOOLS in tools.ts) — reference only that tool here. The other
* tools (node/search/callers/…) stay defined and are re-enablable via
* CODEGRAPH_MCP_TOOLS, but they are NOT listed to agents, so don't name them.
*/
export const SERVER_INSTRUCTIONS = `# Codegraph — code intelligence over an indexed knowledge graph
@@ -27,45 +29,36 @@ verbatim source PLUS who calls it and what it affects, so you edit with the
blast radius in view. More accurate context, in far fewer tokens and
round-trips than reading files yourself.
## Use codegraph instead of reading files — for questions AND edits
## One tool: codegraph_explore — use it instead of reading files
Whether you're answering "how does X work" or implementing a change (fixing
a bug, adding a feature), reach for codegraph before you Read. For
understanding, answer DIRECTLY — usually with ONE \`codegraph_explore\` call.
\`codegraph_explore\` takes either a natural-language question or a bag of
symbol/file names and returns the verbatim source of the relevant symbols
grouped by file, so it is Read-equivalent and most often the ONLY
codegraph call you need. Codegraph IS the pre-built search index — so
delegating the lookup to a separate file-reading sub-task/agent, or
running your own grep + read loop, repeats work codegraph already did and
costs more for the same answer. Reach for raw Read/Grep only to confirm a
specific detail codegraph didn't cover. A direct codegraph answer is
typically one to a few calls; a grep/read exploration is dozens.
There is a single tool, \`codegraph_explore\`, and it is Read-equivalent. It
takes either a natural-language question or a bag of symbol/file names and
returns the **verbatim, line-numbered source** of the relevant symbols
grouped by file — the same \`<n>\\t<line>\` shape \`Read\` gives you, safe to
\`Edit\` from — PLUS the call path among them (including dynamic-dispatch hops
like callbacks, React re-render, and JSX children that grep can't follow) and
a blast-radius summary of what depends on them.
## Tool selection by intent
Whether you're answering "how does X work" or implementing a change (fixing a
bug, adding a feature), call \`codegraph_explore\` before you Read. ONE call
usually answers the whole question. Codegraph IS the pre-built search index —
so running your own grep + read loop, or delegating the lookup to a separate
file-reading sub-task/agent, repeats work codegraph already did and costs more
for the same answer. A direct codegraph answer is typically one to a few
calls; a grep/read exploration is dozens.
- **Almost any question — "how does X work", architecture, a bug, "what/where is X", or surveying an area** → \`codegraph_explore\` (PRIMARY — call FIRST; ONE capped call returns the verbatim source of the relevant symbols grouped by file; most often the ONLY call you need)
- **"How does X reach/become Y? / the flow / the path from X to Y"** → \`codegraph_explore\`, naming the symbols that span the flow (e.g. \`mutateElement renderScene\`) — it surfaces the call path among them, including dynamic-dispatch hops (callbacks, React re-render, JSX children) grep can't follow
- **"What is the symbol named X?" (just its location)** → \`codegraph_search\`
- **"What calls this?" / "What would changing this break?"** → \`codegraph_callers\` — EVERY call site with file:line, including where a function is **registered as a callback** (passed as an argument, assigned to a function pointer/field, listed in a handler table) — labeled "via callback registration" — so a function with no direct calls is NOT dead if it's wired up somewhere. When several UNRELATED symbols share a name (one \`UserService\` per monorepo app), it reports **one section per definition** (never a merged list) — pass \`file\` to focus the definition you mean. The wider blast radius arrives automatically on \`codegraph_explore\` (its "Blast radius" section) and \`codegraph_node\` (the dependents note)
- **"What does this call?"** → \`codegraph_node\` with that symbol and \`includeCode: true\` — the body IS the callee list, and the caller/callee trail comes with it
- **Reading a source FILE (any time you'd use the \`Read\` tool)** → \`codegraph_node\` with a \`file\` path and no \`symbol\`. It returns the file's **current source with line numbers — the same \`<n>\\t<line>\` shape \`Read\` gives you, safe to \`Edit\` from** — narrowable with \`offset\`/\`limit\` exactly like \`Read\`, PLUS a one-line note of which files depend on it. Same bytes as \`Read\`, faster (served from the index), with the blast radius attached. Use it **instead of \`Read\`** for indexed source files; fall back to \`Read\` only for what codegraph doesn't index (configs, docs). Pass \`symbolsOnly: true\` for just the file's structure.
- **About to read or edit a symbol you can name** → \`codegraph_node\` with that \`symbol\` (SECONDARY — the after-explore depth tool): the verbatim source (\`includeCode: true\`) PLUS its caller/callee trail, so before changing it you see what calls it and what your edit would break. For an OVERLOADED name it returns EVERY matching definition's body in one call, so you never Read a file to find the right overload
## How to query
## Common chains
- **Flow / "how does X reach Y"**: ONE \`codegraph_explore\` with the symbol names spanning the flow — it surfaces the call path among them (riding dynamic-dispatch hops) AND returns their source. No need to reconstruct the path with \`codegraph_search\` + \`codegraph_callers\`.
- **Onboarding / understanding any area**: ONE \`codegraph_explore\` is usually the whole answer. Only follow up — \`codegraph_node\` for a specific symbol — if something is still unclear.
- **Refactor planning**: \`codegraph_callers\` for the complete call-site list to update; the wider blast radius is already attached to \`codegraph_explore\` / \`codegraph_node\` output.
- **Debugging a regression**: \`codegraph_callers\` of the suspected symbol; \`codegraph_node\` on anything unexpected that appears.
- **Almost any question — "how does X work", architecture, a bug, "what/where is X", or surveying an area** → \`codegraph_explore\` with a natural-language question or the relevant names. ONE capped call returns the verbatim source grouped by file; most often the ONLY call you need.
- **"How does X reach/become Y? / the flow / the path from X to Y"** → \`codegraph_explore\`, naming the symbols that span the flow (e.g. \`mutateElement renderScene\`) — it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.
- **Reading or editing a file/symbol you can name** → put its name or file path in the \`codegraph_explore\` query — it returns that current line-numbered source (safe to \`Edit\` from) with the call path and blast radius attached, so you don't Read it separately. For an overloaded name it returns every matching definition's body in one call.
- **Need more?** Call \`codegraph_explore\` again with more specific names — treat the source it returns as already Read.
## Anti-patterns
- **Trust codegraph's results — don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.
- **Don't grep first** when looking up a symbol by name — \`codegraph_search\` is faster and returns kind + location + signature.
- **Don't chain \`codegraph_search\` + \`codegraph_node\`** to understand an area — ONE \`codegraph_explore\` returns the relevant symbols' source together in a single round-trip.
- **Don't loop \`codegraph_node\` over many symbols** — one \`codegraph_explore\` call returns them all grouped by file, while each separate call re-reads the whole context and costs far more. Use \`codegraph_node\` for a single symbol.
- **Don't reach for the \`Read\` tool on an indexed source file** — \`codegraph_node\` with a \`file\` reads it for you (same \`<n>\\t<line>\` source, \`offset\`/\`limit\` like Read, faster, with its blast radius), and with a \`symbol\` it returns the source plus the caller/callee trail. Reach for raw \`Read\` only for what codegraph doesn't index (configs, docs) or when the staleness banner flags a file as pending re-index.
- **Don't grep or Read first** to find or understand indexed code — ONE \`codegraph_explore\` returns the relevant symbols' source together in a single round-trip. Reach for raw \`Read\`/\`Grep\` only to confirm a specific detail codegraph didn't cover, or for what codegraph doesn't index (configs, docs).
- **Don't reconstruct a flow by hand** — name the endpoints in one \`codegraph_explore\` and it surfaces the path between them, dynamic-dispatch hops included.
- **After editing, check the staleness banner.** When a tool response starts with "⚠️ Some files referenced below were edited since the last index sync…", the listed files are pending re-index — Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust codegraph. A different, rarer banner — "⚠️ CodeGraph auto-sync is DISABLED…" — means live watching stopped entirely (the whole index is frozen, not just a few files); until it's resolved, Read files directly to confirm anything that may have changed.
## Limitations
+10 -20
View File
@@ -633,28 +633,18 @@ export function getStaticTools(): ToolDefinition[] {
}
/**
* The MCP tools served by DEFAULT (short names). The other defined tools
* (callees, impact, files, status) remain fully functional — handlers stay,
* the library API and CLI are untouched, and `CODEGRAPH_MCP_TOOLS` re-enables
* any of them — they just aren't LISTED to agents anymore.
* The MCP tools served by DEFAULT (short names). Pared to ONLY `codegraph_explore`
* — the single tool that reliably earns its place: one capped call returns the
* verbatim source of the relevant symbols grouped by file (and, with the offload,
* a reasoned flow map over that source). Every other tool is a narrower slice of
* what explore already does, and presence itself steers mis-picks, so they are no
* longer LISTED to agents.
*
* Evidence for the cut (the "adapt the tool to the agent" principle —
* fewer tools = fewer mis-picks, and presence itself steers):
* - `codegraph_impact` appears in ZERO recorded eval runs ever — its
* blast-radius info already arrives inline on explore (the "Blast radius"
* section) and node (the dependents note), so agents never need the
* standalone tool.
* - `codegraph_callees` is redundant by construction: a symbol's body (which
* node returns) IS its callee list, plus the caller/callee trail.
* - `codegraph_files` / `codegraph_status`: the tiny-repo audit (see
* getTools) found they "reduce to one grep"; staleness banners already
* inline the pending-sync info on every read tool, and the CLI covers
* diagnostics.
* - `codegraph_callers` stays: exhaustive call-site enumeration (every
* caller with file:line, callback registrations labeled, one section per
* same-named definition) is the one job explore/node don't replicate.
* The other defined tools (`node`, `search`, `callers`, plus callees/impact/files/
* status) remain fully functional — handlers stay, the library API and CLI are
* untouched, and `CODEGRAPH_MCP_TOOLS=explore,node,...` re-enables any of them.
*/
const DEFAULT_MCP_TOOLS = new Set(['explore', 'node', 'search', 'callers']);
const DEFAULT_MCP_TOOLS = new Set(['explore']);
/**
* Tool handler that executes tools against a CodeGraph instance
+61 -1
View File
@@ -1646,10 +1646,68 @@ function svelteKitLoadEdges(ctx: ResolutionContext): Edge[] {
return edges;
}
/**
* Redux-thunk dispatch chain. `export const X = createAsyncThunk(prefix, async (a, api) => {...})`
* (or a wrapper like trezor's `createThunk(...)`) passes the async body as an ARGUMENT, so
* tree-sitter never extracts it as a function node: `X` is a `constant` whose body's calls are
* ORPHANED. The `dispatch(nextThunk(...))` calls that drive a thunk chain forward therefore produce
* no edges, so `callees(X)` is empty and a flow `dispatch(X(...)) → X → nextThunk` dead-ends at the
* constant (validated on trezor-suite: the signXxxThunk constants had ZERO outgoing edges). Bridge
* it: body-scan each thunk constant for `dispatch(Y(...))` and link `X → Y`, so the dispatch chain
* connects. High-precision — the `dispatch(` keyword plus `Y` must resolve to a function/constant/
* method node; capped; gated on thunk constants existing so it never runs on non-RTK repos.
* Cross-file by design (a suite thunk dispatches a wallet-core thunk). Provenance `heuristic`,
* `synthesizedBy:'redux-thunk'`; `registeredAt` is the dispatch site.
*/
const THUNK_DECL_RE = /create(?:Async)?Thunk/;
const THUNK_DISPATCH_RE = /\bdispatch\s*\(\s*([A-Za-z_]\w*)\s*[(),]/g;
const THUNK_FANOUT_CAP = 24;
function reduxThunkEdges(queries: QueryBuilder, ctx: ResolutionContext): Edge[] {
const edges: Edge[] = [];
const seen = new Set<string>();
for (const node of queries.iterateNodesByKind('constant')) {
// Cheap gate: the initializer (captured in `signature`) must be a create(Async)Thunk call —
// avoids reading every constant's body on a large repo.
if (!node.signature || !THUNK_DECL_RE.test(node.signature)) continue;
const content = ctx.readFile(node.filePath);
const src = content && sliceLines(content, node.startLine, node.endLine);
if (!src) continue;
// Thunks are TS/JS-family (same // and /* */ comment syntax); map to a CommentLang.
const safe = stripCommentsForRegex(src, node.language === 'javascript' || node.language === 'jsx' ? 'javascript' : 'typescript');
THUNK_DISPATCH_RE.lastIndex = 0;
let m: RegExpExecArray | null;
let added = 0;
while ((m = THUNK_DISPATCH_RE.exec(safe)) && added < THUNK_FANOUT_CAP) {
const name = m[1]!;
if (name === node.name) continue; // self-dispatch (recursive thunk) — skip
const target = ctx
.getNodesByName(name)
.find((n) => n.kind === 'constant' || n.kind === 'function' || n.kind === 'method');
if (!target || target.id === node.id) continue;
const key = `${node.id}>${target.id}`;
if (seen.has(key)) continue;
seen.add(key);
const line = node.startLine + safe.slice(0, m.index).split('\n').length - 1;
edges.push({
source: node.id,
target: target.id,
kind: 'calls',
line,
provenance: 'heuristic',
metadata: { synthesizedBy: 'redux-thunk', via: name, registeredAt: `${node.filePath}:${line}` },
});
added++;
}
}
return edges;
}
/**
* Synthesize dispatcher→callback edges (field observers + EventEmitters +
* React re-render + JSX children + Vue templates + SvelteKit load + RN event
* channel + Fabric native-impl + MyBatis Java↔XML + Gin middleware chain).
* channel + Fabric native-impl + MyBatis Java↔XML + Gin middleware chain +
* Redux-thunk dispatch chain).
* Returns the count added. Never throws into indexing — callers wrap in try/catch.
*/
export function synthesizeCallbackEdges(queries: QueryBuilder, ctx: ResolutionContext): number {
@@ -1687,6 +1745,7 @@ export function synthesizeCallbackEdges(queries: QueryBuilder, ctx: ResolutionCo
const rnXPlatEdges = rnCrossPlatformEdges(queries);
const mybatisEdges = mybatisJavaXmlEdges(queries);
const ginEdges = ginMiddlewareChainEdges(queries, ctx);
const thunkEdges = reduxThunkEdges(queries, ctx);
const merged: Edge[] = [];
const seen = new Set<string>();
@@ -1710,6 +1769,7 @@ export function synthesizeCallbackEdges(queries: QueryBuilder, ctx: ResolutionCo
...rnXPlatEdges,
...mybatisEdges,
...ginEdges,
...thunkEdges,
]) {
const key = `${e.source}>${e.target}`;
if (seen.has(key)) continue;