stock-bot/libs/research/test/mcp-read-knowledge-qa.test.ts
2026-12-01 07:22:36 -05:00

581 lines
21 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import {
createMcpServer,
createReadKnowledgeTool,
type FindingQuery,
type FindingRecord,
type KnowledgePort,
type LibraryCardQuery,
type LibraryCardRecord,
type ProviderCaveatQuery,
type ProviderCaveatRecord,
READ_KNOWLEDGE_MAX_LIMIT,
READ_KNOWLEDGE_MAX_QUERY_LENGTH,
READ_KNOWLEDGE_MAX_TEXT_LENGTH,
type ReadKnowledgeResultPayload,
} from '../src/mcp/index';
// QA fixtures: deterministic in-memory KnowledgePort (no network, no Postgres,
// no filesystem). All timestamps are pinned ISO strings; shuffles use a seeded PRNG.
const SECRET = 'postgres://admin:super-secret@10.0.0.51:5432/trading_bot';
function card(id: string, o: Partial<LibraryCardRecord> = {}): LibraryCardRecord {
return {
id,
title: o.title ?? `Card ${id}`,
tags: o.tags ?? ['methodology'],
summary: o.summary ?? `Summary ${id}`,
body: o.body ?? `Body ${id}`,
};
}
function finding(id: string, o: Partial<FindingRecord> = {}): FindingRecord {
return {
id,
title: o.title ?? `Finding ${id}`,
status: o.status ?? 'confirmed',
createdAt: o.createdAt ?? '2025-01-15T12:00:00.000Z',
summary: o.summary ?? `Finding summary ${id}`,
trialRefs: o.trialRefs ?? [`trial-${id}`],
evidenceRefs: o.evidenceRefs ?? [`ev-${id}`],
};
}
function caveat(id: string, o: Partial<ProviderCaveatRecord> = {}): ProviderCaveatRecord {
return {
id,
provider: o.provider ?? 'eodhd',
dataset: o.dataset ?? `dataset_${id}`,
caveat: o.caveat ?? `Caveat ${id}`,
createdAt: o.createdAt ?? '2025-01-20T08:30:00.000Z',
};
}
interface PortImpl {
readonly library?: (q: LibraryCardQuery) => unknown;
readonly findings?: (q: FindingQuery) => unknown;
readonly caveats?: (q: ProviderCaveatQuery) => unknown;
}
function makePort(impl: PortImpl): { port: KnowledgePort; calls: string[] } {
const calls: string[] = [];
const port: KnowledgePort = {
listLibraryCards(q) {
calls.push('listLibraryCards');
return (impl.library ?? (() => Promise.resolve([])))(q) as Promise<
readonly LibraryCardRecord[]
>;
},
listFindings(q) {
calls.push('listFindings');
return (impl.findings ?? (() => Promise.resolve([])))(q) as Promise<
readonly FindingRecord[]
>;
},
listProviderCaveats(q) {
calls.push('listProviderCaveats');
return (impl.caveats ?? (() => Promise.resolve([])))(q) as Promise<
readonly ProviderCaveatRecord[]
>;
},
};
return { port, calls };
}
function staticPort(
library: readonly LibraryCardRecord[],
findings: readonly FindingRecord[],
caveats: readonly ProviderCaveatRecord[]
): { port: KnowledgePort; calls: string[] } {
return makePort({
library: async () => library,
findings: async () => findings,
caveats: async () => caveats,
});
}
async function call(
port: KnowledgePort,
args: Record<string, unknown> | undefined
): Promise<{ isError: boolean; text: string; payload: ReadKnowledgeResultPayload | null }> {
const server = createMcpServer({
name: 'stock-bot-research',
version: '0.1.0',
tools: [createReadKnowledgeTool({ port })],
});
const params: Record<string, unknown> = { name: 'read_knowledge' };
if (args !== undefined) {
params.arguments = args;
}
const raw = await server.handleMessage(
JSON.stringify({ jsonrpc: '2.0', id: 'qa', method: 'tools/call', params })
);
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw as string) as {
result: { isError?: boolean; content: { type: string; text: string }[] };
};
const isError = parsed.result.isError === true;
const text = parsed.result.content[0]?.text ?? '';
return { isError, text, payload: isError ? null : (JSON.parse(text) as ReadKnowledgeResultPayload) };
}
function expectSanitized(res: { isError: boolean; text: string }): void {
expect(res.isError).toBe(true);
expect(res.text).toMatch(/^[A-Za-z][A-Za-z0-9_]*: Tool execution failed\.$/);
for (const leak of ['super-secret', '10.0.0.51', 'trading_bot', 'postgres://', 'db.ts', ' at ']) {
expect(res.text).not.toContain(leak);
}
}
function deepFreeze<T>(value: T): T {
if (typeof value === 'object' && value !== null) {
for (const v of Object.values(value)) {
deepFreeze(v);
}
Object.freeze(value);
}
return value;
}
// mulberry32 — seeded PRNG for reproducible shuffles.
function seededShuffle<T>(items: readonly T[], seed: number): T[] {
let s = seed >>> 0;
const rand = (): number => {
s = (s + 0x6d2b79f5) >>> 0;
let t = s;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const out = [...items];
for (let i = out.length - 1; i > 0; i -= 1) {
const j = Math.floor(rand() * (i + 1));
[out[i], out[j]] = [out[j] as T, out[i] as T];
}
return out;
}
describe('read_knowledge QA: port failures and malformed port output', () => {
test('non-Error rejections and synchronous throws carrying connection strings are sanitized', async () => {
const cases: PortImpl[] = [
{ library: () => Promise.reject(SECRET) },
{ findings: () => Promise.reject({ message: SECRET, stack: 'at /srv/db.ts:1' }) },
{
caveats: () => {
throw new Error(SECRET);
},
},
{
library: () => {
const err = new Error(SECRET);
err.name = SECRET;
throw err;
},
},
];
for (const impl of cases) {
const { port } = makePort(impl);
const res = await call(port, { query: 'alpha' });
expectSanitized(res);
}
});
test('malformed port responses map to a sanitized isError without echoing record contents', async () => {
const badResponses: PortImpl[] = [
{ library: async () => SECRET },
{ library: async () => undefined },
{ library: async () => [null] },
{ library: async () => [{ ...card('c1'), id: 42 }] },
{ library: async () => [{ ...card('c1'), tags: [SECRET, 7] }] },
{ library: async () => [{ ...card('c1'), tags: SECRET }] },
{ findings: async () => [{ ...finding('f1'), trialRefs: undefined }] },
{ findings: async () => [{ ...finding('f1'), createdAt: 1_700_000_000_000 }] },
{ caveats: async () => [{ ...caveat('v1'), caveat: { text: SECRET } }] },
{ caveats: async () => ({ rows: [caveat('v1')] }) },
];
for (const impl of badResponses) {
const { port } = makePort(impl);
const res = await call(port, {});
expectSanitized(res);
}
});
// Regression: port calls were started eagerly inside the Promise.all array literal, so a
// synchronous throw from a later source abandoned an earlier source's rejected promise.
// Bun treats that unhandled rejection as fatal: the MCP stdio process exits 1 after replying
// and prints the raw error (including any connection string) to stderr. Bun's test runner
// also reports it as an error between tests, so the scenario runs in a child process.
test('earlier async rejection combined with a later synchronous throw does not crash the process', () => {
const indexPath = new URL('../src/mcp/index.ts', import.meta.url).pathname;
const script = `
import { createMcpServer, createReadKnowledgeTool } from ${JSON.stringify(indexPath)};
const secret = ${JSON.stringify(SECRET)};
const combos = [
{ listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: () => { throw new Error('sync'); }, listProviderCaveats: async () => [] },
{ listLibraryCards: () => Promise.reject(new Error(secret)), listFindings: async () => [], listProviderCaveats: () => { throw new Error('sync'); } },
{ listLibraryCards: async () => [], listFindings: () => Promise.reject(new Error(secret)), listProviderCaveats: () => { throw new Error('sync'); } },
];
for (const port of combos) {
const server = createMcpServer({ name: 'qa', version: '0.0.0', tools: [createReadKnowledgeTool({ port })] });
const raw = await server.handleMessage(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'read_knowledge', arguments: {} } }));
console.log(JSON.parse(raw).result.content[0].text);
}
await new Promise(resolve => setTimeout(resolve, 20));
console.log('DONE');
`;
const proc = Bun.spawnSync([process.execPath, '-e', script], {
stdout: 'pipe',
stderr: 'pipe',
timeout: 30_000,
});
const stdout = proc.stdout.toString();
const stderr = proc.stderr.toString();
expect(stdout.trim().split('\n')).toEqual([
'Error: Tool execution failed.',
'Error: Tool execution failed.',
'Error: Tool execution failed.',
'DONE',
]);
expect(stderr).not.toContain('super-secret');
expect(proc.exitCode).toBe(0);
});
});
describe('read_knowledge QA: read-only port usage', () => {
test('never calls write-like methods present on the injected object and calls each read method at most once', async () => {
const writes: string[] = [];
const base = staticPort([card('c1')], [finding('f1')], [caveat('v1')]);
const port = Object.assign(base.port, {
fileFinding: () => writes.push('fileFinding'),
upsertCard: () => writes.push('upsertCard'),
deleteCaveat: () => writes.push('deleteCaveat'),
});
for (const args of [{}, { source: 'library' }, { id: 'f1' }, { query: 'card', limit: 1 }]) {
base.calls.length = 0;
const res = await call(port, args);
expect(res.isError).toBe(false);
expect(new Set(base.calls).size).toBe(base.calls.length);
}
expect(writes).toEqual([]);
});
test('does not mutate deeply frozen port records and returns copies of array fields', async () => {
const lib = deepFreeze([card('c1', { tags: ['Alpha', 'beta'], body: 'b'.repeat(5000) })]);
const fin = deepFreeze([finding('f1', { title: 'Alpha finding' })]);
const cav = deepFreeze([caveat('v1', { dataset: 'alpha_ds', caveat: 'c'.repeat(5000) })]);
const snapshot = JSON.stringify([lib, fin, cav]);
const { port } = staticPort(lib, fin, cav);
const res = await call(port, { query: 'alpha', tags: ['ALPHA'] });
expect(res.isError).toBe(false);
expect(res.payload?.rowCount).toBe(3);
expect(JSON.stringify([lib, fin, cav])).toBe(snapshot);
});
test('omitted tools/call arguments use defaults and call all three sources with an empty selector', async () => {
const seen: unknown[] = [];
const { port, calls } = makePort({
library: async q => {
seen.push(q);
return [card('c1')];
},
findings: async q => {
seen.push(q);
return [finding('f1')];
},
caveats: async q => {
seen.push(q);
return [caveat('v1')];
},
});
const res = await call(port, undefined);
expect(res.isError).toBe(false);
expect(calls.sort()).toEqual(['listFindings', 'listLibraryCards', 'listProviderCaveats']);
expect(seen).toEqual([{}, {}, {}]);
expect(res.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 1 });
});
});
describe('read_knowledge QA: input boundaries', () => {
test('accepts query at exactly the cap, including when surrounding whitespace is trimmed', async () => {
const atCap = 'q'.repeat(READ_KNOWLEDGE_MAX_QUERY_LENGTH);
const seen: (string | undefined)[] = [];
const { port } = makePort({
library: async q => {
seen.push(q.query);
return [card('c1', { title: `x${atCap}x` })];
},
});
for (const query of [atCap, ` ${atCap}\t\n `]) {
const res = await call(port, { source: 'library', query });
expect(res.isError).toBe(false);
expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']);
}
expect(seen).toEqual([atCap, atCap]);
});
test('accepts limit 1 and limit max as boundary values', async () => {
const lib = Array.from({ length: READ_KNOWLEDGE_MAX_LIMIT + 5 }, (_, i) =>
card(`c${String(i).padStart(3, '0')}`)
);
const { port } = staticPort(lib, [], []);
const one = await call(port, { limit: 1 });
const max = await call(port, { limit: READ_KNOWLEDGE_MAX_LIMIT });
expect(one.payload?.rows.map(r => r.id)).toEqual(['c000']);
expect(max.payload?.rowCount).toBe(READ_KNOWLEDGE_MAX_LIMIT);
expect(max.payload?.rows.at(-1)?.id).toBe('c099');
});
test('rejects null-valued optional selectors and non-array tags before calling the port', async () => {
for (const args of [
{ query: null },
{ id: null },
{ tags: 'alpha' },
{ tags: [1] },
{ provider: ['eodhd'] },
{ source: null },
{ limit: null },
{ limit: Number.POSITIVE_INFINITY },
]) {
const { port, calls } = staticPort([card('c1')], [], []);
const res = await call(port, args);
expect(res.isError).toBe(true);
expect(res.text).toContain('Invalid arguments for tool "read_knowledge"');
expect(calls).toEqual([]);
}
});
});
describe('read_knowledge QA: matching semantics', () => {
test('free-text query does not match on id, status, createdAt, or trial/evidence refs alone', async () => {
const { port } = staticPort(
[card('zeta-card', { title: 'A', tags: ['b'], summary: 'c', body: 'zeta in body only' })],
[
finding('zeta-finding', {
title: 'A',
summary: 'c',
status: 'zeta',
createdAt: 'zeta',
trialRefs: ['zeta'],
evidenceRefs: ['zeta'],
}),
],
[caveat('zeta-caveat', { provider: 'p', dataset: 'd', caveat: 'c', createdAt: 'zeta' })]
);
const res = await call(port, { query: 'zeta' });
expect(res.payload).toEqual({
rowCount: 0,
sources: { library: 0, findings: 0, provider_caveats: 0 },
rows: [],
});
});
test('provider filter is exact (not substring) and tags filter requires whole-tag equality', async () => {
const { port } = staticPort(
[card('c-full', { tags: ['momentum'] }), card('c-partial', { tags: ['momentum-crash'] })],
[],
[caveat('v-eodhd', { provider: 'eodhd' }), caveat('v-eod', { provider: 'eod' })]
);
const byProvider = await call(port, { source: 'provider_caveats', provider: 'EOD' });
const byTag = await call(port, { source: 'library', tags: ['Momentum'] });
expect(byProvider.payload?.rows.map(r => r.id)).toEqual(['v-eod']);
expect(byTag.payload?.rows.map(r => r.id)).toEqual(['c-full']);
});
test('provider matched in free text ranks below a dataset match for caveats', async () => {
const { port } = staticPort(
[],
[],
[
caveat('a-provider', { provider: 'quantmedia', dataset: 'bars', caveat: 'x' }),
caveat('z-dataset', { provider: 'eodhd', dataset: 'quantmedia_filings', caveat: 'x' }),
]
);
const res = await call(port, { query: 'QuantMedia' });
expect(res.payload?.rows.map(r => r.id)).toEqual(['z-dataset', 'a-provider']);
});
test('id lookup still honours source-specific filters: tag mismatch drops the card but keeps other sources under all', async () => {
const { port } = staticPort(
[card('shared', { tags: ['risk'] })],
[finding('shared')],
[caveat('shared', { provider: 'polygon' })]
);
const res = await call(port, { id: 'shared', tags: ['momentum'], provider: 'eodhd' });
expect(res.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual(['findings:shared']);
expect(res.payload?.sources).toEqual({ library: 0, findings: 1, provider_caveats: 0 });
});
test('regex and wildcard metacharacters in query are matched literally', async () => {
const { port } = staticPort(
[card('c-literal', { title: 'Sharpe (annualised) * sqrt(252)' }), card('c-plain', { title: 'Sharpe annualised' })],
[finding('f-dot', { summary: 'a.b' }), finding('f-any', { summary: 'axb' })],
[caveat('v-pct', { caveat: '100% adjusted' }), caveat('v-none', { caveat: '100 adjusted' })]
);
const paren = await call(port, { query: '(annualised) *' });
const dot = await call(port, { query: 'a.b' });
const pct = await call(port, { query: '100%' });
expect(paren.payload?.rows.map(r => r.id)).toEqual(['c-literal']);
expect(dot.payload?.rows.map(r => r.id)).toEqual(['f-dot']);
expect(pct.payload?.rows.map(r => r.id)).toEqual(['v-pct']);
});
test('case-insensitive matching handles non-ASCII text', async () => {
const { port } = staticPort(
[card('c1', { title: 'Étude des rendements' })],
[finding('f1', { summary: 'ÜBERRENDITE nach Ankündigung' })],
[]
);
const res = await call(port, { query: 'étude' });
const res2 = await call(port, { query: 'überrendite' });
expect(res.payload?.rows.map(r => r.id)).toEqual(['c1']);
expect(res2.payload?.rows.map(r => r.id)).toEqual(['f1']);
});
test('projects exactly the documented fields for findings and caveats, dropping extra port fields', async () => {
const extraFinding = { ...finding('f1'), holdoutPnl: 123, dsn: SECRET } as FindingRecord;
const extraCaveat = { ...caveat('v1'), internalNote: SECRET } as ProviderCaveatRecord;
const { port } = staticPort([], [extraFinding], [extraCaveat]);
const res = await call(port, {});
expect(res.text).not.toContain('super-secret');
expect(res.text).not.toContain('holdoutPnl');
expect(res.payload?.rows).toEqual([
{
source: 'findings',
id: 'f1',
title: 'Finding f1',
status: 'confirmed',
createdAt: '2025-01-15T12:00:00.000Z',
summary: 'Finding summary f1',
trialRefs: ['trial-f1'],
evidenceRefs: ['ev-f1'],
truncated: false,
},
{
source: 'provider_caveats',
id: 'v1',
provider: 'eodhd',
dataset: 'dataset_v1',
caveat: 'Caveat v1',
createdAt: '2025-01-20T08:30:00.000Z',
truncated: false,
},
]);
});
});
describe('read_knowledge QA: deterministic ranking and limit', () => {
test('seeded permutations of a mixed fixture replay to identical rows and counts at every limit', async () => {
const lib = [
card('m-title', { title: 'Drift study', summary: 's' }),
card('a-tag', { title: 'x', tags: ['drift'] }),
card('Q-sum', { title: 'x', summary: 'post drift' }),
card('shared', { title: 'Drift shared', summary: 's' }),
];
const fin = [
finding('shared', { title: 'Drift finding' }),
finding('b-sum', { title: 'x', summary: 'DRIFT' }),
finding('k-none', { title: 'x', summary: 'nothing' }),
];
const cav = [
caveat('shared', { dataset: 'drift_ds' }),
caveat('c-cav', { dataset: 'bars', caveat: 'drift noted' }),
];
for (const limit of [1, 2, 3, 5, 8, 20]) {
let baseline: ReadKnowledgeResultPayload | null = null;
for (let seed = 1; seed <= 12; seed += 1) {
const { port } = staticPort(
seededShuffle(lib, seed),
seededShuffle(fin, seed * 7),
seededShuffle(cav, seed * 13)
);
const res = await call(port, { query: 'drift', limit });
expect(res.isError).toBe(false);
if (baseline === null) {
baseline = res.payload;
} else {
expect(res.payload).toEqual(baseline);
}
}
const expectedOrder = [
'library:m-title',
'library:shared',
'findings:shared',
'provider_caveats:shared',
'library:Q-sum',
'library:a-tag',
'findings:b-sum',
'provider_caveats:c-cav',
].slice(0, limit);
expect(baseline?.rows.map(r => `${r.source}:${r.id}`)).toEqual(expectedOrder);
const counts = { library: 0, findings: 0, provider_caveats: 0 };
for (const r of baseline?.rows ?? []) {
counts[r.source] += 1;
}
expect(baseline?.sources).toEqual(counts);
expect(baseline?.rowCount).toBe(expectedOrder.length);
}
});
test('truncation flag reflects only text fields over the cap; title, tags and refs are never truncated', async () => {
const longTitle = 'T'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 10);
const { port } = staticPort(
[card('c1', { title: longTitle, tags: ['t'.repeat(READ_KNOWLEDGE_MAX_TEXT_LENGTH + 1)] })],
[finding('f1', { title: longTitle })],
[]
);
const res = await call(port, {});
for (const row of res.payload?.rows ?? []) {
expect(row.truncated).toBe(false);
if (row.source !== 'provider_caveats') {
expect(row.title).toHaveLength(longTitle.length);
}
}
});
});
describe('read_knowledge QA: limit cutting through a cross-source tie', () => {
test('limit inside a same-id tie keeps library > findings > provider_caveats and counts only returned rows', async () => {
const { port } = staticPort(
[card('dup', { title: 'Basis risk' })],
[finding('dup', { title: 'Basis risk' })],
[caveat('dup', { dataset: 'basis_ds' })]
);
const two = await call(port, { query: 'basis', limit: 2 });
expect(two.payload?.rows.map(r => `${r.source}:${r.id}`)).toEqual([
'library:dup',
'findings:dup',
]);
expect(two.payload?.sources).toEqual({ library: 1, findings: 1, provider_caveats: 0 });
expect(two.payload?.rowCount).toBe(2);
});
});