454 lines
13 KiB
TypeScript
454 lines
13 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { z } from 'zod';
|
|
import * as rootResearchExports from '../src/index';
|
|
import {
|
|
JSON_RPC_ERROR_CODES,
|
|
MCP_PROTOCOL_VERSION,
|
|
createMcpServer,
|
|
defineMcpTool,
|
|
zodObjectToJsonSchema,
|
|
} from '../src/mcp/index';
|
|
|
|
interface JsonRpcParsedResponse {
|
|
jsonrpc: string;
|
|
id: string | number | null;
|
|
result?: Record<string, unknown>;
|
|
error?: {
|
|
code: number;
|
|
message: string;
|
|
data?: unknown;
|
|
};
|
|
}
|
|
|
|
function parseResponse(raw: string | null): JsonRpcParsedResponse {
|
|
expect(raw).not.toBeNull();
|
|
return JSON.parse(raw as string) as JsonRpcParsedResponse;
|
|
}
|
|
|
|
describe('MCP protocol & server core', () => {
|
|
test('initialize returns protocolVersion, serverInfo, and capabilities.tools', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'initialize',
|
|
params: {
|
|
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
capabilities: {},
|
|
clientInfo: { name: 'test-client', version: '1.0.0' },
|
|
},
|
|
})
|
|
);
|
|
|
|
const response = parseResponse(raw);
|
|
expect(response.jsonrpc).toBe('2.0');
|
|
expect(response.id).toBe(1);
|
|
expect(response.error).toBeUndefined();
|
|
expect(response.result).toEqual({
|
|
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
capabilities: { tools: {} },
|
|
serverInfo: {
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
},
|
|
});
|
|
});
|
|
|
|
test('notifications/initialized returns null (no response)', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
method: 'notifications/initialized',
|
|
})
|
|
);
|
|
|
|
expect(raw).toBeNull();
|
|
});
|
|
|
|
test('ping returns empty object result', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'ping-1',
|
|
method: 'ping',
|
|
})
|
|
);
|
|
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBe('ping-1');
|
|
expect(response.result).toEqual({});
|
|
});
|
|
|
|
test('echoes string and numeric request ids verbatim (including 0 and negative integers)', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const ids: readonly (string | number)[] = ['req-abc', '', 0, -42, 9007199254740991];
|
|
for (const id of ids) {
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id,
|
|
method: 'ping',
|
|
})
|
|
);
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBe(id);
|
|
}
|
|
});
|
|
|
|
test('malformed JSON returns -32700 with id: null', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const raw = await server.handleMessage('{not valid json');
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBeNull();
|
|
expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR);
|
|
});
|
|
|
|
test('non-JSON-RPC objects and explicit invalid id return -32600', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const badPayloads = [
|
|
'42',
|
|
'"hello"',
|
|
'null',
|
|
'[]',
|
|
JSON.stringify({ foo: 'bar' }),
|
|
JSON.stringify({ jsonrpc: '1.0', id: 1, method: 'ping' }),
|
|
JSON.stringify({ jsonrpc: '2.0', id: null, method: 'ping' }),
|
|
JSON.stringify({ jsonrpc: '2.0', id: true, method: 'ping' }),
|
|
JSON.stringify({ jsonrpc: '2.0', id: { nested: 1 }, method: 'ping' }),
|
|
JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping', extra: true }),
|
|
];
|
|
|
|
for (const payload of badPayloads) {
|
|
const raw = await server.handleMessage(payload);
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBeNull();
|
|
expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_REQUEST);
|
|
}
|
|
});
|
|
|
|
test('unknown method returns -32601 echoing request id', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'unknown-1',
|
|
method: 'resources/list',
|
|
})
|
|
);
|
|
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBe('unknown-1');
|
|
expect(response.error?.code).toBe(JSON_RPC_ERROR_CODES.METHOD_NOT_FOUND);
|
|
});
|
|
|
|
test('tools/call rejects unknown tool name and malformed params with -32602', async () => {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [],
|
|
});
|
|
|
|
const unknownToolRaw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 10,
|
|
method: 'tools/call',
|
|
params: { name: 'does_not_exist', arguments: {} },
|
|
})
|
|
);
|
|
const unknownToolResp = parseResponse(unknownToolRaw);
|
|
expect(unknownToolResp.id).toBe(10);
|
|
expect(unknownToolResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS);
|
|
|
|
const badParamsRaw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 11,
|
|
method: 'tools/call',
|
|
params: { name: 123, arguments: 'not-an-object' },
|
|
})
|
|
);
|
|
const badParamsResp = parseResponse(badParamsRaw);
|
|
expect(badParamsResp.id).toBe(11);
|
|
expect(badParamsResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS);
|
|
});
|
|
|
|
test('invalid tool arguments return isError: true with readable message and zero handler calls', async () => {
|
|
let handlerCalls = 0;
|
|
const echoTool = defineMcpTool({
|
|
name: 'echo_count',
|
|
description: 'Echoes a positive integer count.',
|
|
inputSchema: z.object({ count: z.number().int().min(1) }).strict(),
|
|
handler(input) {
|
|
handlerCalls += 1;
|
|
return {
|
|
content: [{ type: 'text', text: String(input.count) }],
|
|
};
|
|
},
|
|
});
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [echoTool],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 20,
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'echo_count',
|
|
arguments: { count: 0, unexpected: true },
|
|
},
|
|
})
|
|
);
|
|
|
|
expect(handlerCalls).toBe(0);
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBe(20);
|
|
expect(response.error).toBeUndefined();
|
|
const result = response.result as {
|
|
isError?: boolean;
|
|
content: { type: string; text: string }[];
|
|
};
|
|
expect(result.isError).toBe(true);
|
|
expect(result.content[0]?.type).toBe('text');
|
|
expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"');
|
|
});
|
|
|
|
test('throwing tool handler returns isError: true with sanitized error and zero stack trace or paths', async () => {
|
|
const boomTool = defineMcpTool({
|
|
name: 'explode',
|
|
description: 'Always throws an error.',
|
|
inputSchema: z.object({}).strict(),
|
|
handler() {
|
|
const err = new Error(
|
|
'Failed reading /mnt/data/stockbot/secret.parquet\n at secretInternal (/srv/app/secret.ts:42:9)'
|
|
);
|
|
err.name = 'BackendFailureError';
|
|
throw err;
|
|
},
|
|
});
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [boomTool],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 30,
|
|
method: 'tools/call',
|
|
params: { name: 'explode', arguments: {} },
|
|
})
|
|
);
|
|
|
|
const response = parseResponse(raw);
|
|
expect(response.id).toBe(30);
|
|
expect(response.error).toBeUndefined();
|
|
const result = response.result as {
|
|
isError?: boolean;
|
|
content: { type: string; text: string }[];
|
|
};
|
|
expect(result.isError).toBe(true);
|
|
const text = result.content[0]?.text ?? '';
|
|
expect(text).toBe('BackendFailureError: Tool execution failed.');
|
|
expect(text).not.toContain('/mnt/data/stockbot');
|
|
expect(text).not.toContain('at ');
|
|
expect(text).not.toContain('/srv/app/secret.ts');
|
|
expect(text).not.toContain('\n');
|
|
});
|
|
|
|
test('accepts standard MCP _meta.progressToken on requests and rejects malformed _meta', async () => {
|
|
let calls = 0;
|
|
const echoTool = defineMcpTool({
|
|
name: 'echo_msg',
|
|
description: 'Echoes a message.',
|
|
inputSchema: z.object({ msg: z.string() }).strict(),
|
|
handler(input) {
|
|
calls += 1;
|
|
return { content: [{ type: 'text', text: input.msg }] };
|
|
},
|
|
});
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [echoTool],
|
|
});
|
|
|
|
const initResp = parseResponse(
|
|
await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'm1',
|
|
method: 'initialize',
|
|
params: {
|
|
protocolVersion: MCP_PROTOCOL_VERSION,
|
|
_meta: { progressToken: 'init-tok' },
|
|
},
|
|
})
|
|
)
|
|
);
|
|
expect(initResp.error).toBeUndefined();
|
|
|
|
const pingResp = parseResponse(
|
|
await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'm2',
|
|
method: 'ping',
|
|
params: { _meta: { progressToken: 42 } },
|
|
})
|
|
)
|
|
);
|
|
expect(pingResp.result).toEqual({});
|
|
|
|
const listResp = parseResponse(
|
|
await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'm3',
|
|
method: 'tools/list',
|
|
params: { _meta: { progressToken: 'list-tok', customFlag: true } },
|
|
})
|
|
)
|
|
);
|
|
expect(listResp.error).toBeUndefined();
|
|
|
|
const callResp = parseResponse(
|
|
await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'm4',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'echo_msg',
|
|
arguments: { msg: 'hello' },
|
|
_meta: { progressToken: 'call-tok-1' },
|
|
},
|
|
})
|
|
)
|
|
);
|
|
expect(calls).toBe(1);
|
|
expect(callResp.error).toBeUndefined();
|
|
const callResult = callResp.result as {
|
|
isError?: boolean;
|
|
content: { type: string; text: string }[];
|
|
};
|
|
expect(callResult.isError).toBeUndefined();
|
|
expect(callResult.content[0]?.text).toBe('hello');
|
|
|
|
// Invalid progressToken type -> -32602 before handler runs
|
|
const badMetaResp = parseResponse(
|
|
await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'm5',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'echo_msg',
|
|
arguments: { msg: 'hello' },
|
|
_meta: { progressToken: true },
|
|
},
|
|
})
|
|
)
|
|
);
|
|
expect(calls).toBe(1);
|
|
expect(badMetaResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS);
|
|
});
|
|
|
|
test('raw JSON own __proto__ key in tools/call arguments is preserved and rejected by strict tool schema', async () => {
|
|
let calls = 0;
|
|
const strictTool = defineMcpTool({
|
|
name: 'strict_tool',
|
|
description: 'Accepts only x.',
|
|
inputSchema: z.object({ x: z.number() }).strict(),
|
|
handler(input) {
|
|
calls += 1;
|
|
return { content: [{ type: 'text', text: String(input.x) }] };
|
|
},
|
|
});
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [strictTool],
|
|
});
|
|
|
|
const rawRequest =
|
|
'{"jsonrpc":"2.0","id":"proto-check","method":"tools/call","params":{"name":"strict_tool","arguments":{"x":1,"__proto__":{"injected":true}}}}';
|
|
const response = parseResponse(await server.handleMessage(rawRequest));
|
|
expect(calls).toBe(0);
|
|
expect(response.error).toBeUndefined();
|
|
const result = response.result as { isError?: boolean; content: { type: string; text: string }[] };
|
|
expect(result.isError).toBe(true);
|
|
expect(result.content[0]?.text).toContain('Invalid arguments for tool "strict_tool"');
|
|
});
|
|
|
|
test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => {
|
|
const makeTool = () =>
|
|
defineMcpTool({
|
|
name: 'dup_tool',
|
|
description: 'Duplicate tool test.',
|
|
inputSchema: z.object({ x: z.string() }).strict(),
|
|
handler: () => ({ content: [{ type: 'text', text: 'ok' }] }),
|
|
});
|
|
|
|
expect(() =>
|
|
createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [makeTool(), makeTool()],
|
|
})
|
|
).toThrow(/Duplicate MCP tool name/i);
|
|
|
|
expect(() =>
|
|
zodObjectToJsonSchema(z.object({ bad: z.date() }).strict())
|
|
).toThrow(/Unsupported Zod schema type/i);
|
|
});
|
|
|
|
test('browser-safe root entrypoint does not re-export MCP symbols', () => {
|
|
const exportedKeys = Object.keys(rootResearchExports);
|
|
expect(exportedKeys).not.toContain('createMcpServer');
|
|
expect(exportedKeys).not.toContain('defineMcpTool');
|
|
expect(exportedKeys).not.toContain('runStdioServer');
|
|
expect(exportedKeys).not.toContain('createQueryDataTool');
|
|
});
|
|
});
|