|
| 1 | +/** |
| 2 | + * MCP project-resolution regression tests (issue #196). |
| 3 | + * |
| 4 | + * When an MCP client launches the server outside the project directory AND |
| 5 | + * doesn't pass a `rootUri`/`workspaceFolders` in `initialize`, the server used |
| 6 | + * to fall straight back to `process.cwd()` — which for many IDE clients is the |
| 7 | + * wrong directory. Every tool call without an explicit `projectPath` then |
| 8 | + * failed with a misleading "CodeGraph not initialized. Run 'codegraph init'." |
| 9 | + * |
| 10 | + * The fix: when no explicit path is provided, the server asks the client for |
| 11 | + * its workspace root via the spec-blessed `roots/list` request (if the client |
| 12 | + * advertised the `roots` capability), and only falls back to cwd otherwise. |
| 13 | + * When it still can't resolve, the error now says exactly how to fix it. |
| 14 | + * |
| 15 | + * These tests drive the real stdio transport via a spawned subprocess — no |
| 16 | + * mocking — so they also exercise the new bidirectional request/response path. |
| 17 | + */ |
| 18 | +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; |
| 19 | +import { spawn, ChildProcessWithoutNullStreams } from 'child_process'; |
| 20 | +import * as fs from 'fs'; |
| 21 | +import * as path from 'path'; |
| 22 | +import * as os from 'os'; |
| 23 | +import { CodeGraph } from '../src'; |
| 24 | + |
| 25 | +const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js'); |
| 26 | + |
| 27 | +function spawnServer(cwd: string): ChildProcessWithoutNullStreams { |
| 28 | + // --no-watch keeps the test deterministic and avoids watcher startup noise. |
| 29 | + return spawn(process.execPath, [BIN, 'serve', '--mcp', '--no-watch'], { |
| 30 | + cwd, |
| 31 | + stdio: ['pipe', 'pipe', 'pipe'], |
| 32 | + }) as ChildProcessWithoutNullStreams; |
| 33 | +} |
| 34 | + |
| 35 | +/** Parse every JSON-RPC message the server writes to stdout into an array. */ |
| 36 | +function collectMessages(child: ChildProcessWithoutNullStreams): Array<Record<string, any>> { |
| 37 | + const messages: Array<Record<string, any>> = []; |
| 38 | + let buf = ''; |
| 39 | + child.stdout.on('data', (chunk) => { |
| 40 | + buf += chunk.toString('utf8'); |
| 41 | + let idx; |
| 42 | + while ((idx = buf.indexOf('\n')) !== -1) { |
| 43 | + const line = buf.slice(0, idx).trim(); |
| 44 | + buf = buf.slice(idx + 1); |
| 45 | + if (!line) continue; |
| 46 | + try { messages.push(JSON.parse(line)); } catch { /* ignore non-JSON */ } |
| 47 | + } |
| 48 | + }); |
| 49 | + return messages; |
| 50 | +} |
| 51 | + |
| 52 | +function waitForMessage( |
| 53 | + messages: ReadonlyArray<Record<string, any>>, |
| 54 | + predicate: (m: Record<string, any>) => boolean, |
| 55 | + timeoutMs: number, |
| 56 | +): Promise<Record<string, any>> { |
| 57 | + return new Promise((resolve, reject) => { |
| 58 | + const started = Date.now(); |
| 59 | + const tick = () => { |
| 60 | + const hit = messages.find(predicate); |
| 61 | + if (hit) return resolve(hit); |
| 62 | + if (Date.now() - started > timeoutMs) { |
| 63 | + return reject(new Error(`Timed out. Messages so far: ${JSON.stringify(messages)}`)); |
| 64 | + } |
| 65 | + setTimeout(tick, 20); |
| 66 | + }; |
| 67 | + tick(); |
| 68 | + }); |
| 69 | +} |
| 70 | + |
| 71 | +function send(child: ChildProcessWithoutNullStreams, msg: object): void { |
| 72 | + child.stdin.write(JSON.stringify(msg) + '\n'); |
| 73 | +} |
| 74 | + |
| 75 | +const CLIENT_INFO = { name: 'test', version: '0.0.0' }; |
| 76 | + |
| 77 | +describe('MCP project resolution via roots/list (issue #196)', () => { |
| 78 | + let cwdDir: string; // where the server is launched — has NO .codegraph |
| 79 | + let projectDir: string; // the real indexed project the client reports |
| 80 | + let child: ChildProcessWithoutNullStreams | null = null; |
| 81 | + |
| 82 | + beforeEach(() => { |
| 83 | + cwdDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-cwd-')); |
| 84 | + projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-proj-')); |
| 85 | + }); |
| 86 | + |
| 87 | + afterEach(() => { |
| 88 | + if (child && !child.killed) { |
| 89 | + child.kill('SIGKILL'); |
| 90 | + child = null; |
| 91 | + } |
| 92 | + fs.rmSync(cwdDir, { recursive: true, force: true }); |
| 93 | + fs.rmSync(projectDir, { recursive: true, force: true }); |
| 94 | + }); |
| 95 | + |
| 96 | + it('resolves the project from the client roots/list when no rootUri is sent', async () => { |
| 97 | + const cg = await CodeGraph.init(projectDir); |
| 98 | + cg.close(); |
| 99 | + |
| 100 | + child = spawnServer(cwdDir); |
| 101 | + const messages = collectMessages(child); |
| 102 | + |
| 103 | + // Advertise the roots capability but pass NO rootUri/workspaceFolders. |
| 104 | + send(child, { |
| 105 | + jsonrpc: '2.0', id: 0, method: 'initialize', |
| 106 | + params: { protocolVersion: '2025-11-25', capabilities: { roots: {} }, clientInfo: CLIENT_INFO }, |
| 107 | + }); |
| 108 | + await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000); |
| 109 | + send(child, { jsonrpc: '2.0', method: 'notifications/initialized' }); |
| 110 | + |
| 111 | + // First tool call (no projectPath) drives the server to ask us for roots. |
| 112 | + send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } }); |
| 113 | + |
| 114 | + const rootsReq = await waitForMessage(messages, (m) => m.method === 'roots/list', 5000); |
| 115 | + expect(typeof rootsReq.id).toBe('string'); // server-initiated id |
| 116 | + send(child, { |
| 117 | + jsonrpc: '2.0', id: rootsReq.id, |
| 118 | + result: { roots: [{ uri: `file://${projectDir}`, name: 'proj' }] }, |
| 119 | + }); |
| 120 | + |
| 121 | + // The status call now succeeds against the resolved project. |
| 122 | + const resp = await waitForMessage(messages, (m) => m.id === 1, 8000); |
| 123 | + const text = resp.result.content[0].text as string; |
| 124 | + expect(text).toContain('CodeGraph Status'); |
| 125 | + expect(text).not.toContain('No CodeGraph project is loaded'); |
| 126 | + }, 20000); |
| 127 | + |
| 128 | + it('returns an actionable error when there is no rootUri and no roots capability', async () => { |
| 129 | + child = spawnServer(cwdDir); |
| 130 | + const messages = collectMessages(child); |
| 131 | + |
| 132 | + send(child, { |
| 133 | + jsonrpc: '2.0', id: 0, method: 'initialize', |
| 134 | + params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: CLIENT_INFO }, |
| 135 | + }); |
| 136 | + await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000); |
| 137 | + send(child, { jsonrpc: '2.0', method: 'notifications/initialized' }); |
| 138 | + |
| 139 | + send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } }); |
| 140 | + const resp = await waitForMessage(messages, (m) => m.id === 1, 8000); |
| 141 | + const text = resp.result.content[0].text as string; |
| 142 | + |
| 143 | + expect(text).toContain('No CodeGraph project is loaded'); |
| 144 | + expect(text).toContain('projectPath'); |
| 145 | + expect(text).toContain('--path'); |
| 146 | + // Names the directory it actually searched (the wrong cwd) so the user can |
| 147 | + // see why detection missed. basename survives any symlink realpath-ing. |
| 148 | + expect(text).toContain(path.basename(cwdDir)); |
| 149 | + // It must not have hung waiting on roots/list — the client never offered it. |
| 150 | + expect(messages.some((m) => m.method === 'roots/list')).toBe(false); |
| 151 | + }, 20000); |
| 152 | + |
| 153 | + it('honors an explicit rootUri without asking the client for roots', async () => { |
| 154 | + const cg = await CodeGraph.init(projectDir); |
| 155 | + cg.close(); |
| 156 | + |
| 157 | + child = spawnServer(cwdDir); |
| 158 | + const messages = collectMessages(child); |
| 159 | + |
| 160 | + send(child, { |
| 161 | + jsonrpc: '2.0', id: 0, method: 'initialize', |
| 162 | + params: { |
| 163 | + protocolVersion: '2025-11-25', |
| 164 | + capabilities: { roots: {} }, |
| 165 | + clientInfo: CLIENT_INFO, |
| 166 | + rootUri: `file://${projectDir}`, |
| 167 | + }, |
| 168 | + }); |
| 169 | + await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000); |
| 170 | + send(child, { jsonrpc: '2.0', method: 'notifications/initialized' }); |
| 171 | + |
| 172 | + send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } }); |
| 173 | + const resp = await waitForMessage(messages, (m) => m.id === 1, 8000); |
| 174 | + const text = resp.result.content[0].text as string; |
| 175 | + |
| 176 | + expect(text).toContain('CodeGraph Status'); |
| 177 | + // rootUri is a stronger signal than roots — we never needed to ask. |
| 178 | + expect(messages.some((m) => m.method === 'roots/list')).toBe(false); |
| 179 | + }, 20000); |
| 180 | +}); |
0 commit comments