mcp-initialize.test.ts 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /**
  2. * MCP `initialize` handshake regression tests.
  3. *
  4. * Issue #172: on slow filesystems (Docker Desktop VirtioFS on macOS, WSL2),
  5. * the MCP server was blocking the initialize response on CodeGraph.open() and
  6. * Parser.init() (web-tree-sitter WASM bootstrap), which could take longer than
  7. * Claude Code's ~30s handshake timeout. The child process stayed alive and
  8. * had received the request, but never sent a response, so tools never
  9. * appeared in the client. The fix sends the initialize response before
  10. * kicking off the heavy init in the background. These tests guard the
  11. * contract that initialize is fast regardless of how much work init does.
  12. */
  13. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  14. import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
  15. import * as fs from 'fs';
  16. import * as path from 'path';
  17. import * as os from 'os';
  18. import { CodeGraph } from '../src';
  19. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  20. function spawnServer(cwd: string): ChildProcessWithoutNullStreams {
  21. return spawn(process.execPath, [BIN, 'serve', '--mcp'], {
  22. cwd,
  23. stdio: ['pipe', 'pipe', 'pipe'],
  24. }) as ChildProcessWithoutNullStreams;
  25. }
  26. function sendInitialize(child: ChildProcessWithoutNullStreams, projectPath: string) {
  27. const msg = JSON.stringify({
  28. jsonrpc: '2.0',
  29. id: 0,
  30. method: 'initialize',
  31. params: {
  32. protocolVersion: '2025-11-25',
  33. capabilities: {},
  34. clientInfo: { name: 'test', version: '0.0.0' },
  35. rootUri: `file://${projectPath}`,
  36. },
  37. });
  38. child.stdin.write(msg + '\n');
  39. }
  40. /**
  41. * Collect stdout lines and stderr text from the child, tagging each piece
  42. * with a monotonic sequence number. Lets us assert ordering between the
  43. * JSON-RPC response (stdout) and side-effect logs (stderr).
  44. */
  45. function tagStreams(child: ChildProcessWithoutNullStreams) {
  46. const events: Array<{ seq: number; stream: 'stdout' | 'stderr'; text: string }> = [];
  47. let seq = 0;
  48. let stdoutBuf = '';
  49. let stderrBuf = '';
  50. child.stdout.on('data', (chunk) => {
  51. stdoutBuf += chunk.toString('utf8');
  52. let idx;
  53. while ((idx = stdoutBuf.indexOf('\n')) !== -1) {
  54. const line = stdoutBuf.slice(0, idx);
  55. stdoutBuf = stdoutBuf.slice(idx + 1);
  56. events.push({ seq: seq++, stream: 'stdout', text: line });
  57. }
  58. });
  59. child.stderr.on('data', (chunk) => {
  60. stderrBuf += chunk.toString('utf8');
  61. let idx;
  62. while ((idx = stderrBuf.indexOf('\n')) !== -1) {
  63. const line = stderrBuf.slice(0, idx);
  64. stderrBuf = stderrBuf.slice(idx + 1);
  65. events.push({ seq: seq++, stream: 'stderr', text: line });
  66. }
  67. });
  68. return events;
  69. }
  70. function waitFor<T>(
  71. events: ReadonlyArray<{ seq: number; stream: string; text: string }>,
  72. predicate: (e: { seq: number; stream: string; text: string }) => boolean,
  73. timeoutMs: number,
  74. ): Promise<{ seq: number; stream: string; text: string }> {
  75. return new Promise((resolve, reject) => {
  76. const started = Date.now();
  77. const tick = () => {
  78. const hit = events.find(predicate);
  79. if (hit) return resolve(hit);
  80. if (Date.now() - started > timeoutMs) {
  81. return reject(new Error(`Timed out waiting for predicate. Events: ${JSON.stringify(events)}`));
  82. }
  83. setTimeout(tick, 20);
  84. };
  85. tick();
  86. });
  87. }
  88. describe('MCP initialize handshake (issue #172)', () => {
  89. let tempDir: string;
  90. let child: ChildProcessWithoutNullStreams | null = null;
  91. beforeEach(() => {
  92. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-init-'));
  93. });
  94. afterEach(() => {
  95. if (child && !child.killed) {
  96. child.kill('SIGKILL');
  97. child = null;
  98. }
  99. fs.rmSync(tempDir, { recursive: true, force: true });
  100. });
  101. it('responds to initialize quickly when no .codegraph exists in cwd', async () => {
  102. child = spawnServer(tempDir);
  103. const events = tagStreams(child);
  104. sendInitialize(child, tempDir);
  105. const response = await waitFor(events, (e) => e.stream === 'stdout', 5000);
  106. const json = JSON.parse(response.text);
  107. expect(json.jsonrpc).toBe('2.0');
  108. expect(json.id).toBe(0);
  109. expect(json.result.protocolVersion).toBeDefined();
  110. expect(json.result.capabilities.tools).toBeDefined();
  111. }, 10000);
  112. it('sends initialize response BEFORE tryInitializeDefault finishes', async () => {
  113. // Seed a real .codegraph so the server's tryInitializeDefault path runs
  114. // its full body: CodeGraph.open() (which awaits initGrammars()) and then
  115. // startWatching() (which logs "File watcher active" to stderr). On any
  116. // platform, that stderr log is observable evidence that tryInitializeDefault
  117. // has completed. The contract we're protecting: the JSON-RPC response on
  118. // stdout must arrive BEFORE that stderr log. If a future change re-awaits
  119. // tryInitializeDefault before sendResult, this ordering inverts and the
  120. // test fails — regardless of how fast the local filesystem is.
  121. const cg = await CodeGraph.init(tempDir);
  122. cg.close();
  123. child = spawnServer(tempDir);
  124. const events = tagStreams(child);
  125. sendInitialize(child, tempDir);
  126. const response = await waitFor(events, (e) => e.stream === 'stdout', 10000);
  127. const watcherLog = await waitFor(
  128. events,
  129. (e) => e.stream === 'stderr' && e.text.includes('File watcher active'),
  130. 10000,
  131. );
  132. expect(response.seq).toBeLessThan(watcherLog.seq);
  133. const json = JSON.parse(response.text);
  134. expect(json.id).toBe(0);
  135. expect(json.result.serverInfo.name).toBe('codegraph');
  136. }, 20000);
  137. });