711 lines
23 KiB
TypeScript
711 lines
23 KiB
TypeScript
import { describe, expect, test } from 'bun:test';
|
|
import {
|
|
type MarketDataStore,
|
|
MarketDataStoreValidationError,
|
|
} from '../src/market-data-store';
|
|
import { MarketDataStoreNotImplementedError } from '../src/market-data-store-duckdb';
|
|
import {
|
|
SEARCH_SYMBOLS_DEFAULT_LIMIT,
|
|
SEARCH_SYMBOLS_MAX_LIMIT,
|
|
SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
|
|
type SearchSymbolsResultPayload,
|
|
type SymbolSearchPort,
|
|
type SymbolSearchQuery,
|
|
type SymbolSearchRow,
|
|
createAnalyzeSignalTool,
|
|
createEventStudyTool,
|
|
createMcpServer,
|
|
createQueryDataTool,
|
|
createSearchSymbolsTool,
|
|
} from '../src/mcp/index';
|
|
import type { TrialLedgerExecutor } from '../src/trial-ledger';
|
|
|
|
const VAULT_CUTOFF_TS = Date.UTC(2025, 2, 31, 0, 0, 0, 0); // 2025-03-31T00:00:00.000Z
|
|
const VAULT_CUTOFF_DATE = '2025-03-31';
|
|
|
|
interface FixtureRow extends SymbolSearchRow {
|
|
readonly country?: 'US' | 'CA';
|
|
}
|
|
|
|
function makeRow(overrides: Partial<FixtureRow> & { readonly listingId: number }): SymbolSearchRow {
|
|
return {
|
|
listingId: overrides.listingId,
|
|
instrumentId: overrides.instrumentId ?? overrides.listingId * 10,
|
|
ticker: overrides.ticker ?? `T${overrides.listingId}`,
|
|
classSuffix: overrides.classSuffix ?? null,
|
|
name: overrides.name ?? `Company ${overrides.listingId}`,
|
|
mic: overrides.mic ?? 'XNAS',
|
|
currency: overrides.currency ?? 'USD',
|
|
isin: overrides.isin ?? null,
|
|
firstBarDate: overrides.firstBarDate === undefined ? '2020-01-02' : overrides.firstBarDate,
|
|
lastBarDate: overrides.lastBarDate === undefined ? '2025-03-28' : overrides.lastBarDate,
|
|
delistedAt: overrides.delistedAt === undefined ? null : overrides.delistedAt,
|
|
};
|
|
}
|
|
|
|
interface FakePortState {
|
|
readonly calls: SymbolSearchQuery[];
|
|
readonly port: SymbolSearchPort;
|
|
}
|
|
|
|
function createFakePort(options?: {
|
|
readonly rows?: readonly FixtureRow[];
|
|
readonly filterByCountry?: boolean;
|
|
readonly error?: unknown;
|
|
readonly rawReturn?: unknown;
|
|
}): FakePortState {
|
|
const calls: SymbolSearchQuery[] = [];
|
|
const rows = options?.rows ?? [];
|
|
|
|
const port: SymbolSearchPort = {
|
|
async searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]> {
|
|
calls.push({ ...q });
|
|
if (options?.error !== undefined) {
|
|
throw options.error;
|
|
}
|
|
if (options?.rawReturn !== undefined) {
|
|
return options.rawReturn as readonly SymbolSearchRow[];
|
|
}
|
|
if (options?.filterByCountry && q.country !== undefined) {
|
|
return rows.filter(row => row.country === q.country);
|
|
}
|
|
return [...rows];
|
|
},
|
|
};
|
|
|
|
return { calls, port };
|
|
}
|
|
|
|
function createMinimalStore(): MarketDataStore {
|
|
return {
|
|
bars() {
|
|
return {
|
|
async *[Symbol.asyncIterator]() {
|
|
// empty stream
|
|
},
|
|
};
|
|
},
|
|
async universe() {
|
|
return [];
|
|
},
|
|
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');
|
|
},
|
|
};
|
|
}
|
|
|
|
function createMinimalLedger(): TrialLedgerExecutor {
|
|
return {
|
|
async query() {
|
|
return { rows: [] };
|
|
},
|
|
};
|
|
}
|
|
|
|
async function callSearchSymbols(
|
|
fake: FakePortState,
|
|
args: Record<string, unknown>,
|
|
vaultCutoffTs = VAULT_CUTOFF_TS
|
|
): Promise<{
|
|
readonly isError: boolean;
|
|
readonly text: string;
|
|
readonly payload: SearchSymbolsResultPayload | null;
|
|
}> {
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createSearchSymbolsTool({
|
|
port: fake.port,
|
|
vaultContext: { vaultCutoffTs },
|
|
}),
|
|
],
|
|
});
|
|
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'ss-1',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'search_symbols',
|
|
arguments: args,
|
|
},
|
|
})
|
|
);
|
|
|
|
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 SearchSymbolsResultPayload),
|
|
};
|
|
}
|
|
|
|
describe('MCP search_symbols tool', () => {
|
|
test('registers alongside query_data, analyze_signal, and event_study and exposes strict schema via tools/list', async () => {
|
|
const store = createMinimalStore();
|
|
const ledger = createMinimalLedger();
|
|
const fake = createFakePort({
|
|
rows: [
|
|
makeRow({
|
|
listingId: 42,
|
|
instrumentId: 420,
|
|
ticker: 'AAPL',
|
|
classSuffix: null,
|
|
name: 'Apple Inc.',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: 'US0378331005',
|
|
firstBarDate: '1980-12-12',
|
|
lastBarDate: '2025-03-28',
|
|
delistedAt: null,
|
|
}),
|
|
],
|
|
});
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createQueryDataTool({
|
|
store,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
}),
|
|
createAnalyzeSignalTool({
|
|
store,
|
|
ledger,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
principalId: 'operator',
|
|
}),
|
|
createEventStudyTool({
|
|
store,
|
|
ledger,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
principalId: 'operator',
|
|
resolveExchangeCalendars: () => ({}),
|
|
}),
|
|
createSearchSymbolsTool({
|
|
port: fake.port,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
}),
|
|
],
|
|
});
|
|
|
|
const listRaw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 1,
|
|
method: 'tools/list',
|
|
})
|
|
);
|
|
expect(listRaw).not.toBeNull();
|
|
|
|
const listParsed = JSON.parse(listRaw as string) as {
|
|
result: {
|
|
tools: {
|
|
name: string;
|
|
description: string;
|
|
inputSchema: {
|
|
type: string;
|
|
properties: Record<string, Record<string, unknown>>;
|
|
required?: string[];
|
|
additionalProperties: boolean;
|
|
};
|
|
}[];
|
|
};
|
|
};
|
|
|
|
expect(listParsed.result.tools.map(t => t.name)).toEqual([
|
|
'query_data',
|
|
'analyze_signal',
|
|
'event_study',
|
|
'search_symbols',
|
|
]);
|
|
|
|
const searchTool = listParsed.result.tools.find(t => t.name === 'search_symbols');
|
|
expect(searchTool).toBeDefined();
|
|
expect(searchTool?.inputSchema.type).toBe('object');
|
|
expect(searchTool?.inputSchema.additionalProperties).toBe(false);
|
|
expect(searchTool?.inputSchema.required).toEqual(['query']);
|
|
expect(searchTool?.inputSchema.properties.query).toMatchObject({
|
|
type: 'string',
|
|
minLength: 1,
|
|
maxLength: SEARCH_SYMBOLS_MAX_QUERY_LENGTH,
|
|
});
|
|
expect(searchTool?.inputSchema.properties.limit).toMatchObject({
|
|
type: 'integer',
|
|
minimum: 1,
|
|
maximum: SEARCH_SYMBOLS_MAX_LIMIT,
|
|
default: SEARCH_SYMBOLS_DEFAULT_LIMIT,
|
|
});
|
|
expect(searchTool?.inputSchema.properties.country).toMatchObject({
|
|
type: 'string',
|
|
enum: ['US', 'CA'],
|
|
});
|
|
expect(searchTool?.inputSchema.properties.includeDelisted).toMatchObject({
|
|
type: 'boolean',
|
|
default: true,
|
|
});
|
|
expect(searchTool?.inputSchema.properties.scope).toBeUndefined();
|
|
expect(searchTool?.inputSchema.properties.vault_evaluation_only).toBeUndefined();
|
|
expect(searchTool?.inputSchema.properties.vaultCutoffTs).toBeUndefined();
|
|
|
|
// Exercise JSON-RPC tools/call end-to-end on the multi-tool server.
|
|
const callRaw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 2,
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'search_symbols',
|
|
arguments: { query: 'AAPL' },
|
|
},
|
|
})
|
|
);
|
|
expect(callRaw).not.toBeNull();
|
|
const callParsed = JSON.parse(callRaw as string) as {
|
|
result: { isError?: boolean; content: { type: string; text: string }[] };
|
|
};
|
|
expect(callParsed.result.isError).toBeUndefined();
|
|
const payload = JSON.parse(callParsed.result.content[0]?.text ?? '') as SearchSymbolsResultPayload;
|
|
expect(payload).toEqual({
|
|
scope: 'vault_fenced',
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
rowCount: 1,
|
|
truncated: false,
|
|
rows: [
|
|
{
|
|
listingId: 42,
|
|
instrumentId: 420,
|
|
ticker: 'AAPL',
|
|
classSuffix: null,
|
|
name: 'Apple Inc.',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: 'US0378331005',
|
|
firstBarDate: '1980-12-12',
|
|
lastBarDate: '2025-03-28',
|
|
delistedAt: null,
|
|
},
|
|
],
|
|
});
|
|
});
|
|
|
|
test('ranks exact ticker > ticker prefix > company name case-insensitively with numeric listingId tie-break', async () => {
|
|
const fixture: SymbolSearchRow[] = [
|
|
makeRow({ listingId: 100, ticker: 'XYZ', name: 'Apple Blossom Holdings' }),
|
|
makeRow({ listingId: 10, ticker: 'AAPL', name: 'Apple Inc. Secondary' }),
|
|
makeRow({ listingId: 25, ticker: 'AAPLE', name: 'Apple Energy Corp' }),
|
|
makeRow({ listingId: 2, ticker: 'aapl', name: 'Apple Inc.' }),
|
|
makeRow({ listingId: 5, ticker: 'AAPLX', name: 'Apple Extended ETF' }),
|
|
makeRow({ listingId: 15, ticker: 'ZZZ', name: 'aapl Partners LP' }),
|
|
makeRow({ listingId: 30, ticker: 'OTHER', name: 'Unrelated Name' }),
|
|
];
|
|
|
|
const fakeA = createFakePort({ rows: fixture });
|
|
const fakeB = createFakePort({ rows: [...fixture].reverse() });
|
|
|
|
const resA = await callSearchSymbols(fakeA, { query: ' AaPl ' });
|
|
const resB = await callSearchSymbols(fakeB, { query: ' AaPl ' });
|
|
|
|
expect(resA.isError).toBe(false);
|
|
expect(resB.isError).toBe(false);
|
|
expect(resA.payload).toEqual(resB.payload);
|
|
|
|
// Exact ticker (2, 10) -> prefix (5, 25) -> name substring (15); unrelated candidates (30, 100) are excluded
|
|
expect(resA.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]);
|
|
expect(resA.payload?.rowCount).toBe(5);
|
|
expect(resA.payload?.truncated).toBe(false);
|
|
|
|
// Unrelated candidates must not trigger truncation when all actual matches fit within limit.
|
|
const exactFitRes = await callSearchSymbols(createFakePort({ rows: fixture }), {
|
|
query: 'AAPL',
|
|
limit: 5,
|
|
});
|
|
expect(exactFitRes.isError).toBe(false);
|
|
expect(exactFitRes.payload?.rows.map(r => r.listingId)).toEqual([2, 10, 5, 25, 15]);
|
|
expect(exactFitRes.payload?.rowCount).toBe(5);
|
|
expect(exactFitRes.payload?.truncated).toBe(false);
|
|
|
|
// When none of the port's returned candidates match, return an empty, non-truncated payload.
|
|
const noMatchRes = await callSearchSymbols(createFakePort({ rows: fixture }), {
|
|
query: 'UNMATCHED',
|
|
limit: 2,
|
|
});
|
|
expect(noMatchRes.isError).toBe(false);
|
|
expect(noMatchRes.payload).toEqual({
|
|
scope: 'vault_fenced',
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
rowCount: 0,
|
|
truncated: false,
|
|
rows: [],
|
|
});
|
|
|
|
// Verify trimmed query, default limit, includeDelisted: true, and vaultCutoffTs were passed to port.
|
|
expect(fakeA.calls).toHaveLength(1);
|
|
expect(fakeA.calls[0]).toEqual({
|
|
query: 'AaPl',
|
|
limit: SEARCH_SYMBOLS_DEFAULT_LIMIT,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
});
|
|
|
|
test('forwards country filter and returns empty payload when no listings match', async () => {
|
|
const fake = createFakePort({
|
|
filterByCountry: true,
|
|
rows: [
|
|
{ ...makeRow({ listingId: 1, ticker: 'SHOP', mic: 'XNYS', currency: 'USD' }), country: 'US' },
|
|
{ ...makeRow({ listingId: 2, ticker: 'SHOP', mic: 'XTSE', currency: 'CAD' }), country: 'CA' },
|
|
],
|
|
});
|
|
|
|
const caRes = await callSearchSymbols(fake, { query: 'SHOP', country: 'CA' });
|
|
expect(caRes.isError).toBe(false);
|
|
expect(caRes.payload?.rows.map(r => r.listingId)).toEqual([2]);
|
|
expect(fake.calls[0]?.country).toBe('CA');
|
|
|
|
const emptyFake = createFakePort({ rows: [] });
|
|
const emptyRes = await callSearchSymbols(emptyFake, { query: 'NO_SUCH_SYMBOL', country: 'US' });
|
|
expect(emptyRes.isError).toBe(false);
|
|
expect(emptyRes.payload).toEqual({
|
|
scope: 'vault_fenced',
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
rowCount: 0,
|
|
truncated: false,
|
|
rows: [],
|
|
});
|
|
expect(emptyFake.calls[0]?.country).toBe('US');
|
|
});
|
|
|
|
test('enforces default limit 20, hard max 100, exact-fit, and over-returning port truncation', async () => {
|
|
// 25 eligible rows with default limit (20) -> truncated: true
|
|
const rows25: SymbolSearchRow[] = [];
|
|
for (let i = 1; i <= 25; i += 1) {
|
|
rows25.push(makeRow({ listingId: i, ticker: `SYM${i}`, name: `Symbol ${i}` }));
|
|
}
|
|
const defaultOver = await callSearchSymbols(createFakePort({ rows: rows25 }), { query: 'SYM' });
|
|
expect(defaultOver.isError).toBe(false);
|
|
expect(defaultOver.payload?.rowCount).toBe(20);
|
|
expect(defaultOver.payload?.rows).toHaveLength(20);
|
|
expect(defaultOver.payload?.truncated).toBe(true);
|
|
|
|
// Exact fit of 20 eligible rows -> truncated: false
|
|
const defaultExact = await callSearchSymbols(createFakePort({ rows: rows25.slice(0, 20) }), {
|
|
query: 'SYM',
|
|
});
|
|
expect(defaultExact.isError).toBe(false);
|
|
expect(defaultExact.payload?.rowCount).toBe(20);
|
|
expect(defaultExact.payload?.truncated).toBe(false);
|
|
|
|
// Hard max 100 accepted; port over-returns 115 rows with late exact match at end
|
|
const rows115: SymbolSearchRow[] = [];
|
|
for (let i = 1; i <= 114; i += 1) {
|
|
rows115.push(makeRow({ listingId: i + 10, ticker: `ABC${i}`, name: `ABC Corp ${i}` }));
|
|
}
|
|
rows115.push(makeRow({ listingId: 999, ticker: 'ABC', name: 'Exact Match Late In Array' }));
|
|
|
|
const maxOver = await callSearchSymbols(createFakePort({ rows: rows115 }), {
|
|
query: 'ABC',
|
|
limit: 100,
|
|
});
|
|
expect(maxOver.isError).toBe(false);
|
|
expect(maxOver.payload?.rowCount).toBe(100);
|
|
expect(maxOver.payload?.rows).toHaveLength(100);
|
|
expect(maxOver.payload?.truncated).toBe(true);
|
|
// Late exact ticker match must still rank #1 before slicing
|
|
expect(maxOver.payload?.rows[0]?.listingId).toBe(999);
|
|
|
|
// Exact fit at max 100 -> truncated: false
|
|
const maxExact = await callSearchSymbols(createFakePort({ rows: rows115.slice(0, 100) }), {
|
|
query: 'ABC',
|
|
limit: 100,
|
|
});
|
|
expect(maxExact.isError).toBe(false);
|
|
expect(maxExact.payload?.rowCount).toBe(100);
|
|
expect(maxExact.payload?.truncated).toBe(false);
|
|
});
|
|
|
|
test('rows removed by Vault fencing or includeDelisted: false do not count toward truncation', async () => {
|
|
const rows: SymbolSearchRow[] = [
|
|
// Post-cutoff listings placed ahead of eligible matches
|
|
makeRow({ listingId: 1, ticker: 'ACME', firstBarDate: '2025-04-01' }),
|
|
makeRow({ listingId: 2, ticker: 'ACME2', firstBarDate: '2025-05-15' }),
|
|
// Historically delisted listings
|
|
makeRow({ listingId: 3, ticker: 'ACME3', delistedAt: '2024-06-30', lastBarDate: '2024-06-28' }),
|
|
makeRow({ listingId: 4, ticker: 'ACME4', delistedAt: '2025-03-31', lastBarDate: '2025-03-31' }),
|
|
// Active as of cutoff (one active forever, one delisted after cutoff)
|
|
makeRow({ listingId: 5, ticker: 'ACME5', delistedAt: null }),
|
|
makeRow({ listingId: 6, ticker: 'ACME6', delistedAt: '2025-04-15', lastBarDate: '2025-04-14' }),
|
|
];
|
|
|
|
const res = await callSearchSymbols(createFakePort({ rows }), {
|
|
query: 'ACME',
|
|
limit: 2,
|
|
includeDelisted: false,
|
|
});
|
|
|
|
expect(res.isError).toBe(false);
|
|
expect(res.payload?.rows.map(r => r.listingId)).toEqual([5, 6]);
|
|
expect(res.payload?.rowCount).toBe(2);
|
|
expect(res.payload?.truncated).toBe(false);
|
|
});
|
|
|
|
test('enforces Vault fencing on firstBarDate, lastBarDate, delistedAt, UTC cutoff equality, and null dates', async () => {
|
|
const extraFieldRow = {
|
|
...makeRow({
|
|
listingId: 10,
|
|
ticker: 'VLT',
|
|
classSuffix: 'A',
|
|
isin: 'US0000000010',
|
|
firstBarDate: '2024-02-29', // valid leap-year date
|
|
lastBarDate: '2025-06-01', // after cutoff -> clamp to 2025-03-31
|
|
delistedAt: '2025-05-01', // after cutoff -> mask to null
|
|
}),
|
|
internalSecretField: 'must-not-leak',
|
|
} as unknown as SymbolSearchRow;
|
|
|
|
const rows: SymbolSearchRow[] = [
|
|
extraFieldRow,
|
|
// firstBarDate strictly after cutoff -> dropped
|
|
makeRow({
|
|
listingId: 11,
|
|
ticker: 'VLT',
|
|
firstBarDate: '2025-04-01',
|
|
lastBarDate: '2025-06-01',
|
|
delistedAt: null,
|
|
}),
|
|
// firstBarDate / lastBarDate / delistedAt equal to cutoff -> kept as-is
|
|
makeRow({
|
|
listingId: 12,
|
|
ticker: 'VLT',
|
|
firstBarDate: VAULT_CUTOFF_DATE,
|
|
lastBarDate: VAULT_CUTOFF_DATE,
|
|
delistedAt: VAULT_CUTOFF_DATE,
|
|
}),
|
|
// Null dates preserved
|
|
makeRow({
|
|
listingId: 13,
|
|
ticker: 'VLT',
|
|
firstBarDate: null,
|
|
lastBarDate: null,
|
|
delistedAt: null,
|
|
}),
|
|
// Historical delisting before cutoff -> preserved by default
|
|
makeRow({
|
|
listingId: 14,
|
|
ticker: 'VLT',
|
|
firstBarDate: '2019-01-03',
|
|
lastBarDate: '2023-10-12',
|
|
delistedAt: '2023-10-15',
|
|
}),
|
|
];
|
|
|
|
const fakeDefault = createFakePort({ rows });
|
|
const resDefault = await callSearchSymbols(fakeDefault, { query: 'VLT' });
|
|
expect(resDefault.isError).toBe(false);
|
|
expect(resDefault.payload?.rows).toEqual([
|
|
{
|
|
listingId: 10,
|
|
instrumentId: 100,
|
|
ticker: 'VLT',
|
|
classSuffix: 'A',
|
|
name: 'Company 10',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: 'US0000000010',
|
|
firstBarDate: '2024-02-29',
|
|
lastBarDate: VAULT_CUTOFF_DATE,
|
|
delistedAt: null,
|
|
},
|
|
{
|
|
listingId: 12,
|
|
instrumentId: 120,
|
|
ticker: 'VLT',
|
|
classSuffix: null,
|
|
name: 'Company 12',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: null,
|
|
firstBarDate: VAULT_CUTOFF_DATE,
|
|
lastBarDate: VAULT_CUTOFF_DATE,
|
|
delistedAt: VAULT_CUTOFF_DATE,
|
|
},
|
|
{
|
|
listingId: 13,
|
|
instrumentId: 130,
|
|
ticker: 'VLT',
|
|
classSuffix: null,
|
|
name: 'Company 13',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: null,
|
|
firstBarDate: null,
|
|
lastBarDate: null,
|
|
delistedAt: null,
|
|
},
|
|
{
|
|
listingId: 14,
|
|
instrumentId: 140,
|
|
ticker: 'VLT',
|
|
classSuffix: null,
|
|
name: 'Company 14',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: null,
|
|
firstBarDate: '2019-01-03',
|
|
lastBarDate: '2023-10-12',
|
|
delistedAt: '2023-10-15',
|
|
},
|
|
]);
|
|
// Extra port property must not be projected
|
|
expect('internalSecretField' in (resDefault.payload?.rows[0] ?? {})).toBe(false);
|
|
|
|
// With includeDelisted: false, historical delistings (12, 14) are excluded,
|
|
// while future delisting (10) remains eligible with delistedAt: null.
|
|
const fakeNoDelisted = createFakePort({ rows });
|
|
const resNoDelisted = await callSearchSymbols(fakeNoDelisted, {
|
|
query: 'VLT',
|
|
includeDelisted: false,
|
|
});
|
|
expect(resNoDelisted.isError).toBe(false);
|
|
expect(resNoDelisted.payload?.rows.map(r => r.listingId)).toEqual([10, 13]);
|
|
expect(resNoDelisted.payload?.rows[0]?.delistedAt).toBeNull();
|
|
// Port must still be called with includeDelisted: true
|
|
expect(fakeNoDelisted.calls[0]?.includeDelisted).toBe(true);
|
|
});
|
|
|
|
test('rejects invalid port date strings with sanitized isError result', async () => {
|
|
const invalidDateCases: Partial<SymbolSearchRow>[] = [
|
|
{ firstBarDate: '2025-02-29' }, // non-leap year Feb 29
|
|
{ lastBarDate: '2025-04-31' }, // April has 30 days
|
|
{ delistedAt: '2025-13-01' }, // invalid month
|
|
{ firstBarDate: '2025-03-31T00:00:00Z' }, // timestamp instead of YYYY-MM-DD
|
|
{ lastBarDate: 'not-a-date' },
|
|
{ delistedAt: '' },
|
|
];
|
|
|
|
for (const badFields of invalidDateCases) {
|
|
const fake = createFakePort({
|
|
rows: [makeRow({ listingId: 1, ticker: 'BAD', ...badFields })],
|
|
});
|
|
const res = await callSearchSymbols(fake, { query: 'BAD' });
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toBe('Error: Tool execution failed.');
|
|
}
|
|
});
|
|
|
|
test('factory throws MarketDataStoreValidationError on missing or invalid port or vaultCutoffTs', () => {
|
|
const validPort = createFakePort().port;
|
|
|
|
expect(() =>
|
|
createSearchSymbolsTool(null as unknown as Parameters<typeof createSearchSymbolsTool>[0])
|
|
).toThrow(MarketDataStoreValidationError);
|
|
|
|
expect(() =>
|
|
createSearchSymbolsTool({
|
|
port: null as unknown as SymbolSearchPort,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
|
|
expect(() =>
|
|
createSearchSymbolsTool({
|
|
port: {} as unknown as SymbolSearchPort,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
|
|
const invalidCutoffs: unknown[] = [
|
|
undefined,
|
|
null,
|
|
'2025-03-31',
|
|
Number.NaN,
|
|
Number.POSITIVE_INFINITY,
|
|
Number.NEGATIVE_INFINITY,
|
|
123.45,
|
|
8_640_000_000_000_000,
|
|
];
|
|
|
|
for (const badCutoff of invalidCutoffs) {
|
|
expect(() =>
|
|
createSearchSymbolsTool({
|
|
port: validPort,
|
|
vaultContext: { vaultCutoffTs: badCutoff as number },
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
}
|
|
|
|
expect(() =>
|
|
createSearchSymbolsTool({
|
|
port: validPort,
|
|
vaultContext: undefined as unknown as { vaultCutoffTs: number },
|
|
})
|
|
).toThrow(MarketDataStoreValidationError);
|
|
});
|
|
|
|
test('returns structured isError without calling port on invalid arguments', async () => {
|
|
const invalidInputs: Record<string, unknown>[] = [
|
|
{},
|
|
{ query: '' },
|
|
{ query: ' \t\n ' },
|
|
{ query: 'A'.repeat(SEARCH_SYMBOLS_MAX_QUERY_LENGTH + 1) },
|
|
{ query: 'AAPL', limit: 0 },
|
|
{ query: 'AAPL', limit: -5 },
|
|
{ query: 'AAPL', limit: SEARCH_SYMBOLS_MAX_LIMIT + 1 },
|
|
{ query: 'AAPL', limit: 1.5 },
|
|
{ query: 'AAPL', country: 'UK' },
|
|
{ query: 'AAPL', country: 'us' },
|
|
{ query: 'AAPL', includeDelisted: 'true' },
|
|
{ query: 'AAPL', scope: 'vault_evaluation_only' },
|
|
{ query: 'AAPL', unknownField: 123 },
|
|
];
|
|
|
|
for (const args of invalidInputs) {
|
|
const fake = createFakePort({ rows: [makeRow({ listingId: 1, ticker: 'AAPL' })] });
|
|
const res = await callSearchSymbols(fake, args);
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toContain('Invalid arguments for tool "search_symbols"');
|
|
expect(fake.calls).toHaveLength(0);
|
|
}
|
|
});
|
|
|
|
test('returns sanitized isError without leaking error message when port rejects', async () => {
|
|
const fake = createFakePort({
|
|
error: new Error('postgres://admin:super-secret@10.0.0.51:5432/trading_bot failed'),
|
|
});
|
|
|
|
const res = await callSearchSymbols(fake, { query: 'AAPL' });
|
|
expect(res.isError).toBe(true);
|
|
expect(res.text).toBe('Error: Tool execution failed.');
|
|
expect(res.text).not.toContain('super-secret');
|
|
expect(res.text).not.toContain('10.0.0.51');
|
|
expect(res.text).not.toContain('trading_bot');
|
|
expect(fake.calls).toHaveLength(1);
|
|
});
|
|
});
|