Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
!.yamllint.yaml
!.configurations/
!/.npmrc
!.mcp.json

# === Rules for root dir ===
/core
Expand Down
9 changes: 9 additions & 0 deletions .mcp.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"mcpServers": {
"node-core": {
"type": "stdio",
"command": "node",
"args": ["tools/node-core-mcp/bin/node-core-mcp.mjs", "--repo", "."]
}
}
}
12 changes: 12 additions & 0 deletions tools/node-core-mcp/bin/node-core-mcp.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env node
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import { server, start } from '../lib/server.mjs';
import { registerTools } from '../lib/tools.mjs';

const argv = process.argv.slice(2);
const repoIdx = argv.indexOf('--repo');
const ROOT = resolve(repoIdx !== -1 ? argv[repoIdx + 1] : dirname(fileURLToPath(import.meta.url)) + '/../../..');

registerTools(server, ROOT);
start();
67 changes: 67 additions & 0 deletions tools/node-core-mcp/bin/node-core-mcp.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
const SERVER = resolve(dirname(fileURLToPath(import.meta.url)), 'node-core-mcp.mjs');

function createClient(args = []) {
const proc = spawn(process.execPath, [SERVER, ...args], {
stdio: ['pipe', 'pipe', 'pipe'],
});

let buffer = '';
let nextId = 1;
const pending = new Map();

proc.stdout.setEncoding('utf8');
proc.stdout.on('data', (chunk) => {
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg = JSON.parse(line);
const cb = pending.get(msg.id);
if (cb) { pending.delete(msg.id); cb(msg); }
} catch { /* ignore malformed lines */ }
}
});

const call = (method, params = {}) => new Promise((resolve, reject) => {
const id = nextId++;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`Timeout: no response to "${method}"`));
}, 10_000);
pending.set(id, (msg) => { clearTimeout(timer); resolve(msg); });
proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
});

return { call, close: () => proc.kill() };
}

test('--repo <path>: tools use the specified root', async () => {
const client = createClient(['--repo', REPO_ROOT]);
try {
const res = await client.call('tools/call', { name: 'list_docs', arguments: {} });
assert.ok(!res.error, res.error?.message);
assert.ok(res.result.content[0].text.includes('.md'));
} finally {
client.close();
}
});

test('--repo <nonexistent>: tools return an error, server stays alive', async () => {
const client = createClient(['--repo', '/nonexistent/path']);
try {
const res = await client.call('tools/call', { name: 'list_docs', arguments: {} });
// Server must respond (not crash) — result is either an error content or isError
assert.ok(res.result || res.error, 'server should respond');
} finally {
client.close();
}
});
59 changes: 59 additions & 0 deletions tools/node-core-mcp/lib/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const registeredTools = [];

export const server = {
tool(name, description, inputSchema, handler) {
registeredTools.push({ name, description, inputSchema, handler });
},
};

function send(obj) {
process.stdout.write(JSON.stringify(obj) + '\n');
}

async function dispatch(msg) {
switch (msg.method) {
case 'initialize':
return {
protocolVersion: '2024-11-05',
capabilities: { tools: {} },
serverInfo: { name: 'node-core', version: '1.0.0' },
};
case 'notifications/initialized':
return null;
case 'tools/list':
return {
tools: registeredTools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })),
};
case 'tools/call': {
const tool = registeredTools.find((t) => t.name === msg.params?.name);
if (!tool) throw Object.assign(new Error(`Unknown tool: ${msg.params?.name}`), { code: -32601 });
return tool.handler(msg.params?.arguments ?? {});
}
default:
throw Object.assign(new Error(`Method not found: ${msg.method}`), { code: -32601 });
}
}

export function start() {
let buffer = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', async (chunk) => {
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.trim()) continue;
let msg;
try { msg = JSON.parse(line); } catch { continue; }
if (msg.id == null) continue; // Notification — no response
let result;
try {
result = await dispatch(msg);
} catch (err) {
send({ jsonrpc: '2.0', id: msg.id, error: { code: err.code ?? -32603, message: err.message } });
continue;
}
if (result !== null) send({ jsonrpc: '2.0', id: msg.id, result });
}
});
}
113 changes: 113 additions & 0 deletions tools/node-core-mcp/lib/server.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
const SERVER = resolve(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'node-core-mcp.mjs');

function createClient() {
const proc = spawn(process.execPath, [SERVER, '--repo', REPO_ROOT], {
stdio: ['pipe', 'pipe', 'pipe'],
});

let buffer = '';
let nextId = 1;
const pending = new Map();

proc.stdout.setEncoding('utf8');
proc.stdout.on('data', (chunk) => {
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) {
if (!line.trim()) continue;
try {
const msg = JSON.parse(line);
const cb = pending.get(msg.id);
if (cb) { pending.delete(msg.id); cb(msg); }
} catch { /* ignore malformed lines */ }
}
});

const call = (method, params = {}) => new Promise((resolve, reject) => {
const id = nextId++;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`Timeout: no response to "${method}"`));
}, 10_000);
pending.set(id, (msg) => { clearTimeout(timer); resolve(msg); });
proc.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
});

return { call, close: () => proc.kill() };
}

test('initialize returns protocol version and server info', async () => {
const client = createClient();
try {
const res = await client.call('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'test', version: '0.1' },
});
assert.strictEqual(res.result.protocolVersion, '2024-11-05');
assert.strictEqual(res.result.serverInfo.name, 'node-core');
assert.ok(res.result.capabilities.tools);
} finally {
client.close();
}
});

test('unknown method returns error -32601', async () => {
const client = createClient();
try {
const res = await client.call('no/such/method');
assert.ok(res.error);
assert.strictEqual(res.error.code, -32601);
} finally {
client.close();
}
});

test('tools/list returns all expected tools in order', async () => {
const client = createClient();
try {
const res = await client.call('tools/list');
const names = res.result.tools.map((t) => t.name);
assert.deepStrictEqual(names, [
'configure', 'build', 'run_test', 'run_tests',
'search_code', 'list_docs', 'read_doc',
'find_subsystem', 'list_relevant_tests', 'explain_test_failure', 'search_docs',
'get_pr_metadata',
]);
} finally {
client.close();
}
});

test('each tool has name, description, and inputSchema', async () => {
const client = createClient();
try {
const res = await client.call('tools/list');
for (const tool of res.result.tools) {
assert.ok(tool.name, 'missing name');
assert.ok(tool.description, `${tool.name}: missing description`);
assert.ok(tool.inputSchema, `${tool.name}: missing inputSchema`);
}
} finally {
client.close();
}
});

test('tools/call unknown tool returns error -32601', async () => {
const client = createClient();
try {
const res = await client.call('tools/call', { name: 'nonexistent', arguments: {} });
assert.ok(res.error);
assert.strictEqual(res.error.code, -32601);
} finally {
client.close();
}
});
Loading
Loading