482 lines
15 KiB
TypeScript
482 lines
15 KiB
TypeScript
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);
|
|
});
|
|
});
|