447 lines
16 KiB
TypeScript
447 lines
16 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Pool } from 'pg';
|
|
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
|
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
|
import {
|
|
type SearchSymbolsResultPayload,
|
|
type SymbolSearchExecutor,
|
|
createMcpServer,
|
|
createPostgresSymbolSearchPort,
|
|
createSearchSymbolsTool,
|
|
} from '../../libs/research/src/mcp/index';
|
|
|
|
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
|
const logger = getLogger('mcp-symbol-search-adapter-pg-test');
|
|
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
|
|
|
const VAULT_CUTOFF_DATE = '2024-06-30';
|
|
const VAULT_CUTOFF_TS = Date.UTC(2024, 5, 30, 0, 0, 0, 0);
|
|
|
|
const cleanup: (() => Promise<void> | void)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanup.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
|
|
function assertSafetyDatabaseUrl(connectionString: string | undefined): string {
|
|
if (!connectionString || !new URL(connectionString).pathname.startsWith('/stock_bot_safety')) {
|
|
throw new Error('Dedicated stock_bot_safety database required');
|
|
}
|
|
return connectionString;
|
|
}
|
|
|
|
function createPgExecutor(pool: Pool): SymbolSearchExecutor {
|
|
return {
|
|
query<Row = Record<string, unknown>>(
|
|
text: string,
|
|
params?: readonly unknown[]
|
|
): Promise<{ readonly rows: readonly Row[] }> {
|
|
return pool.query(
|
|
text,
|
|
params === undefined ? undefined : [...params]
|
|
) as unknown as Promise<{ readonly rows: readonly Row[] }>;
|
|
},
|
|
};
|
|
}
|
|
|
|
async function createIsolatedFixture() {
|
|
const safeUrl = assertSafetyDatabaseUrl(url);
|
|
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
|
const admin = new Pool({ connectionString: safeUrl });
|
|
await admin.query(`CREATE SCHEMA ${schema}`);
|
|
const pool = new Pool({
|
|
connectionString: safeUrl,
|
|
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
|
});
|
|
cleanup.push(async () => {
|
|
await pool.end();
|
|
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
|
await admin.end();
|
|
});
|
|
|
|
const postgres = new PostgreSQLClient(
|
|
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
|
logger
|
|
);
|
|
Object.defineProperty(postgres, 'connectionPool', {
|
|
get: () => ({
|
|
connect: () => pool.connect(),
|
|
}),
|
|
});
|
|
|
|
await runPostgresMigrations(postgres, { track: 'master' });
|
|
await seedFixture(pool);
|
|
|
|
return { admin, pool, schema };
|
|
}
|
|
|
|
async function seedFixture(pool: Pool): Promise<void> {
|
|
const client = await pool.connect();
|
|
try {
|
|
await client.query('BEGIN');
|
|
|
|
await client.query(`
|
|
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
|
|
VALUES
|
|
('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
|
|
('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
|
|
('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered')
|
|
ON CONFLICT (mic) DO NOTHING
|
|
`);
|
|
|
|
await client.query(`
|
|
INSERT INTO instrument (instrument_id, primary_isin, canonical_name, security_type, issuer_country)
|
|
OVERRIDING SYSTEM VALUE
|
|
VALUES
|
|
(101, 'US1010000001', 'Renamed Holdings Inc', 'common', 'US'),
|
|
(102, 'US1020000002', 'Gap Rename Corp', 'common', 'US'),
|
|
(103, 'US1030000003', 'Stealth Future Ventures', 'common', 'US'),
|
|
(104, 'CA1040000004', 'No History Metals', 'common', 'CA'),
|
|
(105, 'US1050000005', 'Overlap Equity Inc', 'common', 'US'),
|
|
(106, 'US1060000006', 'Post Cutoff IPO Inc', 'common', 'US'),
|
|
(107, 'CA1070000007', 'Unknown Start Corp', 'common', 'CA'),
|
|
(108, 'US1080000008', 'Delist Boundary Co', 'common', 'US'),
|
|
(109, 'US1090000009', 'Delist Boundary Active', 'common', 'US'),
|
|
(110, 'US1100000010', 'Delist Boundary Unspecified', 'common', 'US'),
|
|
(111, 'US1110000011', 'Delist Boundary Future', 'common', 'US'),
|
|
(112, 'US1120000012', '100% Pure_Wild\\Co', 'common', 'US'),
|
|
(113, 'US1130000013', 'Second Oldco Group', 'common', 'US'),
|
|
(114, 'CA1140000014', 'Alpha Oldco Canada', 'common', 'CA')
|
|
`);
|
|
|
|
await client.query(`
|
|
INSERT INTO listing (
|
|
listing_id, instrument_id, mic, ticker_root, class_suffix, currency,
|
|
listed_from, listed_to, delist_reason
|
|
)
|
|
OVERRIDING SYSTEM VALUE
|
|
VALUES
|
|
(101, 101, 'XNAS', 'NEWCO', '', 'USD', '2018-01-02', '2024-12-31', 'active'),
|
|
(102, 102, 'XNYS', 'GAPNEW', '', 'USD', '2019-01-01', '2024-12-31', 'active'),
|
|
(103, 103, 'XNAS', 'FUTROOT', '', 'USD', '2020-01-01', NULL, NULL),
|
|
(104, 104, 'XTSE', 'NOHIST', 'A', 'CAD', '2021-03-15', '2024-06-28', 'active'),
|
|
(105, 105, 'XNYS', 'OVLP', '', 'USD', '2018-01-01', '2024-06-28', 'active'),
|
|
(106, 106, 'XNAS', 'IPO25', '', 'USD', '2024-07-01', NULL, 'active'),
|
|
(107, 107, 'XTSE', 'NULLSTART', '', 'CAD', NULL, NULL, NULL),
|
|
(108, 108, 'XNAS', 'DLST1', '', 'USD', '2015-01-01', '2024-06-30', 'merger_cash'),
|
|
(109, 109, 'XNAS', 'DLST2', '', 'USD', '2015-01-01', '2024-06-28', 'active'),
|
|
(110, 110, 'XNAS', 'DLST3', '', 'USD', '2015-01-01', '2024-06-28', NULL),
|
|
(111, 111, 'XNAS', 'DLST4', '', 'USD', '2015-01-01', '2024-09-15', 'bankruptcy_cancelled'),
|
|
(112, 112, 'XNYS', 'WILD', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
|
|
(113, 113, 'XNAS', 'OLDCO2', '', 'USD', '2020-01-01', '2024-06-28', 'active'),
|
|
(114, 114, 'XTSE', 'ZOLD', '', 'CAD', '2020-01-01', '2024-06-28', 'active')
|
|
`);
|
|
|
|
await client.query(`
|
|
INSERT INTO listing_symbol_history (listing_id, ticker, valid_from, valid_to, source)
|
|
VALUES
|
|
(101, 'OLDCO', '2018-01-02', '2024-06-30', 'eod'),
|
|
(101, 'NEWCO', '2024-07-01', NULL, 'eod'),
|
|
(102, 'GAPOLD', '2019-01-01', '2024-05-31', 'eod'),
|
|
(102, 'GAPNEW', '2024-07-01', NULL, 'eod'),
|
|
(103, 'FUTROOT', '2024-07-15', NULL, 'eod'),
|
|
(105, 'OVLP1', '2018-01-01', NULL, 'eod'),
|
|
(105, 'OVLPZ', '2023-01-01', NULL, 'eod'),
|
|
(105, 'OVLPA', '2023-01-01', NULL, 'eod')
|
|
`);
|
|
|
|
await client.query('COMMIT');
|
|
} catch (err) {
|
|
await client.query('ROLLBACK');
|
|
throw err;
|
|
} finally {
|
|
client.release();
|
|
}
|
|
}
|
|
|
|
describe('PostgreSQL symbol search safety guard', () => {
|
|
test('rejects unsafe database targets before connecting', () => {
|
|
expect(() => assertSafetyDatabaseUrl(undefined)).toThrow('Dedicated stock_bot_safety database required');
|
|
expect(() =>
|
|
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/trading_bot')
|
|
).toThrow('Dedicated stock_bot_safety database required');
|
|
expect(() =>
|
|
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5433/trading_bot_dev')
|
|
).toThrow('Dedicated stock_bot_safety database required');
|
|
expect(
|
|
assertSafetyDatabaseUrl('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test')
|
|
).toBe('postgres://postgres:postgres@127.0.0.1:5432/stock_bot_safety_test');
|
|
});
|
|
});
|
|
|
|
describe.skipIf(!url)('PostgreSQL MCP symbol search adapter', () => {
|
|
test('enforces as-of-cutoff ticker resolution, root suppression, and listed_from bounds', async () => {
|
|
const f = await createIsolatedFixture();
|
|
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
|
|
|
|
// (a)/(g) Post-cutoff rename: OLDCO is valid on 2024-06-30; NEWCO starts 2024-07-01 and is invisible even as ticker_root
|
|
const oldcoRows = await port.searchSymbols({
|
|
query: 'OLDCO',
|
|
limit: 1,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(oldcoRows.map(r => r.listingId)).toEqual([101, 113, 114]);
|
|
expect(oldcoRows[0]).toEqual({
|
|
listingId: 101,
|
|
instrumentId: 101,
|
|
ticker: 'OLDCO',
|
|
classSuffix: null,
|
|
name: 'Renamed Holdings Inc',
|
|
mic: 'XNAS',
|
|
currency: 'USD',
|
|
isin: 'US1010000001',
|
|
firstBarDate: '2018-01-02',
|
|
lastBarDate: '2024-12-31',
|
|
delistedAt: null,
|
|
});
|
|
|
|
const newcoRows = await port.searchSymbols({
|
|
query: 'NEWCO',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(newcoRows).toEqual([]);
|
|
|
|
// Expired-but-known fallback (step 3c): GAPNEW is future-only root, falls back to GAPOLD
|
|
const gapOldRows = await port.searchSymbols({
|
|
query: 'GAPOLD',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(gapOldRows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
|
|
{ id: 102, ticker: 'GAPOLD' },
|
|
]);
|
|
const gapNewRows = await port.searchSymbols({
|
|
query: 'GAPNEW',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(gapNewRows).toEqual([]);
|
|
|
|
// (h) Future-only root with no prior history: excluded by root, name, and ISIN searches
|
|
expect(
|
|
await port.searchSymbols({
|
|
query: 'FUTROOT',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
})
|
|
).toEqual([]);
|
|
expect(
|
|
await port.searchSymbols({
|
|
query: 'Stealth Future',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
})
|
|
).toEqual([]);
|
|
expect(
|
|
await port.searchSymbols({
|
|
query: 'US1030000003',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
})
|
|
).toEqual([]);
|
|
|
|
// (i) No history rows at all: falls back to ticker_root
|
|
const noHistRows = await port.searchSymbols({
|
|
query: 'NOHIST',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(noHistRows).toEqual([
|
|
{
|
|
listingId: 104,
|
|
instrumentId: 104,
|
|
ticker: 'NOHIST',
|
|
classSuffix: 'A',
|
|
name: 'No History Metals',
|
|
mic: 'XTSE',
|
|
currency: 'CAD',
|
|
isin: 'CA1040000004',
|
|
firstBarDate: '2021-03-15',
|
|
lastBarDate: '2024-06-28',
|
|
delistedAt: null,
|
|
},
|
|
]);
|
|
|
|
// Overlapping valid history: latest valid_from wins, tie-breaking by ticker ASC (OVLPA < OVLPZ)
|
|
const overlapRows = await port.searchSymbols({
|
|
query: 'Overlap Equity',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(overlapRows).toHaveLength(1);
|
|
expect(overlapRows[0]!.listingId).toBe(105);
|
|
expect(overlapRows[0]!.ticker).toBe('OVLPA');
|
|
|
|
// (b) listed_from > cutoff excluded
|
|
expect(
|
|
await port.searchSymbols({
|
|
query: 'IPO25',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
})
|
|
).toEqual([]);
|
|
|
|
// (c) listed_from IS NULL included
|
|
const nullStartRows = await port.searchSymbols({
|
|
query: 'NULLSTART',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(nullStartRows).toHaveLength(1);
|
|
expect(nullStartRows[0]!.listingId).toBe(107);
|
|
expect(nullStartRows[0]!.firstBarDate).toBeNull();
|
|
expect(nullStartRows[0]!.lastBarDate).toBeNull();
|
|
expect(nullStartRows[0]!.delistedAt).toBeNull();
|
|
});
|
|
|
|
test('supports country filter, case-insensitive exact ISIN, literal wildcards, delisting semantics, explicit schema, and deterministic ordering', async () => {
|
|
const f = await createIsolatedFixture();
|
|
// Use admin pool (default search_path) with explicit schema option to verify schema quoting
|
|
const port = createPostgresSymbolSearchPort({
|
|
executor: createPgExecutor(f.admin),
|
|
schema: f.schema,
|
|
});
|
|
|
|
// (d) country: 'CA' returns only CA-venue listings
|
|
const caRows = await port.searchSymbols({
|
|
query: 'OLDCO',
|
|
limit: 20,
|
|
country: 'CA',
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(caRows.map(r => ({ id: r.listingId, mic: r.mic }))).toEqual([
|
|
{ id: 114, mic: 'XTSE' },
|
|
]);
|
|
|
|
// (e) Case-insensitive exact ISIN match with partial-ISIN negative
|
|
const isinRows = await port.searchSymbols({
|
|
query: 'ca1040000004',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(isinRows.map(r => r.listingId)).toEqual([104]);
|
|
|
|
const partialIsinRows = await port.searchSymbols({
|
|
query: 'CA104000',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(partialIsinRows).toEqual([]);
|
|
|
|
// Literal wildcard matching: %, _, and \ are escaped
|
|
const wildRows = await port.searchSymbols({
|
|
query: '100% Pure_Wild\\',
|
|
limit: 20,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(wildRows.map(r => r.listingId)).toEqual([112]);
|
|
|
|
// Delisting boundary: 108 confirmed delisted on cutoff (2024-06-30), 109 active, 110 null reason, 111 future delist (2024-09-15)
|
|
const allDelist = await port.searchSymbols({
|
|
query: 'Delist Boundary',
|
|
limit: 1,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(allDelist.map(r => ({ id: r.listingId, delistedAt: r.delistedAt }))).toEqual([
|
|
{ id: 108, delistedAt: '2024-06-30' },
|
|
{ id: 109, delistedAt: null },
|
|
{ id: 110, delistedAt: null },
|
|
{ id: 111, delistedAt: '2024-09-15' },
|
|
]);
|
|
|
|
const activeAsOfCutoff = await port.searchSymbols({
|
|
query: 'Delist Boundary',
|
|
limit: 20,
|
|
includeDelisted: false,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(activeAsOfCutoff.map(r => r.listingId)).toEqual([109, 110, 111]);
|
|
|
|
// Repeated pinned query produces identical deterministic rows
|
|
const repeat = await port.searchSymbols({
|
|
query: 'Delist Boundary',
|
|
limit: 1,
|
|
includeDelisted: true,
|
|
vaultCutoffTs: VAULT_CUTOFF_TS,
|
|
});
|
|
expect(repeat).toEqual(allDelist);
|
|
});
|
|
|
|
test('composes with createSearchSymbolsTool through MCP for ranking, truncation, clamping, and future delisting masking', async () => {
|
|
const f = await createIsolatedFixture();
|
|
const port = createPostgresSymbolSearchPort({ executor: createPgExecutor(f.pool) });
|
|
|
|
const server = createMcpServer({
|
|
name: 'stock-bot-research',
|
|
version: '0.1.0',
|
|
tools: [
|
|
createSearchSymbolsTool({
|
|
port,
|
|
vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS },
|
|
}),
|
|
],
|
|
});
|
|
|
|
const callTool = async (args: Record<string, unknown>): Promise<SearchSymbolsResultPayload> => {
|
|
const raw = await server.handleMessage(
|
|
JSON.stringify({
|
|
jsonrpc: '2.0',
|
|
id: 'mcp-pg-1',
|
|
method: 'tools/call',
|
|
params: {
|
|
name: 'search_symbols',
|
|
arguments: args,
|
|
},
|
|
})
|
|
);
|
|
expect(raw).not.toBeNull();
|
|
const parsed = JSON.parse(raw!) as {
|
|
result: { isError?: boolean; content: Array<{ text: string }> };
|
|
};
|
|
expect(parsed.result.isError).toBeUndefined();
|
|
return JSON.parse(parsed.result.content[0]!.text) as SearchSymbolsResultPayload;
|
|
};
|
|
|
|
// Ranking & truncation: exact ticker OLDCO (101) > prefix OLDCO2 (113) > name Alpha Oldco Canada (114)
|
|
const oldcoPayload = await callTool({ query: 'OLDCO', limit: 2 });
|
|
expect(oldcoPayload.scope).toBe('vault_fenced');
|
|
expect(oldcoPayload.vaultCutoffTs).toBe(VAULT_CUTOFF_TS);
|
|
expect(oldcoPayload.truncated).toBe(true);
|
|
expect(oldcoPayload.rowCount).toBe(2);
|
|
expect(oldcoPayload.rows.map(r => ({ id: r.listingId, ticker: r.ticker }))).toEqual([
|
|
{ id: 101, ticker: 'OLDCO' },
|
|
{ id: 113, ticker: 'OLDCO2' },
|
|
]);
|
|
// Post-cutoff lastBarDate (2024-12-31) is clamped to vaultCutoffDate (2024-06-30)
|
|
expect(oldcoPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE);
|
|
|
|
// Future delisting (111: listed_to=2024-09-15, delist_reason=bankruptcy_cancelled) is masked to null and clamped
|
|
const futureDelistPayload = await callTool({
|
|
query: 'DLST4',
|
|
includeDelisted: false,
|
|
});
|
|
expect(futureDelistPayload.rowCount).toBe(1);
|
|
expect(futureDelistPayload.rows[0]!.listingId).toBe(111);
|
|
expect(futureDelistPayload.rows[0]!.lastBarDate).toBe(VAULT_CUTOFF_DATE);
|
|
expect(futureDelistPayload.rows[0]!.delistedAt).toBeNull();
|
|
});
|
|
});
|