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:
Studio 2026-12-02 08:49:30 -05:00
parent a44815fa87
commit 4e4be190df
5 changed files with 1224 additions and 0 deletions

View 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;
},
};
}

View file

@ -1,3 +1,4 @@
export * from './adapters/postgres-symbol-search';
export * from './copilot-server';
export * from './protocol';
export * from './server';