T-158: M2.1k — PostgreSQL security-master adapter for the MCP copilot search_symbols tool: SymbolSearchPort over an injected executor in libs/research/src/mcp/adapters/postgres-symbol-search.ts (as-of-cutoff ticker resolution, parameterized SQL, no new deps)
This commit is contained in:
parent
a44815fa87
commit
4e4be190df
5 changed files with 1224 additions and 0 deletions
|
|
@ -256,6 +256,14 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text.
|
||||
- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`.
|
||||
|
||||
### PostgreSQL Symbol Search Adapter
|
||||
|
||||
- **`createPostgresSymbolSearchPort({ executor, schema? })`** (exported from `@stock-bot/research/mcp` alongside `SymbolSearchExecutor` and `PostgresSymbolSearchError`) implements `SymbolSearchPort` over the M1 PostgreSQL security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`) in one read-only parameterized `SELECT` with zero runtime `pg` dependency.
|
||||
- **Inputs & schema:** Validates that `executor` exposes a callable `query(text, params?)` method (`INVALID_EXECUTOR`), validates optional `schema` against `^[a-z_][a-z0-9_]*$` before quoting table identifiers (`INVALID_SCHEMA`; defaults to the executor's `search_path`), validates `q.vaultCutoffTs` (epoch milliseconds) and converts it to a UTC calendar date (`YYYY-MM-DD`), escapes `%`, `_`, and `\` before building the `ILIKE` pattern, and rejects malformed/non-integer IDs or invalid/impossible `YYYY-MM-DD` dates returned by the executor (`INVALID_ROW`).
|
||||
- **As-of ticker resolution & root suppression:** Excludes listings with `listed_from > cutoff` (retaining `listed_from IS NULL`). Defines `root_is_future` per listing when `listing_symbol_history` has at least one row with `upper(ticker) = upper(listing.ticker_root)` and none with `valid_from <= cutoff`. Resolves one ticker per listing (breaking same-`valid_from` ties by `ticker ASC`) in strict order: (1) latest history row valid at cutoff (`valid_from <= cutoff AND (valid_to IS NULL OR valid_to >= cutoff)`), (2) `listing.ticker_root` when `NOT root_is_future`, (3) latest history row with `valid_from <= cutoff` even if its `valid_to < cutoff`, (4) otherwise excludes the listing so future tickers never leak via fallback or name/ISIN lookup.
|
||||
- **`delistedAt` derivation:** Projects `delistedAt` as `listing.listed_to` (`YYYY-MM-DD`) when `delist_reason IS NOT NULL AND delist_reason <> 'active'`, else `null`. When `q.includeDelisted === false`, rows with non-null `delistedAt <= cutoff` are filtered out while future delistings (`delistedAt > cutoff`) remain eligible as of the cutoff.
|
||||
- **Port matching vs. MCP ranking:** The adapter matches on resolved as-of ticker (`ILIKE`), `listing.ticker_root` (`ILIKE`, gated by `NOT root_is_future`), `instrument.canonical_name` (`ILIKE`), or case-insensitive exact `instrument.primary_isin`, ignores `q.limit`, and returns all candidates ordered by `listing_id ASC`. When composed with `createSearchSymbolsTool`, the MCP tool applies Vault clamping/masking, ranks by exact ticker > ticker prefix > company name substring (tie-breaking by `listingId ASC`), and truncates to `limit` — so callers needing ticker-substring, root-only, or exact-ISIN lookups should call the port directly, while MCP tool callers should query by ticker or company name.
|
||||
|
||||
### Copilot Server
|
||||
|
||||
- **`createResearchCopilotMcpServer(options)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotMcpServerOptions` and the frozen `RESEARCH_COPILOT_TOOL_NAMES` tuple) composes all six research tools into one transport-agnostic `McpServer` in the fixed registration order `search_symbols`, `query_data`, `analyze_signal`, `event_study`, `file_finding`, `read_knowledge`. It accepts `name` and `version`, shared authoritative `store`, `vaultContext`, `ledger`, and `principalId`, plus the per-tool injected ports (`searchSymbols`, `eventStudy.resolveExchangeCalendars`, `fileFinding`, `readKnowledge`), fails closed on duplicate, missing, unexpected, or out-of-order tool names, and pairs directly with `runStdioServer(server, ...)` for headless newline-delimited JSON-RPC sessions.
|
||||
|
|
|
|||
355
libs/research/src/mcp/adapters/postgres-symbol-search.ts
Normal file
355
libs/research/src/mcp/adapters/postgres-symbol-search.ts
Normal file
|
|
@ -0,0 +1,355 @@
|
|||
/**
|
||||
* Read-only PostgreSQL security-master adapter implementing {@link SymbolSearchPort}
|
||||
* for the MCP copilot `search_symbols` tool.
|
||||
*
|
||||
* Dependency-free (no `pg`, no `node:*`, no bare `process`): SQL execution is
|
||||
* injected via {@link SymbolSearchExecutor}.
|
||||
*/
|
||||
|
||||
import type { SymbolSearchPort, SymbolSearchQuery, SymbolSearchRow } from '../tools/search-symbols';
|
||||
import { utcDateOf, validateVaultCutoffTs } from '../tools/vault-fenced-input';
|
||||
|
||||
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
|
||||
const CALENDAR_DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const DAYS_IN_MONTH: readonly number[] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
||||
|
||||
/** Error codes thrown by {@link PostgresSymbolSearchError}. */
|
||||
export type PostgresSymbolSearchErrorCode =
|
||||
| 'INVALID_EXECUTOR'
|
||||
| 'INVALID_SCHEMA'
|
||||
| 'INVALID_ROW';
|
||||
|
||||
/** Typed validation error thrown by the PostgreSQL symbol-search adapter. */
|
||||
export class PostgresSymbolSearchError extends RangeError {
|
||||
readonly code: PostgresSymbolSearchErrorCode;
|
||||
|
||||
constructor(code: PostgresSymbolSearchErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = 'PostgresSymbolSearchError';
|
||||
this.code = code;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Structural `pg.Pool` / `pg.PoolClient`-compatible query interface so this module
|
||||
* has no runtime dependency on `pg` and is unit-testable with a fake executor.
|
||||
*/
|
||||
export interface SymbolSearchExecutor {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }>;
|
||||
}
|
||||
|
||||
/** Factory options for {@link createPostgresSymbolSearchPort}. */
|
||||
export interface PostgresSymbolSearchPortOptions {
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
/** Optional PostgreSQL schema name (`^[a-z_][a-z0-9_]*$`); defaults to the executor's `search_path`. */
|
||||
readonly schema?: string;
|
||||
}
|
||||
|
||||
interface RawSymbolSearchRow {
|
||||
readonly listing_id: unknown;
|
||||
readonly instrument_id: unknown;
|
||||
readonly ticker: unknown;
|
||||
readonly class_suffix: unknown;
|
||||
readonly name: unknown;
|
||||
readonly mic: unknown;
|
||||
readonly currency: unknown;
|
||||
readonly isin: unknown;
|
||||
readonly first_bar_date: unknown;
|
||||
readonly last_bar_date: unknown;
|
||||
readonly delisted_at: unknown;
|
||||
}
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
function daysInUtcMonth(year: number, monthIndex: number): number {
|
||||
if (monthIndex === 1 && isLeapYear(year)) {
|
||||
return 29;
|
||||
}
|
||||
return DAYS_IN_MONTH[monthIndex] ?? 0;
|
||||
}
|
||||
|
||||
function isValidCalendarDate(value: unknown): value is string {
|
||||
if (typeof value !== 'string') {
|
||||
return false;
|
||||
}
|
||||
const match = CALENDAR_DATE_RE.exec(value);
|
||||
if (match === null) {
|
||||
return false;
|
||||
}
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (month < 1 || month > 12) {
|
||||
return false;
|
||||
}
|
||||
return day >= 1 && day <= daysInUtcMonth(year, month - 1);
|
||||
}
|
||||
|
||||
function escapeLikePattern(value: string): string {
|
||||
return value.replace(/[\\%_]/g, '\\$&');
|
||||
}
|
||||
|
||||
function quoteTable(schemaPrefix: string, table: string): string {
|
||||
return `${schemaPrefix}${table}`;
|
||||
}
|
||||
|
||||
function buildSearchSymbolsSql(schemaPrefix: string): string {
|
||||
const listingTable = quoteTable(schemaPrefix, 'listing');
|
||||
const instrumentTable = quoteTable(schemaPrefix, 'instrument');
|
||||
const exchangeTable = quoteTable(schemaPrefix, 'exchange');
|
||||
const historyTable = quoteTable(schemaPrefix, 'listing_symbol_history');
|
||||
|
||||
return [
|
||||
'SELECT',
|
||||
' l.listing_id AS listing_id,',
|
||||
' l.instrument_id AS instrument_id,',
|
||||
' resolved.ticker AS ticker,',
|
||||
" NULLIF(l.class_suffix, '') AS class_suffix,",
|
||||
' i.canonical_name AS name,',
|
||||
' l.mic AS mic,',
|
||||
' btrim(l.currency) AS currency,',
|
||||
" NULLIF(btrim(i.primary_isin), '') AS isin,",
|
||||
" to_char(l.listed_from, 'YYYY-MM-DD') AS first_bar_date,",
|
||||
" to_char(l.listed_to, 'YYYY-MM-DD') AS last_bar_date,",
|
||||
" to_char(delisted.delisted_at, 'YYYY-MM-DD') AS delisted_at",
|
||||
`FROM ${listingTable} l`,
|
||||
`INNER JOIN ${instrumentTable} i ON i.instrument_id = l.instrument_id`,
|
||||
`INNER JOIN ${exchangeTable} e ON e.mic = l.mic`,
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT (',
|
||||
' EXISTS (',
|
||||
' SELECT 1',
|
||||
` FROM ${historyTable} h_any`,
|
||||
' WHERE h_any.listing_id = l.listing_id',
|
||||
' AND upper(h_any.ticker) = upper(l.ticker_root)',
|
||||
' )',
|
||||
' AND NOT EXISTS (',
|
||||
' SELECT 1',
|
||||
` FROM ${historyTable} h_past`,
|
||||
' WHERE h_past.listing_id = l.listing_id',
|
||||
' AND upper(h_past.ticker) = upper(l.ticker_root)',
|
||||
' AND h_past.valid_from <= $1::date',
|
||||
' )',
|
||||
' ) AS is_future',
|
||||
') root_state',
|
||||
'LEFT JOIN LATERAL (',
|
||||
' SELECT h.ticker',
|
||||
` FROM ${historyTable} h`,
|
||||
' WHERE h.listing_id = l.listing_id',
|
||||
' AND h.valid_from <= $1::date',
|
||||
' AND (h.valid_to IS NULL OR h.valid_to >= $1::date)',
|
||||
' ORDER BY h.valid_from DESC, h.ticker ASC',
|
||||
' LIMIT 1',
|
||||
') hist_active ON TRUE',
|
||||
'LEFT JOIN LATERAL (',
|
||||
' SELECT h.ticker',
|
||||
` FROM ${historyTable} h`,
|
||||
' WHERE h.listing_id = l.listing_id',
|
||||
' AND h.valid_from <= $1::date',
|
||||
' ORDER BY h.valid_from DESC, h.ticker ASC',
|
||||
' LIMIT 1',
|
||||
') hist_prior ON TRUE',
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT CASE',
|
||||
' WHEN hist_active.ticker IS NOT NULL THEN hist_active.ticker',
|
||||
' WHEN NOT root_state.is_future THEN l.ticker_root',
|
||||
' ELSE hist_prior.ticker',
|
||||
' END AS ticker',
|
||||
') resolved',
|
||||
'CROSS JOIN LATERAL (',
|
||||
' SELECT CASE',
|
||||
" WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to",
|
||||
' ELSE NULL',
|
||||
' END AS delisted_at',
|
||||
') delisted',
|
||||
'WHERE (l.listed_from IS NULL OR l.listed_from <= $1::date)',
|
||||
' AND resolved.ticker IS NOT NULL',
|
||||
" AND resolved.ticker <> ''",
|
||||
' AND ($4::text IS NULL OR btrim(e.country_iso) = $4::text)',
|
||||
' AND ($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)',
|
||||
' AND (',
|
||||
" resolved.ticker ILIKE $2::text ESCAPE '\\'",
|
||||
" OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')",
|
||||
" OR i.canonical_name ILIKE $2::text ESCAPE '\\'",
|
||||
' OR (i.primary_isin IS NOT NULL AND upper(btrim(i.primary_isin)) = upper($3::text))',
|
||||
' )',
|
||||
'ORDER BY l.listing_id ASC',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function parseSafeInt(value: unknown, field: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a safe integer.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseNonEmptyString(value: unknown, field: string): string {
|
||||
if (typeof value !== 'string' || value.trim().length === 0) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a non-empty string.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseNullableClassSuffix(value: unknown): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: "class_suffix" must be a string or null.'
|
||||
);
|
||||
}
|
||||
return value === '' ? null : value;
|
||||
}
|
||||
|
||||
function parseNullableIsin(value: unknown): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value !== 'string') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: "isin" must be a string or null.'
|
||||
);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
return trimmed === '' ? null : trimmed;
|
||||
}
|
||||
|
||||
function parseNullableDate(value: unknown, field: string): string | null {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
if (!isValidCalendarDate(value)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
`Invalid security-master row: "${field}" must be a valid YYYY-MM-DD calendar date or null.`
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function mapRawRow(raw: unknown): SymbolSearchRow {
|
||||
if (typeof raw !== 'object' || raw === null) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid security-master row: expected a non-null object.'
|
||||
);
|
||||
}
|
||||
|
||||
const row = raw as RawSymbolSearchRow;
|
||||
const listingId = parseSafeInt(row.listing_id, 'listing_id');
|
||||
const instrumentId = parseSafeInt(row.instrument_id, 'instrument_id');
|
||||
const ticker = parseNonEmptyString(row.ticker, 'ticker');
|
||||
const classSuffix = parseNullableClassSuffix(row.class_suffix);
|
||||
const name = parseNonEmptyString(row.name, 'name');
|
||||
const mic = parseNonEmptyString(row.mic, 'mic');
|
||||
const currency = parseNonEmptyString(row.currency, 'currency').trim();
|
||||
const isin = parseNullableIsin(row.isin);
|
||||
const firstBarDate = parseNullableDate(row.first_bar_date, 'first_bar_date');
|
||||
const lastBarDate = parseNullableDate(row.last_bar_date, 'last_bar_date');
|
||||
const delistedAt = parseNullableDate(row.delisted_at, 'delisted_at');
|
||||
|
||||
return {
|
||||
listingId,
|
||||
instrumentId,
|
||||
ticker,
|
||||
classSuffix,
|
||||
name,
|
||||
mic,
|
||||
currency,
|
||||
isin,
|
||||
firstBarDate,
|
||||
lastBarDate,
|
||||
delistedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function validateFactoryOptions(options: PostgresSymbolSearchPortOptions): {
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
readonly schemaPrefix: string;
|
||||
} {
|
||||
if (typeof options !== 'object' || options === null) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_EXECUTOR',
|
||||
'Invalid options: expected an object with a SymbolSearchExecutor.'
|
||||
);
|
||||
}
|
||||
|
||||
const { executor, schema } = options;
|
||||
if (typeof executor !== 'object' || executor === null || typeof executor.query !== 'function') {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_EXECUTOR',
|
||||
'Invalid executor: expected an object with a callable query(text, params?) method.'
|
||||
);
|
||||
}
|
||||
|
||||
if (schema === undefined) {
|
||||
return { executor, schemaPrefix: '' };
|
||||
}
|
||||
|
||||
if (typeof schema !== 'string' || !SCHEMA_IDENT_RE.test(schema)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_SCHEMA',
|
||||
'Invalid schema: expected an identifier matching ^[a-z_][a-z0-9_]*$.'
|
||||
);
|
||||
}
|
||||
|
||||
return { executor, schemaPrefix: `"${schema}".` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only PostgreSQL {@link SymbolSearchPort} backed by the M1
|
||||
* security master (`listing`, `instrument`, `exchange`, `listing_symbol_history`).
|
||||
*/
|
||||
export function createPostgresSymbolSearchPort(
|
||||
options: PostgresSymbolSearchPortOptions
|
||||
): SymbolSearchPort {
|
||||
const { executor, schemaPrefix } = validateFactoryOptions(options);
|
||||
const sql = buildSearchSymbolsSql(schemaPrefix);
|
||||
|
||||
return {
|
||||
async searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]> {
|
||||
const cutoffTs = validateVaultCutoffTs(q.vaultCutoffTs);
|
||||
const cutoffDate = utcDateOf(cutoffTs);
|
||||
const ilikePattern = `%${escapeLikePattern(q.query)}%`;
|
||||
const country = q.country ?? null;
|
||||
const includeDelisted = q.includeDelisted;
|
||||
|
||||
const result = await executor.query<RawSymbolSearchRow>(sql, [
|
||||
cutoffDate,
|
||||
ilikePattern,
|
||||
q.query,
|
||||
country,
|
||||
includeDelisted,
|
||||
]);
|
||||
|
||||
if (typeof result !== 'object' || result === null || !Array.isArray(result.rows)) {
|
||||
throw new PostgresSymbolSearchError(
|
||||
'INVALID_ROW',
|
||||
'Invalid executor response: expected an object with a rows array.'
|
||||
);
|
||||
}
|
||||
|
||||
const mapped: SymbolSearchRow[] = [];
|
||||
for (let i = 0; i < result.rows.length; i += 1) {
|
||||
mapped.push(mapRawRow(result.rows[i]));
|
||||
}
|
||||
return mapped;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1,3 +1,4 @@
|
|||
export * from './adapters/postgres-symbol-search';
|
||||
export * from './copilot-server';
|
||||
export * from './protocol';
|
||||
export * from './server';
|
||||
|
|
|
|||
413
libs/research/test/mcp-postgres-symbol-search.test.ts
Normal file
413
libs/research/test/mcp-postgres-symbol-search.test.ts
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { MarketDataStoreValidationError } from '../src/market-data-store';
|
||||
import {
|
||||
PostgresSymbolSearchError,
|
||||
type SymbolSearchExecutor,
|
||||
type SymbolSearchQuery,
|
||||
createPostgresSymbolSearchPort,
|
||||
} from '../src/mcp/index';
|
||||
|
||||
interface RecordedCall {
|
||||
readonly text: string;
|
||||
readonly params: readonly unknown[] | undefined;
|
||||
}
|
||||
|
||||
function createFakeExecutor(rows: readonly Record<string, unknown>[] = []): {
|
||||
readonly calls: RecordedCall[];
|
||||
readonly executor: SymbolSearchExecutor;
|
||||
} {
|
||||
const calls: RecordedCall[] = [];
|
||||
const executor: SymbolSearchExecutor = {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
params?: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Row[] }> {
|
||||
calls.push({ text, params });
|
||||
return { rows: rows as readonly Row[] };
|
||||
},
|
||||
};
|
||||
return { calls, executor };
|
||||
}
|
||||
|
||||
function makeRawRow(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
listing_id: 101,
|
||||
instrument_id: 1001,
|
||||
ticker: 'ACME',
|
||||
class_suffix: '',
|
||||
name: 'Acme Corporation',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD',
|
||||
isin: 'US0000001015',
|
||||
first_bar_date: '2018-01-02',
|
||||
last_bar_date: '2024-06-28',
|
||||
delisted_at: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const BASE_QUERY: SymbolSearchQuery = {
|
||||
query: 'ACME',
|
||||
limit: 20,
|
||||
includeDelisted: true,
|
||||
vaultCutoffTs: Date.UTC(2024, 5, 30, 0, 0, 0, 0), // 2024-06-30T00:00:00.000Z
|
||||
};
|
||||
|
||||
describe('createPostgresSymbolSearchPort (fake executor)', () => {
|
||||
test('issues a single parameterized SELECT and never interpolates injection-shaped queries', async () => {
|
||||
const injection = "'; DROP TABLE listing; --";
|
||||
const fake = createFakeExecutor([makeRawRow()]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
query: injection,
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
const call = fake.calls[0]!;
|
||||
expect(call.text.trimStart().startsWith('SELECT')).toBe(true);
|
||||
expect(call.text).not.toContain(';');
|
||||
expect(call.text).not.toContain(injection);
|
||||
expect(call.text).not.toContain('DROP TABLE');
|
||||
expect(call.params).toEqual([
|
||||
'2024-06-30',
|
||||
`%${injection}%`,
|
||||
injection,
|
||||
null,
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
test('escapes %, _, and backslash literals in the ILIKE pattern while preserving raw query for ISIN', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
query: 'A%B_C\\D',
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(1);
|
||||
const call = fake.calls[0]!;
|
||||
expect(call.text).toContain("ESCAPE '\\'");
|
||||
expect(call.params).toEqual([
|
||||
'2024-06-30',
|
||||
'%A\\%B\\_C\\\\D%',
|
||||
'A%B_C\\D',
|
||||
null,
|
||||
true,
|
||||
]);
|
||||
});
|
||||
|
||||
test('converts vaultCutoffTs epoch-ms to UTC calendar date across midnight boundaries', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
vaultCutoffTs: Date.UTC(2024, 5, 30, 23, 59, 59, 999),
|
||||
});
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
vaultCutoffTs: Date.UTC(2024, 6, 1, 0, 0, 0, 0),
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.params?.[0]).toBe('2024-06-30');
|
||||
expect(fake.calls[1]!.params?.[0]).toBe('2024-07-01');
|
||||
});
|
||||
|
||||
test('binds optional country filter and both includeDelisted flags', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
country: 'CA',
|
||||
includeDelisted: false,
|
||||
});
|
||||
await port.searchSymbols({
|
||||
...BASE_QUERY,
|
||||
country: 'US',
|
||||
includeDelisted: true,
|
||||
});
|
||||
|
||||
expect(fake.calls).toHaveLength(2);
|
||||
expect(fake.calls[0]!.params?.[3]).toBe('CA');
|
||||
expect(fake.calls[0]!.params?.[4]).toBe(false);
|
||||
expect(fake.calls[1]!.params?.[3]).toBe('US');
|
||||
expect(fake.calls[1]!.params?.[4]).toBe(true);
|
||||
});
|
||||
|
||||
test('ignores q.limit in SQL and returns all candidates without truncation', async () => {
|
||||
const rows = [
|
||||
makeRawRow({ listing_id: 1, instrument_id: 10, ticker: 'AA' }),
|
||||
makeRawRow({ listing_id: 2, instrument_id: 20, ticker: 'AAB' }),
|
||||
makeRawRow({ listing_id: 3, instrument_id: 30, ticker: 'AAC' }),
|
||||
];
|
||||
const fake = createFakeExecutor(rows);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
const r1 = await port.searchSymbols({ ...BASE_QUERY, limit: 1 });
|
||||
const r2 = await port.searchSymbols({ ...BASE_QUERY, limit: 100 });
|
||||
|
||||
expect(r1).toHaveLength(3);
|
||||
expect(r2).toHaveLength(3);
|
||||
expect(fake.calls[0]!.text).toBe(fake.calls[1]!.text);
|
||||
expect(fake.calls[0]!.params).toEqual(fake.calls[1]!.params);
|
||||
// Outer query has ORDER BY listing_id ASC with no outer LIMIT clause
|
||||
expect(fake.calls[0]!.text.trimEnd().endsWith('ORDER BY l.listing_id ASC')).toBe(true);
|
||||
});
|
||||
|
||||
test('gates ticker_root fallback and matching on cutoff-aware history suppression and derives delisted_at', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await port.searchSymbols(BASE_QUERY);
|
||||
|
||||
const sql = fake.calls[0]!.text;
|
||||
// Root-suppression subquery checks upper(ticker) = upper(ticker_root) and cutoff $1::date
|
||||
expect(sql).toContain('upper(h_any.ticker) = upper(l.ticker_root)');
|
||||
expect(sql).toContain('upper(h_past.ticker) = upper(l.ticker_root)');
|
||||
expect(sql).toContain('h_past.valid_from <= $1::date');
|
||||
// Both fallback resolution and root ILIKE predicate are gated by NOT root_state.is_future
|
||||
expect(sql).toContain('WHEN NOT root_state.is_future THEN l.ticker_root');
|
||||
expect(sql).toContain("OR (NOT root_state.is_future AND l.ticker_root ILIKE $2::text ESCAPE '\\')");
|
||||
// delisted_at derivation and $5 filter
|
||||
expect(sql).toContain("WHEN l.delist_reason IS NOT NULL AND l.delist_reason <> 'active' THEN l.listed_to");
|
||||
expect(sql).toContain('($5::boolean OR delisted.delisted_at IS NULL OR delisted.delisted_at > $1::date)');
|
||||
});
|
||||
|
||||
test('quotes optional validated schema on all security-master tables and omits prefix when unset', async () => {
|
||||
const fakeDefault = createFakeExecutor([]);
|
||||
const defaultPort = createPostgresSymbolSearchPort({ executor: fakeDefault.executor });
|
||||
await defaultPort.searchSymbols(BASE_QUERY);
|
||||
expect(fakeDefault.calls[0]!.text).toContain('FROM listing l');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN instrument i');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('INNER JOIN exchange e');
|
||||
expect(fakeDefault.calls[0]!.text).toContain('FROM listing_symbol_history');
|
||||
|
||||
const fakeScoped = createFakeExecutor([]);
|
||||
const scopedPort = createPostgresSymbolSearchPort({
|
||||
executor: fakeScoped.executor,
|
||||
schema: 'custom_master_1',
|
||||
});
|
||||
await scopedPort.searchSymbols(BASE_QUERY);
|
||||
expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing l');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".instrument i');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('INNER JOIN "custom_master_1".exchange e');
|
||||
expect(fakeScoped.calls[0]!.text).toContain('FROM "custom_master_1".listing_symbol_history');
|
||||
});
|
||||
|
||||
test('maps raw rows into SymbolSearchRow with classSuffix, ISIN trimming, nullable dates, and delistedAt', async () => {
|
||||
const fake = createFakeExecutor([
|
||||
makeRawRow({
|
||||
listing_id: 101,
|
||||
instrument_id: 501,
|
||||
ticker: 'ACME',
|
||||
class_suffix: '',
|
||||
name: 'Acme Corp',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD ',
|
||||
isin: ' US0000001015 ',
|
||||
first_bar_date: '2020-02-29',
|
||||
last_bar_date: '2024-06-28',
|
||||
delisted_at: null,
|
||||
}),
|
||||
makeRawRow({
|
||||
listing_id: 102,
|
||||
instrument_id: 502,
|
||||
ticker: 'BRK',
|
||||
class_suffix: 'B',
|
||||
name: 'Berkshire Example',
|
||||
mic: 'XNYS',
|
||||
currency: 'USD',
|
||||
isin: ' ',
|
||||
first_bar_date: null,
|
||||
last_bar_date: '2023-12-15',
|
||||
delisted_at: '2023-12-15',
|
||||
}),
|
||||
makeRawRow({
|
||||
listing_id: 103,
|
||||
instrument_id: 503,
|
||||
ticker: 'NULLY',
|
||||
class_suffix: null,
|
||||
name: 'Nullable Fields Co',
|
||||
mic: 'XTSE',
|
||||
currency: 'CAD',
|
||||
isin: null,
|
||||
first_bar_date: null,
|
||||
last_bar_date: null,
|
||||
delisted_at: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
const rows = await port.searchSymbols(BASE_QUERY);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
listingId: 101,
|
||||
instrumentId: 501,
|
||||
ticker: 'ACME',
|
||||
classSuffix: null,
|
||||
name: 'Acme Corp',
|
||||
mic: 'XNAS',
|
||||
currency: 'USD',
|
||||
isin: 'US0000001015',
|
||||
firstBarDate: '2020-02-29',
|
||||
lastBarDate: '2024-06-28',
|
||||
delistedAt: null,
|
||||
},
|
||||
{
|
||||
listingId: 102,
|
||||
instrumentId: 502,
|
||||
ticker: 'BRK',
|
||||
classSuffix: 'B',
|
||||
name: 'Berkshire Example',
|
||||
mic: 'XNYS',
|
||||
currency: 'USD',
|
||||
isin: null,
|
||||
firstBarDate: null,
|
||||
lastBarDate: '2023-12-15',
|
||||
delistedAt: '2023-12-15',
|
||||
},
|
||||
{
|
||||
listingId: 103,
|
||||
instrumentId: 503,
|
||||
ticker: 'NULLY',
|
||||
classSuffix: null,
|
||||
name: 'Nullable Fields Co',
|
||||
mic: 'XTSE',
|
||||
currency: 'CAD',
|
||||
isin: null,
|
||||
firstBarDate: null,
|
||||
lastBarDate: null,
|
||||
delistedAt: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects invalid executors and options with INVALID_EXECUTOR before any query', () => {
|
||||
const invalidOptions: unknown[] = [
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
{ executor: null },
|
||||
{ executor: {} },
|
||||
{ executor: { query: 'not-a-fn' } },
|
||||
];
|
||||
|
||||
for (const opts of invalidOptions) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresSymbolSearchPort(opts as Parameters<typeof createPostgresSymbolSearchPort>[0]);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_EXECUTOR');
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid schema names with INVALID_SCHEMA before any query', () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const badSchemas: unknown[] = [
|
||||
'',
|
||||
'Public',
|
||||
'1schema',
|
||||
'bad-name',
|
||||
'bad.name',
|
||||
'public"; DROP TABLE listing; --',
|
||||
'space name',
|
||||
123,
|
||||
null,
|
||||
];
|
||||
|
||||
for (const schema of badSchemas) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createPostgresSymbolSearchPort({
|
||||
executor: fake.executor,
|
||||
schema: schema as string,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_SCHEMA');
|
||||
}
|
||||
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('rejects invalid vaultCutoffTs before executing any query', async () => {
|
||||
const fake = createFakeExecutor([]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
await expect(
|
||||
port.searchSymbols({ ...BASE_QUERY, vaultCutoffTs: Number.NaN })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(fake.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('rejects malformed rows (fractional/unsafe IDs, malformed/impossible dates, invalid types) with INVALID_ROW', async () => {
|
||||
const badRows: readonly Record<string, unknown>[] = [
|
||||
makeRawRow({ listing_id: 1.5 }),
|
||||
makeRawRow({ listing_id: Number.MAX_SAFE_INTEGER + 1 }),
|
||||
makeRawRow({ listing_id: '101' }),
|
||||
makeRawRow({ listing_id: Number.NaN }),
|
||||
makeRawRow({ instrument_id: 2.25 }),
|
||||
makeRawRow({ instrument_id: Number.POSITIVE_INFINITY }),
|
||||
makeRawRow({ ticker: '' }),
|
||||
makeRawRow({ ticker: null }),
|
||||
makeRawRow({ name: '' }),
|
||||
makeRawRow({ mic: null }),
|
||||
makeRawRow({ currency: '' }),
|
||||
makeRawRow({ class_suffix: 42 }),
|
||||
makeRawRow({ isin: 12345 }),
|
||||
makeRawRow({ first_bar_date: '2024-6-1' }),
|
||||
makeRawRow({ first_bar_date: '2023-02-29' }),
|
||||
makeRawRow({ last_bar_date: '2024-02-30' }),
|
||||
makeRawRow({ last_bar_date: '2024-13-01' }),
|
||||
makeRawRow({ delisted_at: '2024-06-30T00:00:00Z' }),
|
||||
makeRawRow({ delisted_at: new Date('2024-06-30T00:00:00Z') }),
|
||||
];
|
||||
|
||||
for (const badRow of badRows) {
|
||||
const fake = createFakeExecutor([badRow]);
|
||||
const port = createPostgresSymbolSearchPort({ executor: fake.executor });
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.searchSymbols(BASE_QUERY);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(PostgresSymbolSearchError);
|
||||
expect((caught as PostgresSymbolSearchError).code).toBe('INVALID_ROW');
|
||||
}
|
||||
|
||||
// Non-object row / invalid result shape
|
||||
const nullRowExecutor: SymbolSearchExecutor = {
|
||||
async query<Row = Record<string, unknown>>() {
|
||||
return { rows: [null as unknown as Row] };
|
||||
},
|
||||
};
|
||||
const portNullRow = createPostgresSymbolSearchPort({ executor: nullRowExecutor });
|
||||
await expect(portNullRow.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf(
|
||||
PostgresSymbolSearchError
|
||||
);
|
||||
|
||||
const badResultExecutor: SymbolSearchExecutor = {
|
||||
async query() {
|
||||
return { rows: 'not-an-array' as unknown as readonly never[] };
|
||||
},
|
||||
};
|
||||
const portBadResult = createPostgresSymbolSearchPort({ executor: badResultExecutor });
|
||||
await expect(portBadResult.searchSymbols(BASE_QUERY)).rejects.toBeInstanceOf(
|
||||
PostgresSymbolSearchError
|
||||
);
|
||||
});
|
||||
});
|
||||
447
test/postgres/mcp-symbol-search-adapter.test.ts
Normal file
447
test/postgres/mcp-symbol-search-adapter.test.ts
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
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();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue