Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(mcp): stdio JSON-RPC server + graft mcp CLI command
Shrish Dwivedic63b731ec26d
diff --git a/src/cli.ts b/src/cli.tsindex 0fb2e231..107e10eb 100644--- a/src/cli.ts+++ b/src/cli.ts@@ -6,6 +6,7 @@* ask query the graph ($0, no LLM).* check fail if graft/ has drifted from the code — for CI.* viz serve the interactive graph viewer.+ * mcp serve the graph over MCP (stdio) for coding agents.* init set up the Claude Code integration (.claude/ statusline + hooks) in this repo.** Git is the sync: commit graft/ and anyone who clones the repo has the@@ -186,6 +187,16 @@ program}});+program+ .command("mcp")+ .description("Serve the graph over MCP (stdio) — exposes graft_ask / graft_check / graft_blast_radius as tools")+ .argument("[dir]", "repository root", ".")+ .action(async (dir: string) => {+ const { resolve } = await import("node:path");+ const { startMcpServer } = await import("./mcp/server.js");+ startMcpServer(resolve(dir));+ });+program.command("init").description("Wire Graft into the AI coding agents used with this repo (instruction files; full hooks + statusline for Claude Code)")diff --git a/src/mcp/server.ts b/src/mcp/server.tsnew file mode 100644index 00000000..439b0fed--- /dev/null+++ b/src/mcp/server.ts@@ -0,0 +1,66 @@+/**+ * Minimal MCP stdio server: newline-delimited JSON-RPC 2.0.+ * stdout carries protocol messages ONLY; diagnostics go to stderr.+ */+import { createInterface } from 'node:readline';+import { TOOLS, callTool } from './tools.js';++function send(msg: object): void {+ process.stdout.write(`${JSON.stringify(msg)}\n`);+}++function reply(id: unknown, result: object): void {+ send({ jsonrpc: '2.0', id, result });+}++function replyError(id: unknown, code: number, message: string): void {+ send({ jsonrpc: '2.0', id, error: { code, message } });+}++export function startMcpServer(root: string): void {+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });+ rl.on('line', (line) => {+ const text = line.trim();+ if (!text) return;+ let msg: { id?: unknown; method?: string; params?: Record<string, any> };+ try {+ msg = JSON.parse(text);+ } catch {+ replyError(null, -32700, 'parse error');+ return;+ }+ const { id, method, params } = msg;+ const isNotification = id === undefined;+ switch (method) {+ case 'initialize':+ reply(id, {+ protocolVersion: params?.protocolVersion ?? '2024-11-05',+ capabilities: { tools: {} },+ serverInfo: { name: 'graft', version: '0' },+ });+ return;+ case 'notifications/initialized':+ case 'notifications/cancelled':+ return; // notifications get no response+ case 'ping':+ if (!isNotification) reply(id, {});+ return;+ case 'tools/list':+ if (!isNotification) {+ reply(id, { tools: TOOLS.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })) });+ }+ return;+ case 'tools/call': {+ if (isNotification) return;+ const name = String(params?.name ?? '');+ const args = (params?.arguments ?? {}) as Record<string, unknown>;+ const r = callTool(root, name, args);+ reply(id, { content: [{ type: 'text', text: r.text }], isError: r.isError });+ return;+ }+ default:+ if (!isNotification) replyError(id, -32601, `method not found: ${method}`);+ }+ });+ process.stdin.on('end', () => process.exit(0));+}diff --git a/test/mcp-server.test.ts b/test/mcp-server.test.tsnew file mode 100644index 00000000..2a5f799d--- /dev/null+++ b/test/mcp-server.test.ts@@ -0,0 +1,58 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { mkdtempSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { once } from 'node:events';++async function rpc(messages: object[], dir: string, expected: number): Promise<any[]> {+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'mcp', dir], { stdio: ['pipe', 'pipe', 'pipe'] });+ const responses: any[] = [];+ let buf = '';+ child.stdout.on('data', (d) => {+ buf += d.toString();+ let i;+ while ((i = buf.indexOf('\n')) !== -1) {+ const line = buf.slice(0, i).trim();+ buf = buf.slice(i + 1);+ if (line) responses.push(JSON.parse(line));+ }+ });+ for (const m of messages) child.stdin.write(`${JSON.stringify(m)}\n`);+ const deadline = Date.now() + 15000;+ while (responses.length < expected && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));+ child.kill();+ await once(child, 'exit').catch(() => {});+ return responses;+}++test('initialize → tools/list → tools/call round-trip', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv-'));+ const rs = await rpc(+ [+ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 't', version: '0' } } },+ { jsonrpc: '2.0', method: 'notifications/initialized' },+ { jsonrpc: '2.0', id: 2, method: 'tools/list' },+ { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'graft_blast_radius', arguments: { file: 'x.ts' } } },+ ],+ dir,+ 3,+ );+ assert.equal(rs.length, 3);+ const init = rs.find((r) => r.id === 1);+ assert.equal(init.result.protocolVersion, '2025-03-26');+ assert.ok(init.result.capabilities.tools);+ assert.equal(init.result.serverInfo.name, 'graft');+ const list = rs.find((r) => r.id === 2);+ assert.deepEqual(list.result.tools.map((t: any) => t.name), ['graft_ask', 'graft_check', 'graft_blast_radius']);+ const call = rs.find((r) => r.id === 3);+ assert.equal(call.result.isError, true); // unbuilt repo → soft error content+ assert.match(call.result.content[0].text, /graft build/);+});++test('unknown method returns -32601', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'graft-mcpsrv2-'));+ const rs = await rpc([{ jsonrpc: '2.0', id: 9, method: 'resources/list' }], dir, 1);+ assert.equal(rs[0].error.code, -32601);+});