feat(mcp): codegraph_explore as the sole primary tool + store coverage + overload disambiguation (#647)
## Summary
Completes the explore-overhaul arc: `codegraph_explore` becomes the single primary tool an agent reaches for, and its coverage + output shape are tuned so flow/architecture questions resolve with near-zero Read/Grep.
### What changed
- **explore is the sole primary tool** — removed `codegraph_context` (the fuzzy-input Read-trigger) and `codegraph_trace` (under-picked by agents); explore already surfaces the call flow among the symbols you name. A plain natural-language question now works as the query.
- **Store/handler coverage** — functions defined inside object literals (Zustand `create((set, get) => ({ … }))`, Redux/Pinia/MobX, exported handler/route maps) are indexed as real symbols, including calls through `useStore.getState().fn()` and destructured `const { fn } = useStore.getState()`. A general AST rule, not a per-lib hack.
- **Overload disambiguation** — explore leads with the *right* definition when a method name is overloaded across types (a PascalCase type token in the query biases to that type's own def); `codegraph_node` returns *every* overload's body in one call, with an optional `file`/`line` selector to pin one.
- **Method-atomic render** — explore never returns half a method; at the size budget it drops whole methods/files (and lists what it dropped) instead of truncating a body mid-method.
- **Native-read-shaped output** — per-call output is capped to ~24K with a 25K hard ceiling and concentrated into ~150–250-line flow windows, mirroring how the agent natively reads; repo size scales the *call* budget, not the per-call size (a larger response just gets externalized to a file the host Reads back).
- **Blast radius** folded into explore (dependents + covering tests, locations only).
### Benchmark (refreshed on this build)
Re-validated the 7-repo A/B on 2026-06-02 (Opus 4.8, effort=high, median of 4). WITH arm re-measured on this build, WITHOUT reused:
**~16% cheaper · 47% fewer tokens · 22% faster · 58% fewer tool calls** — 0 file reads on 6 of 7 repos (Gin ~1).
The arc trades larger, cache-heavy explore responses for guaranteed near-zero reads, so cost/token margins soften vs the prior build (Excalidraw and Tokio land at cost break-even) while time and tool-calls stay clear wins everywhere — consistent with the project's stated optimization target (latency + tool-calls, not token cost).
### Validation
- Full suite green: **1112 passed, 2 skipped**.
- 28/28 plain WITH runs across the 7 README repos completed clean; reads median 0 on 6/7.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
This commit is contained in:
+19
-98
@@ -263,23 +263,35 @@ describe('MCP Input Validation', () => {
|
||||
expect(result.content[0].text).toContain('non-empty string');
|
||||
});
|
||||
|
||||
it('should reject non-string task in codegraph_context', async () => {
|
||||
const result = await handler.execute('codegraph_context', { task: undefined });
|
||||
it('should reject non-string query in codegraph_explore', async () => {
|
||||
const result = await handler.execute('codegraph_explore', { query: undefined });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content[0].text).toContain('non-empty string');
|
||||
});
|
||||
|
||||
it('should truncate oversized codegraph_context output', async () => {
|
||||
const oversizedContext = Array.from({ length: 400 }, (_, i) => `line-${i} ${'x'.repeat(80)}`).join('\n');
|
||||
it('should truncate oversized tool output', async () => {
|
||||
// Force a huge result set through codegraph_search; the response must be
|
||||
// truncated with the sentinel rather than flooding the agent's context.
|
||||
const many = Array.from({ length: 3000 }, (_, i) => ({
|
||||
node: {
|
||||
id: `n${i}`,
|
||||
name: `symbol_${i}_${'x'.repeat(40)}`,
|
||||
kind: 'function',
|
||||
filePath: `src/very/deep/path/file_${i}.ts`,
|
||||
startLine: 1,
|
||||
endLine: 2,
|
||||
language: 'typescript',
|
||||
},
|
||||
score: 1,
|
||||
}));
|
||||
const fakeCg = {
|
||||
buildContext: async () => oversizedContext,
|
||||
searchNodes: () => many,
|
||||
};
|
||||
const fakeHandler = new ToolHandler(fakeCg as unknown as CodeGraph);
|
||||
|
||||
const result = await fakeHandler.execute('codegraph_context', { task: 'find example' });
|
||||
const result = await fakeHandler.execute('codegraph_search', { query: 'x' });
|
||||
|
||||
expect(result.isError).toBeFalsy();
|
||||
expect(result.content[0].text.length).toBeLessThan(oversizedContext.length);
|
||||
expect(result.content[0].text).toContain('... (output truncated)');
|
||||
});
|
||||
|
||||
@@ -551,94 +563,3 @@ describe('Symlink Cycle Detection', () => {
|
||||
expect(files).toContain('src/valid.ts');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Session marker symlink resistance', () => {
|
||||
// The marker write lives in src/mcp/tools.ts behind handleContext. We exercise
|
||||
// it end-to-end via ToolHandler.execute so the test exercises the same code
|
||||
// path Claude Code drives. The session id is per-test so other parallel test
|
||||
// runs can't collide with the marker file we plant a symlink at.
|
||||
const SESSION_ID = `cg-test-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
||||
const crypto = require('crypto') as typeof import('crypto');
|
||||
const hash = crypto.createHash('md5').update(SESSION_ID).digest('hex').slice(0, 16);
|
||||
const markerPath = path.join(os.tmpdir(), `codegraph-consulted-${hash}`);
|
||||
|
||||
let projectDir: string;
|
||||
let victimDir: string;
|
||||
let victimFile: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
projectDir = createTempDir();
|
||||
victimDir = createTempDir();
|
||||
victimFile = path.join(victimDir, 'private.txt');
|
||||
fs.writeFileSync(victimFile, 'SECRET-DO-NOT-OVERWRITE\n');
|
||||
if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
|
||||
|
||||
// A real .codegraph/ has to exist for handleContext to get past the
|
||||
// "not initialized" guard — index a tiny fixture so the call reaches the
|
||||
// marker write step rather than short-circuiting on missing project state.
|
||||
fs.writeFileSync(path.join(projectDir, 'a.ts'), 'export const x = 1;\n');
|
||||
const cg = await CodeGraph.init(projectDir);
|
||||
await cg.indexAll();
|
||||
cg.close();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
|
||||
cleanupTempDir(projectDir);
|
||||
cleanupTempDir(victimDir);
|
||||
});
|
||||
|
||||
it('does not follow a pre-planted symlink at the marker path', async () => {
|
||||
// Skip on platforms where the user can't create symlinks (Windows without
|
||||
// dev mode + admin). The CWE-59 risk we're guarding against doesn't apply
|
||||
// when symlinks aren't creatable, so the skip is correct, not a gap.
|
||||
try {
|
||||
fs.symlinkSync(victimFile, markerPath);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const cg = await CodeGraph.open(projectDir);
|
||||
const handler = new ToolHandler(cg);
|
||||
process.env.CLAUDE_SESSION_ID = SESSION_ID;
|
||||
try {
|
||||
await handler.execute('codegraph_context', { task: 'find x' });
|
||||
} finally {
|
||||
delete process.env.CLAUDE_SESSION_ID;
|
||||
cg.close();
|
||||
}
|
||||
|
||||
// The victim file's contents must be untouched — the old writeFileSync
|
||||
// path would have followed the symlink and written an ISO timestamp here.
|
||||
expect(fs.readFileSync(victimFile, 'utf8')).toBe('SECRET-DO-NOT-OVERWRITE\n');
|
||||
|
||||
// And the marker path itself must still be the symlink we planted —
|
||||
// no fallback path that quietly unlinked + recreated it (which would
|
||||
// also work, but is a behavior we don't want to silently rely on).
|
||||
expect(fs.lstatSync(markerPath).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
it('writes the marker file with 0o600 perms on a clean path', async () => {
|
||||
// No symlink planted — happy path. Verifies the new openSync(mode: 0o600)
|
||||
// call is what actually lands on disk (regression guard for the perm
|
||||
// tightening that came with the O_NOFOLLOW fix).
|
||||
const cg = await CodeGraph.open(projectDir);
|
||||
const handler = new ToolHandler(cg);
|
||||
process.env.CLAUDE_SESSION_ID = SESSION_ID;
|
||||
try {
|
||||
await handler.execute('codegraph_context', { task: 'find x' });
|
||||
} finally {
|
||||
delete process.env.CLAUDE_SESSION_ID;
|
||||
cg.close();
|
||||
}
|
||||
|
||||
expect(fs.existsSync(markerPath)).toBe(true);
|
||||
// chmod's low 9 bits — strip the file-type bits for a clean compare.
|
||||
// Windows can't enforce 0o600 in the POSIX sense; skip the assertion
|
||||
// there since the underlying OS will normalize the mode anyway.
|
||||
if (process.platform !== 'win32') {
|
||||
const mode = fs.statSync(markerPath).mode & 0o777;
|
||||
expect(mode).toBe(0o600);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user