T-129: M2.1a — MCP copilot core: dependency-free JSON-RPC/MCP stdio server + tool registry + vault-fenced query_data in libs/research/src/mcp/
This commit is contained in:
parent
0bea9a6f1d
commit
73ac978bb3
10 changed files with 2266 additions and 0 deletions
324
libs/research/test/mcp-protocol.test.ts
Normal file
324
libs/research/test/mcp-protocol.test.ts
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
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', async () => {
|
||||
const boomTool = defineMcpTool({
|
||||
name: 'explode',
|
||||
description: 'Always throws an error.',
|
||||
inputSchema: z.object({}).strict(),
|
||||
handler() {
|
||||
const err = new Error('Simulated backend failure\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: Simulated backend failure');
|
||||
expect(text).not.toContain('at ');
|
||||
expect(text).not.toContain('/srv/app/secret.ts');
|
||||
expect(text).not.toContain('\n');
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
482
libs/research/test/mcp-query-data.test.ts
Normal file
482
libs/research/test/mcp-query-data.test.ts
Normal file
|
|
@ -0,0 +1,482 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
} from '../src/market-data-store';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type BarsQuery,
|
||||
MarketDataStoreNotImplementedError,
|
||||
type UniverseQuery,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import {
|
||||
QUERY_DATA_DEFAULT_LIMIT,
|
||||
QUERY_DATA_MAX_LIMIT,
|
||||
type QueryDataResultPayload,
|
||||
createMcpServer,
|
||||
createQueryDataTool,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z
|
||||
|
||||
function makeBar(listingId: number, ts: number, close: number, knownAt = ts): BarRecord {
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: close - 1,
|
||||
high: close + 1,
|
||||
low: close - 2,
|
||||
close,
|
||||
volume: 1_000,
|
||||
vwap: close,
|
||||
knownAt,
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeStoreState {
|
||||
readonly barsCalls: BarsQuery[];
|
||||
readonly universeCalls: UniverseQuery[];
|
||||
readonly store: MarketDataStore;
|
||||
}
|
||||
|
||||
function createFakeStore(options?: {
|
||||
batches?: readonly BarBatch[];
|
||||
universeIds?: readonly number[];
|
||||
barsError?: Error;
|
||||
universeError?: Error;
|
||||
}): FakeStoreState {
|
||||
const barsCalls: BarsQuery[] = [];
|
||||
const universeCalls: UniverseQuery[] = [];
|
||||
|
||||
const batches = options?.batches ?? [];
|
||||
const universeIds = options?.universeIds ?? [];
|
||||
|
||||
const store: MarketDataStore = {
|
||||
bars(q: BarsQuery): AsyncIterable<BarBatch> {
|
||||
barsCalls.push(q);
|
||||
if (options?.barsError !== undefined) {
|
||||
const err = options.barsError;
|
||||
return {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
next() {
|
||||
return Promise.reject(err);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const batch of batches) {
|
||||
yield batch;
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
async universe(q: UniverseQuery): Promise<number[]> {
|
||||
universeCalls.push(q);
|
||||
if (options?.universeError !== undefined) {
|
||||
throw options.universeError;
|
||||
}
|
||||
return [...universeIds];
|
||||
},
|
||||
crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
},
|
||||
events() {
|
||||
throw new MarketDataStoreNotImplementedError('events');
|
||||
},
|
||||
shortsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
||||
},
|
||||
macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
},
|
||||
fx() {
|
||||
throw new MarketDataStoreNotImplementedError('fx');
|
||||
},
|
||||
};
|
||||
|
||||
return { barsCalls, universeCalls, store };
|
||||
}
|
||||
|
||||
async function callQueryData(
|
||||
fake: FakeStoreState,
|
||||
args: Record<string, unknown>
|
||||
): Promise<{
|
||||
rawResponse: string;
|
||||
isError: boolean;
|
||||
text: string;
|
||||
}> {
|
||||
const tool = createQueryDataTool({
|
||||
store: fake.store,
|
||||
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
||||
});
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [tool],
|
||||
});
|
||||
|
||||
const rawResponse = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 'q1',
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'query_data',
|
||||
arguments: args,
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
expect(rawResponse).not.toBeNull();
|
||||
const parsed = JSON.parse(rawResponse as string) as {
|
||||
result: {
|
||||
isError?: boolean;
|
||||
content: { type: string; text: string }[];
|
||||
};
|
||||
};
|
||||
return {
|
||||
rawResponse: rawResponse as string,
|
||||
isError: parsed.result.isError === true,
|
||||
text: parsed.result.content[0]?.text ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
describe('MCP query_data tool', () => {
|
||||
test('tools/list exposes query_data with strict inputSchema and omits scope / vault_evaluation_only', async () => {
|
||||
const fake = createFakeStore();
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [
|
||||
createQueryDataTool({
|
||||
store: fake.store,
|
||||
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const raw = await server.handleMessage(
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'tools/list',
|
||||
})
|
||||
);
|
||||
|
||||
const parsed = JSON.parse(raw as string) as {
|
||||
result: {
|
||||
tools: {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: {
|
||||
type: string;
|
||||
properties: Record<string, unknown>;
|
||||
required?: string[];
|
||||
additionalProperties: boolean;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
};
|
||||
|
||||
expect(parsed.result.tools).toHaveLength(1);
|
||||
const tool = parsed.result.tools[0];
|
||||
expect(tool?.name).toBe('query_data');
|
||||
expect(tool?.inputSchema.type).toBe('object');
|
||||
expect(tool?.inputSchema.additionalProperties).toBe(false);
|
||||
expect(tool?.inputSchema.required).toEqual(['from', 'to']);
|
||||
|
||||
const propKeys = Object.keys(tool?.inputSchema.properties ?? {});
|
||||
expect(propKeys).toContain('listingIds');
|
||||
expect(propKeys).toContain('universe');
|
||||
expect(propKeys).toContain('from');
|
||||
expect(propKeys).toContain('to');
|
||||
expect(propKeys).toContain('limit');
|
||||
expect(propKeys).not.toContain('scope');
|
||||
expect(propKeys).not.toContain('vault_evaluation_only');
|
||||
expect(tool?.inputSchema.required).not.toContain('scope');
|
||||
expect(tool?.inputSchema.required).not.toContain('vault_evaluation_only');
|
||||
});
|
||||
|
||||
test('returns pre-cutoff rows and records scope === vault_fenced on every bars() call', async () => {
|
||||
const bar1 = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.5);
|
||||
const bar2 = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 152.0);
|
||||
const fake = createFakeStore({
|
||||
batches: [{ rows: [bar1, bar2] }],
|
||||
});
|
||||
|
||||
const { isError, text } = await callQueryData(fake, {
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
});
|
||||
|
||||
expect(isError).toBe(false);
|
||||
expect(fake.barsCalls).toHaveLength(1);
|
||||
expect(fake.barsCalls[0]?.scope).toBe('vault_fenced');
|
||||
|
||||
const payload = JSON.parse(text) as QueryDataResultPayload;
|
||||
expect(payload.scope).toBe('vault_fenced');
|
||||
expect(payload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS);
|
||||
expect(payload.clampedTo).toBe(false);
|
||||
expect(payload.rowCount).toBe(2);
|
||||
expect(payload.truncated).toBe(false);
|
||||
expect(payload.rows).toEqual([bar1, bar2]);
|
||||
});
|
||||
|
||||
test('enforces default limit, explicit limit, max limit, and rejects out-of-bounds limits with zero store calls', async () => {
|
||||
const totalRows = QUERY_DATA_MAX_LIMIT + 5;
|
||||
const allRows: BarRecord[] = [];
|
||||
for (let i = 0; i < totalRows; i += 1) {
|
||||
allRows.push(makeBar(101, Date.UTC(2024, 0, 1, 0, 0, 0) + i * 60_000, 100 + i * 0.01));
|
||||
}
|
||||
|
||||
// Omitted limit -> caps at QUERY_DATA_DEFAULT_LIMIT with truncated: true
|
||||
const defaultFake = createFakeStore({ batches: [{ rows: allRows }] });
|
||||
const defaultRes = await callQueryData(defaultFake, {
|
||||
listingIds: [101],
|
||||
from: '2024-01-01',
|
||||
to: '2025-03-01',
|
||||
});
|
||||
expect(defaultRes.isError).toBe(false);
|
||||
const defaultPayload = JSON.parse(defaultRes.text) as QueryDataResultPayload;
|
||||
expect(defaultPayload.limit).toBe(QUERY_DATA_DEFAULT_LIMIT);
|
||||
expect(defaultPayload.rowCount).toBe(QUERY_DATA_DEFAULT_LIMIT);
|
||||
expect(defaultPayload.truncated).toBe(true);
|
||||
|
||||
// Explicit limit -> caps at requested value
|
||||
const explicitFake = createFakeStore({ batches: [{ rows: allRows }] });
|
||||
const explicitRes = await callQueryData(explicitFake, {
|
||||
listingIds: [101],
|
||||
from: '2024-01-01',
|
||||
to: '2025-03-01',
|
||||
limit: 3,
|
||||
});
|
||||
expect(explicitRes.isError).toBe(false);
|
||||
const explicitPayload = JSON.parse(explicitRes.text) as QueryDataResultPayload;
|
||||
expect(explicitPayload.limit).toBe(3);
|
||||
expect(explicitPayload.rowCount).toBe(3);
|
||||
expect(explicitPayload.truncated).toBe(true);
|
||||
|
||||
// Exact QUERY_DATA_MAX_LIMIT -> succeeds
|
||||
const maxFake = createFakeStore({ batches: [{ rows: allRows }] });
|
||||
const maxRes = await callQueryData(maxFake, {
|
||||
listingIds: [101],
|
||||
from: '2024-01-01',
|
||||
to: '2025-03-01',
|
||||
limit: QUERY_DATA_MAX_LIMIT,
|
||||
});
|
||||
expect(maxRes.isError).toBe(false);
|
||||
const maxPayload = JSON.parse(maxRes.text) as QueryDataResultPayload;
|
||||
expect(maxPayload.rowCount).toBe(QUERY_DATA_MAX_LIMIT);
|
||||
expect(maxPayload.truncated).toBe(true);
|
||||
|
||||
// limit > QUERY_DATA_MAX_LIMIT or <= 0 -> isError: true with zero store calls
|
||||
for (const badLimit of [QUERY_DATA_MAX_LIMIT + 1, 0, -5]) {
|
||||
const badFake = createFakeStore({ batches: [{ rows: allRows }] });
|
||||
const badRes = await callQueryData(badFake, {
|
||||
listingIds: [101],
|
||||
from: '2024-01-01',
|
||||
to: '2025-03-01',
|
||||
limit: badLimit,
|
||||
});
|
||||
expect(badRes.isError).toBe(true);
|
||||
expect(badFake.barsCalls).toHaveLength(0);
|
||||
expect(badFake.universeCalls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects scope, vault_evaluation_only, or unknown keys with isError: true and zero store calls', async () => {
|
||||
const injectedPayloads: Record<string, unknown>[] = [
|
||||
{
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
scope: 'vault_evaluation_only',
|
||||
},
|
||||
{
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
scope: 'vault_fenced',
|
||||
},
|
||||
{
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
vault_evaluation_only: true,
|
||||
},
|
||||
{
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
unknownFlag: 'x',
|
||||
},
|
||||
];
|
||||
|
||||
for (const args of injectedPayloads) {
|
||||
const fake = createFakeStore({
|
||||
batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }],
|
||||
});
|
||||
const res = await callQueryData(fake, args);
|
||||
expect(res.isError).toBe(true);
|
||||
expect(fake.barsCalls).toHaveLength(0);
|
||||
expect(fake.universeCalls).toHaveLength(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('range starting at or after vaultCutoffTs returns isError: true naming VaultHoldoutFenceError with zero store calls', async () => {
|
||||
const fake = createFakeStore({
|
||||
batches: [{ rows: [makeBar(101, Date.UTC(2025, 3, 5, 20, 0, 0), 200)] }],
|
||||
});
|
||||
|
||||
const res = await callQueryData(fake, {
|
||||
listingIds: [101],
|
||||
from: '2025-03-31',
|
||||
to: '2025-04-15',
|
||||
});
|
||||
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res.text).toContain('VaultHoldoutFenceError');
|
||||
expect(fake.barsCalls).toHaveLength(0);
|
||||
expect(fake.universeCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('range straddling vaultCutoffTs clamps to/asOf strictly below cutoff', async () => {
|
||||
const preBar = makeBar(101, Date.UTC(2025, 2, 30, 20, 0, 0), 150);
|
||||
const fake = createFakeStore({
|
||||
batches: [{ rows: [preBar] }],
|
||||
});
|
||||
|
||||
const res = await callQueryData(fake, {
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-04-30',
|
||||
asOf: '2025-05-01',
|
||||
});
|
||||
|
||||
expect(res.isError).toBe(false);
|
||||
expect(fake.barsCalls).toHaveLength(1);
|
||||
expect(fake.barsCalls[0]?.scope).toBe('vault_fenced');
|
||||
expect(Date.parse(fake.barsCalls[0]?.to ?? '')).toBe(VAULT_CUTOFF_TS - 1);
|
||||
expect(Date.parse(fake.barsCalls[0]?.asOf ?? '')).toBe(VAULT_CUTOFF_TS - 1);
|
||||
|
||||
const payload = JSON.parse(res.text) as QueryDataResultPayload;
|
||||
expect(payload.clampedTo).toBe(true);
|
||||
expect(payload.clampedAsOf).toBe(true);
|
||||
expect(payload.toMs).toBe(VAULT_CUTOFF_TS - 1);
|
||||
expect(payload.asOfMs).toBe(VAULT_CUTOFF_TS - 1);
|
||||
expect(payload.rows).toEqual([preBar]);
|
||||
});
|
||||
|
||||
test('defense-in-depth drops post-cutoff rows (ts >= cutoff or knownAt >= cutoff) from a leaky store', async () => {
|
||||
const preBar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150);
|
||||
const leakyTsBar = makeBar(101, VAULT_CUTOFF_TS, 999);
|
||||
const leakyFutureTsBar = makeBar(101, Date.UTC(2025, 3, 2, 20, 0, 0), 1000);
|
||||
const leakyKnownAtBar = makeBar(
|
||||
101,
|
||||
Date.UTC(2025, 2, 25, 20, 0, 0),
|
||||
148,
|
||||
VAULT_CUTOFF_TS
|
||||
);
|
||||
|
||||
const fake = createFakeStore({
|
||||
batches: [{ rows: [preBar, leakyTsBar, leakyFutureTsBar, leakyKnownAtBar] }],
|
||||
});
|
||||
|
||||
const res = await callQueryData(fake, {
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-04-15',
|
||||
});
|
||||
|
||||
expect(res.isError).toBe(false);
|
||||
const payload = JSON.parse(res.text) as QueryDataResultPayload;
|
||||
expect(payload.rowCount).toBe(1);
|
||||
expect(payload.rows).toEqual([preBar]);
|
||||
});
|
||||
|
||||
test('universe path resolves strictly pre-cutoff date and handles empty universe cleanly', async () => {
|
||||
const preBar = makeBar(202, Date.UTC(2025, 2, 28, 20, 0, 0), 50);
|
||||
const populatedFake = createFakeStore({
|
||||
universeIds: [202],
|
||||
batches: [{ rows: [preBar] }],
|
||||
});
|
||||
|
||||
const res = await callQueryData(populatedFake, {
|
||||
universe: 'US_EQ',
|
||||
from: '2025-03-01',
|
||||
to: '2025-04-30',
|
||||
});
|
||||
|
||||
expect(res.isError).toBe(false);
|
||||
expect(populatedFake.universeCalls).toEqual([{ ref: 'US_EQ', date: '2025-03-30' }]);
|
||||
expect(populatedFake.barsCalls).toHaveLength(1);
|
||||
expect(populatedFake.barsCalls[0]?.listingIds).toEqual([202]);
|
||||
expect(populatedFake.barsCalls[0]?.scope).toBe('vault_fenced');
|
||||
|
||||
// Empty universe -> zero bars() calls
|
||||
const emptyFake = createFakeStore({ universeIds: [] });
|
||||
const emptyRes = await callQueryData(emptyFake, {
|
||||
universe: 'CA_EQ',
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
});
|
||||
expect(emptyRes.isError).toBe(false);
|
||||
expect(emptyFake.universeCalls).toHaveLength(1);
|
||||
expect(emptyFake.barsCalls).toHaveLength(0);
|
||||
const emptyPayload = JSON.parse(emptyRes.text) as QueryDataResultPayload;
|
||||
expect(emptyPayload.rowCount).toBe(0);
|
||||
expect(emptyPayload.rows).toEqual([]);
|
||||
});
|
||||
|
||||
test('maps store domain errors to isError: true naming the exact error class without stack traces', async () => {
|
||||
const domainErrors: readonly [Error, string][] = [
|
||||
[new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'],
|
||||
[new MarketDataStoreValidationError('Bad timeframe bound', 'from'), 'MarketDataStoreValidationError'],
|
||||
[new MarketDataStoreNotImplementedError('bars', '1m not supported'), 'MarketDataStoreNotImplementedError'],
|
||||
[new AdjFactorsSnapshotError('retrospective_rejected', 'Retrospective snapshot rejected'), 'AdjFactorsSnapshotError'],
|
||||
];
|
||||
|
||||
for (const [err, expectedName] of domainErrors) {
|
||||
const fake = createFakeStore({ barsError: err });
|
||||
const res = await callQueryData(fake, {
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
});
|
||||
expect(res.isError).toBe(true);
|
||||
expect(res.text).toContain(expectedName);
|
||||
expect(res.text).not.toContain('\n');
|
||||
expect(res.text).not.toContain('at ');
|
||||
}
|
||||
});
|
||||
|
||||
test('repeated identical calls produce byte-identical JSON output', async () => {
|
||||
const bar = makeBar(101, Date.UTC(2025, 2, 28, 20, 0, 0), 150.25);
|
||||
const fake1 = createFakeStore({ batches: [{ rows: [bar] }] });
|
||||
const fake2 = createFakeStore({ batches: [{ rows: [bar] }] });
|
||||
|
||||
const args = {
|
||||
listingIds: [101],
|
||||
from: '2025-03-01',
|
||||
to: '2025-03-30',
|
||||
timeframe: '1d',
|
||||
adjustment: 'raw',
|
||||
limit: 10,
|
||||
};
|
||||
|
||||
const res1 = await callQueryData(fake1, args);
|
||||
const res2 = await callQueryData(fake2, args);
|
||||
expect(res1.rawResponse).toBe(res2.rawResponse);
|
||||
});
|
||||
});
|
||||
195
libs/research/test/mcp-stdio.test.ts
Normal file
195
libs/research/test/mcp-stdio.test.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
JSON_RPC_ERROR_CODES,
|
||||
type StdioOutput,
|
||||
createMcpServer,
|
||||
defineMcpTool,
|
||||
runStdioServer,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
function createMemoryOutput(): { output: StdioOutput; chunks: string[]; text: () => string } {
|
||||
const chunks: string[] = [];
|
||||
const output: StdioOutput = {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
};
|
||||
return {
|
||||
output,
|
||||
chunks,
|
||||
text: () => chunks.join(''),
|
||||
};
|
||||
}
|
||||
|
||||
async function* yieldChunks(chunks: readonly (Uint8Array | string)[]): AsyncGenerator<Uint8Array | string> {
|
||||
for (const chunk of chunks) {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
|
||||
describe('MCP stdio transport', () => {
|
||||
test('processes 3 messages (1 notification + 1 chunk-split multi-byte UTF-8 request) into exactly 2 newline-terminated responses', async () => {
|
||||
const echoTool = defineMcpTool({
|
||||
name: 'echo_label',
|
||||
description: 'Echoes a UTF-8 label.',
|
||||
inputSchema: z.object({ label: z.string() }).strict(),
|
||||
handler(input) {
|
||||
return {
|
||||
content: [{ type: 'text', text: input.label }],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [echoTool],
|
||||
});
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const msg1 = `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`;
|
||||
const msg2 = `${JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' })}\n`;
|
||||
const msg3Bytes = encoder.encode(
|
||||
`${JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 'utf8-2',
|
||||
method: 'tools/call',
|
||||
params: { name: 'echo_label', arguments: { label: 'café-🚀-αβγ' } },
|
||||
})}\n`
|
||||
);
|
||||
|
||||
// Split right in the middle of the multi-byte UTF-8 emoji sequence.
|
||||
const rocketStart = msg3Bytes.indexOf(0xf0);
|
||||
expect(rocketStart).toBeGreaterThan(0);
|
||||
const splitPoint = rocketStart + 2;
|
||||
|
||||
const input = yieldChunks([
|
||||
encoder.encode(msg1),
|
||||
encoder.encode(msg2),
|
||||
msg3Bytes.slice(0, splitPoint),
|
||||
msg3Bytes.slice(splitPoint),
|
||||
]);
|
||||
|
||||
const sink = createMemoryOutput();
|
||||
await runStdioServer(server, { input, output: sink.output });
|
||||
|
||||
const rawOut = sink.text();
|
||||
expect(rawOut.endsWith('\n')).toBe(true);
|
||||
const lines = rawOut.slice(0, -1).split('\n');
|
||||
expect(lines).toHaveLength(2);
|
||||
|
||||
const resp1 = JSON.parse(lines[0] ?? '') as { id: number; result: Record<string, unknown> };
|
||||
const resp2 = JSON.parse(lines[1] ?? '') as {
|
||||
id: string;
|
||||
result: { content: { type: string; text: string }[] };
|
||||
};
|
||||
|
||||
expect(resp1.id).toBe(1);
|
||||
expect(resp1.result).toEqual({});
|
||||
expect(resp2.id).toBe('utf8-2');
|
||||
expect(resp2.result.content[0]?.text).toBe('café-🚀-αβγ');
|
||||
});
|
||||
|
||||
test('preserves strict arrival order even when earlier async handler takes longer than later handler', async () => {
|
||||
const delayedTool = defineMcpTool({
|
||||
name: 'delayed',
|
||||
description: 'Resolves after deterministic microtask/timer delay.',
|
||||
inputSchema: z.object({ tag: z.string(), delayMs: z.number().int().min(0) }).strict(),
|
||||
async handler(input) {
|
||||
await new Promise<void>(resolve => {
|
||||
setTimeout(resolve, input.delayMs);
|
||||
});
|
||||
return {
|
||||
content: [{ type: 'text', text: input.tag }],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
tools: [delayedTool],
|
||||
});
|
||||
|
||||
const payload = [
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 'first-slow',
|
||||
method: 'tools/call',
|
||||
params: { name: 'delayed', arguments: { tag: 'first', delayMs: 25 } },
|
||||
}),
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 'second-fast',
|
||||
method: 'tools/call',
|
||||
params: { name: 'delayed', arguments: { tag: 'second', delayMs: 0 } },
|
||||
}),
|
||||
].join('\n');
|
||||
|
||||
const sink = createMemoryOutput();
|
||||
await runStdioServer(server, {
|
||||
input: yieldChunks([`${payload}\n`]),
|
||||
output: sink.output,
|
||||
});
|
||||
|
||||
const lines = sink.text().trimEnd().split('\n');
|
||||
expect(lines).toHaveLength(2);
|
||||
const first = JSON.parse(lines[0] ?? '') as { id: string };
|
||||
const second = JSON.parse(lines[1] ?? '') as { id: string };
|
||||
expect(first.id).toBe('first-slow');
|
||||
expect(second.id).toBe('second-fast');
|
||||
});
|
||||
|
||||
test('ignores blank lines, handles CRLF, and flushes a final non-newline-terminated line on EOF', async () => {
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
});
|
||||
|
||||
const input = yieldChunks([
|
||||
'\n \r\n',
|
||||
`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\r\n`,
|
||||
'\n',
|
||||
JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' }),
|
||||
]);
|
||||
|
||||
const sink = createMemoryOutput();
|
||||
await runStdioServer(server, { input, output: sink.output });
|
||||
|
||||
const lines = sink.text().trimEnd().split('\n');
|
||||
expect(lines).toHaveLength(2);
|
||||
expect((JSON.parse(lines[0] ?? '') as { id: number }).id).toBe(1);
|
||||
expect((JSON.parse(lines[1] ?? '') as { id: number }).id).toBe(2);
|
||||
});
|
||||
|
||||
test('rejects oversized frames exceeding maxLineBytes with -32700 and recovers on the next line', async () => {
|
||||
const server = createMcpServer({
|
||||
name: 'stock-bot-research',
|
||||
version: '0.1.0',
|
||||
});
|
||||
|
||||
const hugeLine = `{"jsonrpc":"2.0","id":1,"method":"ping","pad":"${'x'.repeat(300)}"}\n`;
|
||||
const nextLine = `${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'ping' })}\n`;
|
||||
|
||||
const sink = createMemoryOutput();
|
||||
await runStdioServer(server, {
|
||||
input: yieldChunks([hugeLine, nextLine]),
|
||||
output: sink.output,
|
||||
maxLineBytes: 128,
|
||||
});
|
||||
|
||||
const lines = sink.text().trimEnd().split('\n');
|
||||
expect(lines).toHaveLength(2);
|
||||
const errResp = JSON.parse(lines[0] ?? '') as {
|
||||
id: null;
|
||||
error: { code: number };
|
||||
};
|
||||
const okResp = JSON.parse(lines[1] ?? '') as { id: number; result: Record<string, unknown> };
|
||||
expect(errResp.id).toBeNull();
|
||||
expect(errResp.error.code).toBe(JSON_RPC_ERROR_CODES.PARSE_ERROR);
|
||||
expect(okResp.id).toBe(2);
|
||||
expect(okResp.result).toEqual({});
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue