1100 lines
36 KiB
TypeScript
1100 lines
36 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import { readFileSync } from 'node:fs';
|
|
import type {
|
|
BarBatch,
|
|
BarQuery,
|
|
BarRecord,
|
|
MarketDataStore,
|
|
} from '../src/market-data-store';
|
|
import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb';
|
|
import {
|
|
type LibraryCardQuery,
|
|
type LibraryCardRecord,
|
|
type PostgresResearchCopilotExecutor,
|
|
RESEARCH_COPILOT_HOST_NAME,
|
|
RESEARCH_COPILOT_HOST_VERSION,
|
|
RESEARCH_COPILOT_TOOL_NAMES,
|
|
type QueryDataResultPayload,
|
|
type ReadKnowledgeResultPayload,
|
|
type ResearchCopilotHostConfig,
|
|
ResearchCopilotHostConfigError,
|
|
type StdioInput,
|
|
type StdioOutput,
|
|
parseResearchCopilotHostConfig,
|
|
runResearchCopilotStdioHost,
|
|
} from '../src/mcp/index';
|
|
|
|
const FAKE_DECODED_PASSWORD = 's3cr@t pass#99!';
|
|
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_DECODED_PASSWORD);
|
|
const FAKE_POSTGRES_URL = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev?sslmode=disable`;
|
|
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
|
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
|
|
const VALID_CUTOFF_MS = Date.UTC(2025, 5, 1, 0, 0, 0, 0);
|
|
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
|
|
|
|
function buildValidEnv(
|
|
overrides: Readonly<Record<string, string | undefined>> = {}
|
|
): Record<string, string | undefined> {
|
|
return {
|
|
PATH: '/usr/local/bin:/usr/bin',
|
|
HOME: '/tmp/fake-home',
|
|
NODE_ENV: 'test',
|
|
RESEARCH_MCP_POSTGRES_URL: FAKE_POSTGRES_URL,
|
|
RESEARCH_MCP_POSTGRES_SCHEMA: 'research_ro',
|
|
RESEARCH_MCP_CURATED_ROOT: '/mnt/data/stockbot/curated',
|
|
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
|
|
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
|
|
RESEARCH_MCP_LIBRARY_ROOT: '/mnt/data/stockbot/library',
|
|
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({
|
|
XNYS: [101, 102],
|
|
XTSE: [201],
|
|
}),
|
|
RESEARCH_MCP_EARLY_CLOSES: JSON.stringify({
|
|
XNYS: {
|
|
'2024-11-29': 780,
|
|
'2024-12-24': 780,
|
|
},
|
|
}),
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function assertNoCredentialLeak(error: unknown): void {
|
|
expect(error).toBeInstanceOf(Error);
|
|
const err = error as Error & { cause?: unknown };
|
|
expect(err.message).not.toContain(FAKE_POSTGRES_URL);
|
|
expect(err.message).not.toContain(FAKE_ENCODED_PASSWORD);
|
|
expect(err.message).not.toContain(FAKE_DECODED_PASSWORD);
|
|
if (err.cause !== undefined) {
|
|
assertNoCredentialLeak(err.cause);
|
|
}
|
|
}
|
|
|
|
function createMemoryOutput(): {
|
|
readonly output: StdioOutput;
|
|
readonly chunks: string[];
|
|
text(): string;
|
|
jsonLines(): unknown[];
|
|
} {
|
|
const chunks: string[] = [];
|
|
const output: StdioOutput = {
|
|
write(chunk: string): boolean {
|
|
chunks.push(chunk);
|
|
return true;
|
|
},
|
|
};
|
|
return {
|
|
output,
|
|
chunks,
|
|
text: () => chunks.join(''),
|
|
jsonLines: () => {
|
|
const raw = chunks.join('');
|
|
if (raw.length === 0) {
|
|
return [];
|
|
}
|
|
return raw
|
|
.trimEnd()
|
|
.split('\n')
|
|
.map(line => JSON.parse(line) as unknown);
|
|
},
|
|
};
|
|
}
|
|
|
|
function createTrackingInput(messages: readonly unknown[]): {
|
|
readonly input: StdioInput;
|
|
readonly getPulledCount: () => number;
|
|
} {
|
|
let pulled = 0;
|
|
const input: StdioInput = {
|
|
async *[Symbol.asyncIterator]() {
|
|
for (const msg of messages) {
|
|
pulled += 1;
|
|
yield `${JSON.stringify(msg)}\n`;
|
|
}
|
|
},
|
|
};
|
|
return {
|
|
input,
|
|
getPulledCount: () => pulled,
|
|
};
|
|
}
|
|
|
|
function createFakeExecutor(): {
|
|
readonly executor: PostgresResearchCopilotExecutor;
|
|
readonly calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }>;
|
|
} {
|
|
const calls: Array<{ readonly text: string; readonly params: readonly unknown[] | undefined }> = [];
|
|
const executor: PostgresResearchCopilotExecutor = {
|
|
async query<Row = Record<string, unknown>>(
|
|
text: string,
|
|
params?: readonly unknown[]
|
|
): Promise<{ readonly rows: readonly Row[] }> {
|
|
calls.push({ text, params });
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
return { executor, calls };
|
|
}
|
|
|
|
function createFakeStore(
|
|
rows: readonly BarRecord[] = []
|
|
): {
|
|
readonly store: MarketDataStore;
|
|
readonly barQueries: BarQuery[];
|
|
} {
|
|
const barQueries: BarQuery[] = [];
|
|
const store: MarketDataStore = {
|
|
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
|
|
barQueries.push(q);
|
|
yield {
|
|
listingId: q.listingIds[0] ?? 0,
|
|
timeframe: q.timeframe,
|
|
rows: [...rows],
|
|
};
|
|
},
|
|
async crossSection() {
|
|
throw new MarketDataStoreNotImplementedError('crossSection');
|
|
},
|
|
async fundamentalsAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
|
},
|
|
async events() {
|
|
throw new MarketDataStoreNotImplementedError('events');
|
|
},
|
|
async shortsAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
|
},
|
|
async macroAsOf() {
|
|
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
|
},
|
|
async fx() {
|
|
throw new MarketDataStoreNotImplementedError('fx');
|
|
},
|
|
async universe() {
|
|
return [];
|
|
},
|
|
};
|
|
return { store, barQueries };
|
|
}
|
|
|
|
describe('parseResearchCopilotHostConfig', () => {
|
|
test('parses a complete valid env with optionals and ignores unrelated env keys', () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
|
|
expect(config).toEqual({
|
|
postgresUrl: FAKE_POSTGRES_URL,
|
|
postgresSchema: 'research_ro',
|
|
curatedRoot: '/mnt/data/stockbot/curated',
|
|
vaultCutoffTs: VALID_CUTOFF_MS,
|
|
principalId: VALID_AGENT_PRINCIPAL,
|
|
libraryRoot: '/mnt/data/stockbot/library',
|
|
referenceListingIds: {
|
|
XNYS: [101, 102],
|
|
XTSE: [201],
|
|
},
|
|
earlyCloses: {
|
|
XNYS: {
|
|
'2024-11-29': 780,
|
|
'2024-12-24': 780,
|
|
},
|
|
},
|
|
});
|
|
});
|
|
|
|
test('supports omitted optional variables, operator principal, postgres:// scheme, and millisecond UTC instants', () => {
|
|
const env = buildValidEnv({
|
|
RESEARCH_MCP_POSTGRES_URL: 'postgres://user:pass@localhost:5432/db',
|
|
RESEARCH_MCP_POSTGRES_SCHEMA: undefined,
|
|
RESEARCH_MCP_VAULT_CUTOFF_TS: '2025-06-01T13:30:45.250Z',
|
|
RESEARCH_MCP_PRINCIPAL_ID: 'operator',
|
|
RESEARCH_MCP_EARLY_CLOSES: undefined,
|
|
});
|
|
|
|
const config = parseResearchCopilotHostConfig(env);
|
|
|
|
expect(config.postgresUrl).toBe('postgres://user:pass@localhost:5432/db');
|
|
expect(config.postgresSchema).toBeUndefined();
|
|
expect('postgresSchema' in config).toBe(false);
|
|
expect(config.earlyCloses).toBeUndefined();
|
|
expect('earlyCloses' in config).toBe(false);
|
|
expect(config.principalId).toBe('operator');
|
|
expect(config.vaultCutoffTs).toBe(Date.UTC(2025, 5, 1, 13, 30, 45, 250));
|
|
});
|
|
|
|
test.each([
|
|
'RESEARCH_MCP_POSTGRES_URL',
|
|
'RESEARCH_MCP_CURATED_ROOT',
|
|
'RESEARCH_MCP_VAULT_CUTOFF_TS',
|
|
'RESEARCH_MCP_PRINCIPAL_ID',
|
|
'RESEARCH_MCP_LIBRARY_ROOT',
|
|
'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS',
|
|
] as const)('rejects missing required variable %s', variable => {
|
|
const env = buildValidEnv({ [variable]: undefined });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe(variable);
|
|
expect(err.message).toContain(variable);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
'RESEARCH_MCP_POSTGRES_URL',
|
|
'RESEARCH_MCP_POSTGRES_SCHEMA',
|
|
'RESEARCH_MCP_CURATED_ROOT',
|
|
'RESEARCH_MCP_VAULT_CUTOFF_TS',
|
|
'RESEARCH_MCP_PRINCIPAL_ID',
|
|
'RESEARCH_MCP_LIBRARY_ROOT',
|
|
'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS',
|
|
'RESEARCH_MCP_EARLY_CLOSES',
|
|
] as const)('rejects empty and whitespace-only values for %s', variable => {
|
|
for (const blank of ['', ' \t\n ']) {
|
|
const env = buildValidEnv({ [variable]: blank });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe(variable);
|
|
expect(err.message).toContain(variable);
|
|
assertNoCredentialLeak(err);
|
|
}
|
|
});
|
|
|
|
test.each([
|
|
['unknown prefixed key with value', 'RESEARCH_MCP_EXTRA', 'enabled'],
|
|
['unknown prefixed key with empty string', 'RESEARCH_MCP_UNKNOWN_FLAG', ''],
|
|
] as const)('rejects %s', (_label, key, value) => {
|
|
const env = buildValidEnv({ [key]: value });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe(key);
|
|
expect(err.message).toContain(key);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['non-postgres scheme', `http://user:${FAKE_ENCODED_PASSWORD}@localhost:5432/db`],
|
|
['missing host', `postgresql://user:${FAKE_ENCODED_PASSWORD}@/db`],
|
|
['malformed URL', `not-a-url-${FAKE_DECODED_PASSWORD}`],
|
|
['surrounding whitespace', ` ${FAKE_POSTGRES_URL} `],
|
|
] as const)('rejects invalid POSTGRES_URL (%s) without leaking URL or password', (_label, badUrl) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_URL: badUrl });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_URL');
|
|
expect(err.message).toContain('RESEARCH_MCP_POSTGRES_URL');
|
|
expect(err.message).not.toContain(badUrl);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['uppercase', 'Research_RO'],
|
|
['leading digit', '1schema'],
|
|
['hyphen', 'research-ro'],
|
|
['SQL injection', 'public"; DROP TABLE findings; --'],
|
|
] as const)('rejects invalid POSTGRES_SCHEMA (%s)', (_label, badSchema) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_POSTGRES_SCHEMA: badSchema });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_POSTGRES_SCHEMA');
|
|
expect(err.message).toContain('RESEARCH_MCP_POSTGRES_SCHEMA');
|
|
expect(err.message).not.toContain(badSchema);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['bare uuid', '11111111-2222-4333-8444-555555555555'],
|
|
['uppercase agent uuid', 'agent:11111111-2222-4333-8444-55555555555A'],
|
|
['invalid uuid version 0', 'agent:11111111-2222-0333-8444-555555555555'],
|
|
['invalid uuid version 9', 'agent:11111111-2222-9333-8444-555555555555'],
|
|
['invalid RFC variant', 'agent:11111111-2222-4333-0444-555555555555'],
|
|
['unknown role', 'admin'],
|
|
] as const)('rejects invalid PRINCIPAL_ID (%s)', (_label, badPrincipal) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_PRINCIPAL_ID: badPrincipal });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_PRINCIPAL_ID');
|
|
expect(err.message).toContain('RESEARCH_MCP_PRINCIPAL_ID');
|
|
expect(err.message).not.toContain(badPrincipal);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['date-only string', '2025-06-01'],
|
|
['missing seconds', '2025-06-01T00:00Z'],
|
|
['non-UTC offset +00:00', '2025-06-01T00:00:00+00:00'],
|
|
['non-UTC offset -05:00', '2025-06-01T00:00:00-05:00'],
|
|
['lowercase z', '2025-06-01T00:00:00z'],
|
|
['sub-millisecond precision', '2025-06-01T00:00:00.123456Z'],
|
|
['impossible leap day', '2025-02-29T00:00:00Z'],
|
|
['impossible April 31', '2025-04-31T00:00:00Z'],
|
|
['hour 24', '2025-06-01T24:00:00Z'],
|
|
['second 60', '2025-06-01T00:00:60Z'],
|
|
] as const)('rejects invalid VAULT_CUTOFF_TS (%s)', (_label, badTs) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_VAULT_CUTOFF_TS: badTs });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_VAULT_CUTOFF_TS');
|
|
expect(err.message).toContain('RESEARCH_MCP_VAULT_CUTOFF_TS');
|
|
expect(err.message).not.toContain(badTs);
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['malformed JSON', '{bad-json'],
|
|
['JSON array root', '[101, 102]'],
|
|
['JSON null root', 'null'],
|
|
['scalar listing ID', '{"XNYS": 101}'],
|
|
['empty listing ID array', '{"XNYS": []}'],
|
|
['duplicate listing IDs', '{"XNYS": [101, 101]}'],
|
|
['zero listing ID', '{"XNYS": [0]}'],
|
|
['negative listing ID', '{"XNYS": [-5]}'],
|
|
['float listing ID', '{"XNYS": [10.5]}'],
|
|
['INT32 overflow', '{"XNYS": [2147483648]}'],
|
|
['string listing ID', '{"XNYS": ["101"]}'],
|
|
['untrimmed calendar code', '{" XNYS ": [101]}'],
|
|
['blank calendar code', '{"": [101]}'],
|
|
] as const)('rejects invalid SESSION_REFERENCE_LISTINGS (%s)', (_label, badJson) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: badJson });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS');
|
|
expect(err.message).toContain('RESEARCH_MCP_SESSION_REFERENCE_LISTINGS');
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
|
|
test.each([
|
|
['malformed JSON', '{bad-json'],
|
|
['JSON array root', '[]'],
|
|
['JSON null root', 'null'],
|
|
['non-object calendar entry', '{"XNYS": [780]}'],
|
|
['untrimmed calendar code', '{" XNYS": {"2024-11-29": 780}}'],
|
|
['impossible calendar date', '{"XNYS": {"2024-02-30": 780}}'],
|
|
['date below supported range', '{"XNYS": {"1975-12-31": 780}}'],
|
|
['date above supported range', '{"XNYS": {"2031-01-01": 780}}'],
|
|
['minute 0 (below min 1)', '{"XNYS": {"2024-11-29": 0}}'],
|
|
['negative minute', '{"XNYS": {"2024-11-29": -10}}'],
|
|
['minute 961 (above max 960)', '{"XNYS": {"2024-11-29": 961}}'],
|
|
['fractional minute', '{"XNYS": {"2024-11-29": 780.5}}'],
|
|
['string minute', '{"XNYS": {"2024-11-29": "780"}}'],
|
|
] as const)('rejects invalid EARLY_CLOSES (%s)', (_label, badJson) => {
|
|
const env = buildValidEnv({ RESEARCH_MCP_EARLY_CLOSES: badJson });
|
|
let caught: unknown;
|
|
try {
|
|
parseResearchCopilotHostConfig(env);
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBeInstanceOf(ResearchCopilotHostConfigError);
|
|
const err = caught as ResearchCopilotHostConfigError;
|
|
expect(err.variable).toBe('RESEARCH_MCP_EARLY_CLOSES');
|
|
expect(err.message).toContain('RESEARCH_MCP_EARLY_CLOSES');
|
|
assertNoCredentialLeak(err);
|
|
});
|
|
});
|
|
|
|
describe('runResearchCopilotStdioHost', () => {
|
|
test('serves initialize, tools/list (exact 6 tools in order), and read_knowledge (library) with zero SQL calls', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const fakeExec = createFakeExecutor();
|
|
const fakeStore = createFakeStore();
|
|
const libraryQueries: LibraryCardQuery[] = [];
|
|
const expectedCard: LibraryCardRecord = {
|
|
id: 'card-short-squeeze-01',
|
|
title: 'Canadian Short Interest Spike',
|
|
summary: 'Synthetic fixture card for stdio host wiring verification.',
|
|
body: 'Full body text for the synthetic short interest library card.',
|
|
tags: ['shorts', 'ca'],
|
|
};
|
|
|
|
const sink = createMemoryOutput();
|
|
const { input } = createTrackingInput([
|
|
{
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'initialize',
|
|
params: {
|
|
protocolVersion: '2024-11-05',
|
|
capabilities: {},
|
|
clientInfo: { name: 'test-client', version: '1.0.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: 'read_knowledge',
|
|
arguments: {
|
|
source: 'library',
|
|
query: 'short interest',
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: fakeExec.executor,
|
|
close: async () => {},
|
|
}),
|
|
openStore: async () => ({
|
|
store: fakeStore.store,
|
|
close: async () => {},
|
|
}),
|
|
createLibraryCardReader: async () => ({
|
|
listLibraryCards: async (q: LibraryCardQuery) => {
|
|
libraryQueries.push(q);
|
|
return [expectedCard];
|
|
},
|
|
}),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input, output: sink.output },
|
|
});
|
|
|
|
const responses = sink.jsonLines() as Array<{
|
|
readonly id: number;
|
|
readonly result: Record<string, unknown>;
|
|
}>;
|
|
expect(responses).toHaveLength(3);
|
|
|
|
const initResp = responses[0]!;
|
|
expect(initResp.id).toBe(1);
|
|
expect(initResp.result.serverInfo).toEqual({
|
|
name: RESEARCH_COPILOT_HOST_NAME,
|
|
version: RESEARCH_COPILOT_HOST_VERSION,
|
|
});
|
|
|
|
const listResp = responses[1]!;
|
|
expect(listResp.id).toBe(2);
|
|
const listedTools = listResp.result.tools as Array<{ readonly name: string }>;
|
|
expect(listedTools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
|
|
|
|
const callResp = responses[2]!;
|
|
expect(callResp.id).toBe(3);
|
|
const toolEnvelope = callResp.result as {
|
|
readonly isError?: boolean;
|
|
readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>;
|
|
};
|
|
expect(toolEnvelope.isError).toBeUndefined();
|
|
const payload = JSON.parse(toolEnvelope.content[0]!.text) as ReadKnowledgeResultPayload;
|
|
expect(payload.rows).toHaveLength(1);
|
|
expect(payload.rows[0]?.source).toBe('library');
|
|
expect(payload.rows[0]?.id).toBe(expectedCard.id);
|
|
expect(payload.rows[0]?.source === 'library' ? payload.rows[0].title : undefined).toBe(
|
|
expectedCard.title
|
|
);
|
|
|
|
expect(libraryQueries).toHaveLength(1);
|
|
expect(fakeExec.calls).toHaveLength(0);
|
|
});
|
|
|
|
test('enforces the single RESEARCH_MCP_VAULT_CUTOFF_TS across query_data rejection, clamping, and row defense-in-depth', async () => {
|
|
// Pinned synthetic bar fixture (protocol check only, no strategy or return claim):
|
|
// - Cutoff from env: 2025-06-01T00:00:00Z
|
|
// - Listing 101:
|
|
// 1) Pre-cutoff bar (2025-05-30 20:00Z, knownAt 2025-05-30 20:00Z) -> included
|
|
// 2) Cutoff-ts bar (2025-06-01 00:00Z, knownAt 2025-05-30 20:00Z) -> excluded
|
|
// 3) Post-cutoff knownAt bar (2025-05-29 20:00Z, knownAt 2025-06-01 00:00Z) -> excluded
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const preCutoffBar: BarRecord = {
|
|
listingId: 101,
|
|
ts: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
|
|
open: 10,
|
|
high: 11,
|
|
low: 9.5,
|
|
close: 10.5,
|
|
volume: 10_000,
|
|
vwap: 10.25,
|
|
knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
|
|
};
|
|
const atCutoffTsBar: BarRecord = {
|
|
listingId: 101,
|
|
ts: VALID_CUTOFF_MS,
|
|
open: 10.5,
|
|
high: 11.5,
|
|
low: 10,
|
|
close: 11,
|
|
volume: 12_000,
|
|
vwap: 10.75,
|
|
knownAt: Date.UTC(2025, 4, 30, 20, 0, 0, 0),
|
|
};
|
|
const atCutoffKnownAtBar: BarRecord = {
|
|
listingId: 101,
|
|
ts: Date.UTC(2025, 4, 29, 20, 0, 0, 0),
|
|
open: 9.5,
|
|
high: 10,
|
|
low: 9,
|
|
close: 9.8,
|
|
volume: 8_000,
|
|
vwap: 9.6,
|
|
knownAt: VALID_CUTOFF_MS,
|
|
};
|
|
|
|
const fakeExec = createFakeExecutor();
|
|
const fakeStore = createFakeStore([preCutoffBar, atCutoffTsBar, atCutoffKnownAtBar]);
|
|
let storeFactoryConfig: ResearchCopilotHostConfig | undefined;
|
|
|
|
const sink = createMemoryOutput();
|
|
const { input } = createTrackingInput([
|
|
{
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'query_data',
|
|
arguments: {
|
|
listingIds: [101],
|
|
from: '2025-06-01',
|
|
to: '2025-06-05',
|
|
},
|
|
},
|
|
},
|
|
{
|
|
jsonrpc: '2.0',
|
|
id: 2,
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'query_data',
|
|
arguments: {
|
|
listingIds: [101],
|
|
from: '2025-05-29',
|
|
to: '2025-06-05',
|
|
asOf: '2025-06-05',
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: fakeExec.executor,
|
|
close: async () => {},
|
|
}),
|
|
openStore: async cfg => {
|
|
storeFactoryConfig = cfg;
|
|
return {
|
|
store: fakeStore.store,
|
|
close: async () => {},
|
|
};
|
|
},
|
|
createLibraryCardReader: async () => ({
|
|
listLibraryCards: async () => [],
|
|
}),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input, output: sink.output },
|
|
});
|
|
|
|
expect(storeFactoryConfig).toBe(config);
|
|
expect(storeFactoryConfig?.vaultCutoffTs).toBe(VALID_CUTOFF_MS);
|
|
|
|
const responses = sink.jsonLines() as Array<{
|
|
readonly id: number;
|
|
readonly result: {
|
|
readonly isError?: boolean;
|
|
readonly content: ReadonlyArray<{ readonly type: 'text'; readonly text: string }>;
|
|
};
|
|
}>;
|
|
expect(responses).toHaveLength(2);
|
|
|
|
// Call 1: at/beyond cutoff -> VaultHoldoutFenceError with zero store calls.
|
|
expect(responses[0]?.result.isError).toBe(true);
|
|
expect(responses[0]?.result.content[0]?.text).toContain('VaultHoldoutFenceError');
|
|
|
|
// Call 2: straddling range -> clamped strictly below cutoff and post-cutoff rows dropped.
|
|
expect(fakeStore.barQueries).toHaveLength(1);
|
|
const barQuery = fakeStore.barQueries[0]!;
|
|
expect(barQuery.scope).toBe('vault_fenced');
|
|
expect(barQuery.to).toBe('2025-05-31T23:59:59.999999Z');
|
|
expect(barQuery.asOf).toBe('2025-05-31T23:59:59.999999Z');
|
|
|
|
expect(responses[1]?.result.isError).toBeUndefined();
|
|
const payload = JSON.parse(responses[1]!.result.content[0]!.text) as QueryDataResultPayload;
|
|
expect(payload.vaultCutoffTs).toBe(VALID_CUTOFF_MS);
|
|
expect(payload.toMs).toBe(VALID_CUTOFF_MS - 1);
|
|
expect(payload.asOfMs).toBe(VALID_CUTOFF_MS - 1);
|
|
expect(payload.clampedTo).toBe(true);
|
|
expect(payload.clampedAsOf).toBe(true);
|
|
expect(payload.rows).toEqual([preCutoffBar]);
|
|
});
|
|
|
|
test('closes acquired resources exactly once in reverse order on normal EOF', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const fakeExec = createFakeExecutor();
|
|
const fakeStore = createFakeStore();
|
|
const events: string[] = [];
|
|
let execCloses = 0;
|
|
let storeCloses = 0;
|
|
|
|
const sink = createMemoryOutput();
|
|
const { input } = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
|
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => {
|
|
events.push('open:executor');
|
|
return {
|
|
executor: fakeExec.executor,
|
|
close: async () => {
|
|
execCloses += 1;
|
|
events.push('close:executor');
|
|
},
|
|
};
|
|
},
|
|
openStore: async () => {
|
|
events.push('open:store');
|
|
return {
|
|
store: fakeStore.store,
|
|
close: async () => {
|
|
storeCloses += 1;
|
|
events.push('close:store');
|
|
},
|
|
};
|
|
},
|
|
createLibraryCardReader: async () => {
|
|
events.push('open:library');
|
|
return {
|
|
listLibraryCards: async () => [],
|
|
};
|
|
},
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input, output: sink.output },
|
|
});
|
|
|
|
expect(events).toEqual([
|
|
'open:executor',
|
|
'open:store',
|
|
'open:library',
|
|
'close:store',
|
|
'close:executor',
|
|
]);
|
|
expect(storeCloses).toBe(1);
|
|
expect(execCloses).toBe(1);
|
|
expect(sink.jsonLines()).toHaveLength(1);
|
|
});
|
|
|
|
test('fails closed when openExecutor rejects with zero downstream calls, zero stdout, and zero input consumed', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const safeError = new Error('PostgreSQL host unreachable');
|
|
let storeCalled = false;
|
|
let libraryCalled = false;
|
|
|
|
const sink = createMemoryOutput();
|
|
const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => {
|
|
throw safeError;
|
|
},
|
|
openStore: async () => {
|
|
storeCalled = true;
|
|
return { store: createFakeStore().store, close: async () => {} };
|
|
},
|
|
createLibraryCardReader: async () => {
|
|
libraryCalled = true;
|
|
return { listLibraryCards: async () => [] };
|
|
},
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: tracker.input, output: sink.output },
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBe(safeError);
|
|
expect(storeCalled).toBe(false);
|
|
expect(libraryCalled).toBe(false);
|
|
expect(sink.text()).toBe('');
|
|
expect(tracker.getPulledCount()).toBe(0);
|
|
});
|
|
|
|
test('closes executor and preserves original error when openStore throws, even if executor.close throws', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const storeError = new Error('DuckDB catalog open failed');
|
|
let execCloses = 0;
|
|
let libraryCalled = false;
|
|
|
|
const sink = createMemoryOutput();
|
|
const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
execCloses += 1;
|
|
throw new Error('secondary executor close failure');
|
|
},
|
|
}),
|
|
openStore: async () => {
|
|
throw storeError;
|
|
},
|
|
createLibraryCardReader: async () => {
|
|
libraryCalled = true;
|
|
return { listLibraryCards: async () => [] };
|
|
},
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: tracker.input, output: sink.output },
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBe(storeError);
|
|
expect(execCloses).toBe(1);
|
|
expect(libraryCalled).toBe(false);
|
|
expect(sink.text()).toBe('');
|
|
expect(tracker.getPulledCount()).toBe(0);
|
|
});
|
|
|
|
test('closes store then executor and preserves original error when createLibraryCardReader throws, even if both closes throw', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const libraryError = new Error('library.yml unreadable');
|
|
const closeOrder: string[] = [];
|
|
|
|
const sink = createMemoryOutput();
|
|
const tracker = createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]);
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
closeOrder.push('executor');
|
|
throw new Error('executor close failed');
|
|
},
|
|
}),
|
|
openStore: async () => ({
|
|
store: createFakeStore().store,
|
|
close: async () => {
|
|
closeOrder.push('store');
|
|
throw new Error('store close failed');
|
|
},
|
|
}),
|
|
createLibraryCardReader: async () => {
|
|
throw libraryError;
|
|
},
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: tracker.input, output: sink.output },
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(caught).toBe(libraryError);
|
|
expect(closeOrder).toEqual(['store', 'executor']);
|
|
expect(sink.text()).toBe('');
|
|
expect(tracker.getPulledCount()).toBe(0);
|
|
});
|
|
|
|
test('closes both resources in reverse order and preserves transport error when stdio input or output throws', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
|
|
// Case 1: throwing input stream
|
|
const inputError = new Error('stdin read reset');
|
|
const inputCloseOrder: string[] = [];
|
|
const failingInput: StdioInput = {
|
|
async *[Symbol.asyncIterator]() {
|
|
yield `${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'ping' })}\n`;
|
|
throw inputError;
|
|
},
|
|
};
|
|
|
|
let caughtInput: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
inputCloseOrder.push('executor');
|
|
},
|
|
}),
|
|
openStore: async () => ({
|
|
store: createFakeStore().store,
|
|
close: async () => {
|
|
inputCloseOrder.push('store');
|
|
throw new Error('close error masked by primary');
|
|
},
|
|
}),
|
|
createLibraryCardReader: async () => ({
|
|
listLibraryCards: async () => [],
|
|
}),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: failingInput, output: createMemoryOutput().output },
|
|
});
|
|
} catch (err) {
|
|
caughtInput = err;
|
|
}
|
|
expect(caughtInput).toBe(inputError);
|
|
expect(inputCloseOrder).toEqual(['store', 'executor']);
|
|
|
|
// Case 2: throwing output stream
|
|
const outputError = new Error('stdout broken pipe');
|
|
const outputCloseOrder: string[] = [];
|
|
const failingOutput: StdioOutput = {
|
|
write() {
|
|
throw outputError;
|
|
},
|
|
};
|
|
|
|
let caughtOutput: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
outputCloseOrder.push('executor');
|
|
},
|
|
}),
|
|
openStore: async () => ({
|
|
store: createFakeStore().store,
|
|
close: async () => {
|
|
outputCloseOrder.push('store');
|
|
},
|
|
}),
|
|
createLibraryCardReader: async () => ({
|
|
listLibraryCards: async () => [],
|
|
}),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: {
|
|
input: createTrackingInput([{ jsonrpc: '2.0', id: 1, method: 'ping' }]).input,
|
|
output: failingOutput,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
caughtOutput = err;
|
|
}
|
|
expect(caughtOutput).toBe(outputError);
|
|
expect(outputCloseOrder).toEqual(['store', 'executor']);
|
|
});
|
|
|
|
test('attempts both closes after EOF and reports the first close failure when both fail', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
const storeCloseError = new Error('store flush failed');
|
|
const execCloseError = new Error('pool drain failed');
|
|
const closeOrder: string[] = [];
|
|
|
|
let caught: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
closeOrder.push('executor');
|
|
throw execCloseError;
|
|
},
|
|
}),
|
|
openStore: async () => ({
|
|
store: createFakeStore().store,
|
|
close: async () => {
|
|
closeOrder.push('store');
|
|
throw storeCloseError;
|
|
},
|
|
}),
|
|
createLibraryCardReader: async () => ({
|
|
listLibraryCards: async () => [],
|
|
}),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: {
|
|
input: createTrackingInput([]).input,
|
|
output: createMemoryOutput().output,
|
|
},
|
|
});
|
|
} catch (err) {
|
|
caught = err;
|
|
}
|
|
|
|
expect(closeOrder).toEqual(['store', 'executor']);
|
|
expect(caught).toBe(storeCloseError);
|
|
});
|
|
|
|
test('replaces startup and cleanup errors containing the full URL, decoded password, or uninspectable values with fixed stage errors and no cause', async () => {
|
|
const config = parseResearchCopilotHostConfig(buildValidEnv());
|
|
|
|
// 1. Startup error containing full DSN
|
|
let caughtDsn: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => {
|
|
throw new Error(`connect failed for ${FAKE_POSTGRES_URL}`);
|
|
},
|
|
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
|
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
|
});
|
|
} catch (err) {
|
|
caughtDsn = err;
|
|
}
|
|
assertNoCredentialLeak(caughtDsn);
|
|
expect((caughtDsn as Error & { cause?: unknown }).cause).toBeUndefined();
|
|
expect((caughtDsn as Error).message).toContain('executor');
|
|
|
|
// 2. Startup error containing decoded password by itself
|
|
let caughtPass: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {},
|
|
}),
|
|
openStore: async () => {
|
|
throw new Error(`auth rejected password "${FAKE_DECODED_PASSWORD}"`);
|
|
},
|
|
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
|
});
|
|
} catch (err) {
|
|
caughtPass = err;
|
|
}
|
|
assertNoCredentialLeak(caughtPass);
|
|
expect((caughtPass as Error & { cause?: unknown }).cause).toBeUndefined();
|
|
expect((caughtPass as Error).message).toContain('market data store');
|
|
|
|
// 3. Cleanup error containing decoded password after EOF
|
|
let caughtClose: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => ({
|
|
executor: createFakeExecutor().executor,
|
|
close: async () => {
|
|
throw new Error(`disconnect error for ${FAKE_DECODED_PASSWORD}`);
|
|
},
|
|
}),
|
|
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
|
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
|
});
|
|
} catch (err) {
|
|
caughtClose = err;
|
|
}
|
|
assertNoCredentialLeak(caughtClose);
|
|
expect((caughtClose as Error & { cause?: unknown }).cause).toBeUndefined();
|
|
expect((caughtClose as Error).message).toContain('closing host resources');
|
|
|
|
// 4. Uninspectable non-Error rejection containing raw secret
|
|
let caughtRaw: unknown;
|
|
try {
|
|
await runResearchCopilotStdioHost({
|
|
config,
|
|
openExecutor: async () => {
|
|
throw `raw-string-${FAKE_DECODED_PASSWORD}`;
|
|
},
|
|
openStore: async () => ({ store: createFakeStore().store, close: async () => {} }),
|
|
createLibraryCardReader: async () => ({ listLibraryCards: async () => [] }),
|
|
newId: () => 'id-1',
|
|
now: () => FIXED_NOW_MS,
|
|
stdio: { input: createTrackingInput([]).input, output: createMemoryOutput().output },
|
|
});
|
|
} catch (err) {
|
|
caughtRaw = err;
|
|
}
|
|
assertNoCredentialLeak(caughtRaw);
|
|
expect((caughtRaw as Error & { cause?: unknown }).cause).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe('stdio-host dependency-free source invariants', () => {
|
|
test('contains no bare process access and no pg, node:*, or DuckDB imports', () => {
|
|
const src = readFileSync(new URL('../src/mcp/host/stdio-host.ts', import.meta.url), 'utf8');
|
|
expect(src).not.toMatch(/\bprocess\./);
|
|
expect(src).not.toMatch(/from\s+['"]node:/);
|
|
expect(src).not.toMatch(/require\s*\(\s*['"]node:/);
|
|
expect(src).not.toMatch(/from\s+['"]pg(?:\/|['"])/);
|
|
expect(src).not.toMatch(/require\s*\(\s*['"]pg(?:\/|['"])/);
|
|
expect(src).not.toMatch(/from\s+['"][^'"]*duckdb/i);
|
|
expect(src).not.toMatch(/require\s*\(\s*['"][^'"]*duckdb/i);
|
|
});
|
|
});
|