mcp-roots.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  25. function spawnServer(cwd: string): ChildProcessWithoutNullStreams {
  26. // --no-watch keeps the test deterministic and avoids watcher startup noise.
  27. return spawn(process.execPath, [BIN, 'serve', '--mcp', '--no-watch'], {
  28. cwd,
  29. stdio: ['pipe', 'pipe', 'pipe'],
  30. }) as ChildProcessWithoutNullStreams;
  31. }
  32. /** Parse every JSON-RPC message the server writes to stdout into an array. */
  33. function collectMessages(child: ChildProcessWithoutNullStreams): Array<Record<string, any>> {
  34. const messages: Array<Record<string, any>> = [];
  35. let buf = '';
  36. child.stdout.on('data', (chunk) => {
  37. buf += chunk.toString('utf8');
  38. let idx;
  39. while ((idx = buf.indexOf('\n')) !== -1) {
  40. const line = buf.slice(0, idx).trim();
  41. buf = buf.slice(idx + 1);
  42. if (!line) continue;
  43. try { messages.push(JSON.parse(line)); } catch { /* ignore non-JSON */ }
  44. }
  45. });
  46. return messages;
  47. }
  48. function waitForMessage(
  49. messages: ReadonlyArray<Record<string, any>>,
  50. predicate: (m: Record<string, any>) => boolean,
  51. timeoutMs: number,
  52. ): Promise<Record<string, any>> {
  53. return new Promise((resolve, reject) => {
  54. const started = Date.now();
  55. const tick = () => {
  56. const hit = messages.find(predicate);
  57. if (hit) return resolve(hit);
  58. if (Date.now() - started > timeoutMs) {
  59. return reject(new Error(`Timed out. Messages so far: ${JSON.stringify(messages)}`));
  60. }
  61. setTimeout(tick, 20);
  62. };
  63. tick();
  64. });
  65. }
  66. function send(child: ChildProcessWithoutNullStreams, msg: object): void {
  67. child.stdin.write(JSON.stringify(msg) + '\n');
  68. }
  69. const CLIENT_INFO = { name: 'test', version: '0.0.0' };
  70. describe('MCP project resolution via roots/list (issue #196)', () => {
  71. let cwdDir: string; // where the server is launched — has NO .codegraph
  72. let projectDir: string; // the real indexed project the client reports
  73. let child: ChildProcessWithoutNullStreams | null = null;
  74. beforeEach(() => {
  75. cwdDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-cwd-'));
  76. projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-proj-'));
  77. });
  78. afterEach(() => {
  79. if (child && !child.killed) {
  80. child.kill('SIGKILL');
  81. child = null;
  82. }
  83. fs.rmSync(cwdDir, { recursive: true, force: true });
  84. fs.rmSync(projectDir, { recursive: true, force: true });
  85. });
  86. it('resolves the project from the client roots/list when no rootUri is sent', async () => {
  87. const cg = await CodeGraph.init(projectDir);
  88. cg.close();
  89. child = spawnServer(cwdDir);
  90. const messages = collectMessages(child);
  91. // Advertise the roots capability but pass NO rootUri/workspaceFolders.
  92. send(child, {
  93. jsonrpc: '2.0', id: 0, method: 'initialize',
  94. params: { protocolVersion: '2025-11-25', capabilities: { roots: {} }, clientInfo: CLIENT_INFO },
  95. });
  96. await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
  97. send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
  98. // First tool call (no projectPath) drives the server to ask us for roots.
  99. send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  100. const rootsReq = await waitForMessage(messages, (m) => m.method === 'roots/list', 5000);
  101. expect(typeof rootsReq.id).toBe('string'); // server-initiated id
  102. send(child, {
  103. jsonrpc: '2.0', id: rootsReq.id,
  104. result: { roots: [{ uri: `file://${projectDir}`, name: 'proj' }] },
  105. });
  106. // The status call now succeeds against the resolved project.
  107. const resp = await waitForMessage(messages, (m) => m.id === 1, 8000);
  108. const text = resp.result.content[0].text as string;
  109. expect(text).toContain('CodeGraph Status');
  110. expect(text).not.toContain('No CodeGraph project is loaded');
  111. }, 20000);
  112. it('returns an actionable error when there is no rootUri and no roots capability', async () => {
  113. child = spawnServer(cwdDir);
  114. const messages = collectMessages(child);
  115. send(child, {
  116. jsonrpc: '2.0', id: 0, method: 'initialize',
  117. params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: CLIENT_INFO },
  118. });
  119. await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
  120. send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
  121. send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  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('No CodeGraph project is loaded');
  125. expect(text).toContain('projectPath');
  126. expect(text).toContain('--path');
  127. // Names the directory it actually searched (the wrong cwd) so the user can
  128. // see why detection missed. basename survives any symlink realpath-ing.
  129. expect(text).toContain(path.basename(cwdDir));
  130. // It must not have hung waiting on roots/list — the client never offered it.
  131. expect(messages.some((m) => m.method === 'roots/list')).toBe(false);
  132. }, 20000);
  133. it('honors an explicit rootUri without asking the client for roots', async () => {
  134. const cg = await CodeGraph.init(projectDir);
  135. cg.close();
  136. child = spawnServer(cwdDir);
  137. const messages = collectMessages(child);
  138. send(child, {
  139. jsonrpc: '2.0', id: 0, method: 'initialize',
  140. params: {
  141. protocolVersion: '2025-11-25',
  142. capabilities: { roots: {} },
  143. clientInfo: CLIENT_INFO,
  144. rootUri: `file://${projectDir}`,
  145. },
  146. });
  147. await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
  148. send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
  149. send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  150. const resp = await waitForMessage(messages, (m) => m.id === 1, 8000);
  151. const text = resp.result.content[0].text as string;
  152. expect(text).toContain('CodeGraph Status');
  153. // rootUri is a stronger signal than roots — we never needed to ask.
  154. expect(messages.some((m) => m.method === 'roots/list')).toBe(false);
  155. }, 20000);
  156. });