T-134: M2.1d — MCP copilot search_symbols tool: vault-safe security-master symbol lookup via an injected SymbolSearchPort in libs/research/src/mcp/tools/

This commit is contained in:
Studio 2026-12-01 06:06:38 -05:00
parent f0f55acef2
commit 857eedf379
3 changed files with 1044 additions and 0 deletions

View file

@ -4,3 +4,4 @@ export * from './stdio';
export * from './tools/analyze-signal';
export * from './tools/event-study';
export * from './tools/query-data';
export * from './tools/search-symbols';

View file

@ -0,0 +1,356 @@
import { z } from 'zod';
import { MarketDataStoreValidationError, type VaultFenceContext } from '../../market-data-store';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
import { utcDateOf, validateVaultCutoffTs } from './vault-fenced-input';
/** Default maximum number of matching listings returned by `search_symbols`. */
export const SEARCH_SYMBOLS_DEFAULT_LIMIT = 20;
/** Hard maximum number of matching listings returned by `search_symbols`. */
export const SEARCH_SYMBOLS_MAX_LIMIT = 100;
/** Hard maximum character length of a trimmed `search_symbols` query string. */
export const SEARCH_SYMBOLS_MAX_QUERY_LENGTH = 64;
/** Supported exchange country filters for `search_symbols`. */
export const SEARCH_SYMBOLS_COUNTRIES = ['US', 'CA'] as const;
export type SymbolSearchCountry = (typeof SEARCH_SYMBOLS_COUNTRIES)[number];
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];
/**
* Security-master projection returned by {@link SymbolSearchPort} and emitted
* (after Vault fencing) by the `search_symbols` MCP tool.
*
* Field provenance (M1 security master DDL / `design/DATA-CONTRACTS.md`):
* - `listingId`: `listing.listing_id` (`INT32`)
* - `instrumentId`: `listing.instrument_id` / `instrument.instrument_id` (`INT32`)
* - `ticker`: `listing_symbol_history.ticker` valid as of the Vault cutoff
* - `classSuffix`: nullable `listing.class_suffix`
* - `name`: `instrument.canonical_name`
* - `mic`: `listing.mic`
* - `currency`: `listing.currency`
* - `isin`: nullable `instrument.primary_isin`
* - `firstBarDate`: nullable `YYYY-MM-DD` observed bar span start (`listing.listed_from`)
* - `lastBarDate`: nullable `YYYY-MM-DD` observed bar span end (`listing.listed_to`)
* - `delistedAt`: nullable `YYYY-MM-DD` confirmed delisting date (distinct from `lastBarDate`)
*/
export interface SymbolSearchRow {
readonly listingId: number;
readonly instrumentId: number;
readonly ticker: string;
readonly classSuffix: string | null;
readonly name: string;
readonly mic: string;
readonly currency: string;
readonly isin: string | null;
readonly firstBarDate: string | null;
readonly lastBarDate: string | null;
readonly delistedAt: string | null;
}
/**
* Query passed to {@link SymbolSearchPort.searchSymbols}.
*
* Port contract:
* - Return all matching candidates for tool-side ranking and Vault fencing;
* treat `limit` as a hint only (never truncate ahead of exact-ticker matches).
* - Resolve symbol identities and matches as of `vaultCutoffTs` so future
* renames or delistings do not leak into research queries.
* - Include listings whose `firstBarDate` is unknown (`null`).
* - The tool always passes `includeDelisted: true` to the port so current
* delisting status cannot drop a candidate before Vault cutoff masking.
*/
export interface SymbolSearchQuery {
readonly query: string;
readonly limit: number;
readonly country?: SymbolSearchCountry;
readonly includeDelisted: boolean;
readonly vaultCutoffTs: number;
}
/** Read-only security-master symbol lookup port injected into `createSearchSymbolsTool`. */
export interface SymbolSearchPort {
searchSymbols(q: SymbolSearchQuery): Promise<readonly SymbolSearchRow[]>;
}
/**
* Strict Zod input schema for the `search_symbols` MCP tool.
*
* Intentionally omits `scope`, `vault_evaluation_only`, and `vaultCutoffTs`;
* `.strict()` rejects any unknown keys.
*/
export const searchSymbolsInputSchema = z
.object({
query: z
.string()
.trim()
.min(1)
.max(SEARCH_SYMBOLS_MAX_QUERY_LENGTH)
.describe(
`Ticker symbol or company name search query (trimmed, 1–${SEARCH_SYMBOLS_MAX_QUERY_LENGTH} characters).`
),
limit: z
.number()
.int()
.min(1)
.max(SEARCH_SYMBOLS_MAX_LIMIT)
.default(SEARCH_SYMBOLS_DEFAULT_LIMIT)
.describe(
`Maximum number of matching listings to return (default ${SEARCH_SYMBOLS_DEFAULT_LIMIT}, max ${SEARCH_SYMBOLS_MAX_LIMIT}).`
),
country: z
.enum(SEARCH_SYMBOLS_COUNTRIES)
.optional()
.describe('Optional exchange country filter (US or CA).'),
includeDelisted: z
.boolean()
.default(true)
.describe('Include delisted listings as of the Vault cutoff (default true).'),
})
.strict();
export type SearchSymbolsInput = z.infer<typeof searchSymbolsInputSchema>;
/** Server-side injected configuration for {@link createSearchSymbolsTool}. */
export interface SearchSymbolsToolOptions {
readonly port: SymbolSearchPort;
readonly vaultContext: Pick<VaultFenceContext, 'vaultCutoffTs'>;
}
/** Structured JSON payload serialized into the `search_symbols` MCP text result. */
export interface SearchSymbolsResultPayload {
readonly scope: 'vault_fenced';
readonly vaultCutoffTs: number;
readonly rowCount: number;
readonly truncated: boolean;
readonly rows: readonly SymbolSearchRow[];
}
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 validateNullableDate(value: unknown, field: string): string | null {
if (value === null) {
return null;
}
if (!isValidCalendarDate(value)) {
throw new Error(`Invalid port date for "${field}".`);
}
return value;
}
function validateNullableString(value: unknown, field: string): string | null {
if (value === null) {
return null;
}
if (typeof value !== 'string') {
throw new Error(`Invalid port string for "${field}".`);
}
return value;
}
function validateRequiredString(value: unknown, field: string): string {
if (typeof value !== 'string') {
throw new Error(`Invalid port string for "${field}".`);
}
return value;
}
function validateSafeInteger(value: unknown, field: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new Error(`Invalid port integer for "${field}".`);
}
return value;
}
function fenceAndProjectRow(
raw: SymbolSearchRow,
vaultCutoffDate: string,
includeDelisted: boolean
): SymbolSearchRow | null {
if (typeof raw !== 'object' || raw === null) {
throw new Error('Invalid symbol search row returned by port.');
}
const listingId = validateSafeInteger(raw.listingId, 'listingId');
const instrumentId = validateSafeInteger(raw.instrumentId, 'instrumentId');
const ticker = validateRequiredString(raw.ticker, 'ticker');
const classSuffix = validateNullableString(raw.classSuffix, 'classSuffix');
const name = validateRequiredString(raw.name, 'name');
const mic = validateRequiredString(raw.mic, 'mic');
const currency = validateRequiredString(raw.currency, 'currency');
const isin = validateNullableString(raw.isin, 'isin');
const firstBarDate = validateNullableDate(raw.firstBarDate, 'firstBarDate');
const rawLastBarDate = validateNullableDate(raw.lastBarDate, 'lastBarDate');
const rawDelistedAt = validateNullableDate(raw.delistedAt, 'delistedAt');
if (firstBarDate !== null && firstBarDate > vaultCutoffDate) {
return null;
}
const lastBarDate =
rawLastBarDate !== null && rawLastBarDate > vaultCutoffDate ? vaultCutoffDate : rawLastBarDate;
const delistedAt =
rawDelistedAt !== null && rawDelistedAt > vaultCutoffDate ? null : rawDelistedAt;
if (!includeDelisted && delistedAt !== null) {
return null;
}
return {
listingId,
instrumentId,
ticker,
classSuffix,
name,
mic,
currency,
isin,
firstBarDate,
lastBarDate,
delistedAt,
};
}
function matchRank(row: SymbolSearchRow, normalizedQuery: string): number {
const normalizedTicker = row.ticker.toLowerCase();
if (normalizedTicker === normalizedQuery) {
return 0;
}
if (normalizedTicker.startsWith(normalizedQuery)) {
return 1;
}
if (row.name.toLowerCase().includes(normalizedQuery)) {
return 2;
}
return 3;
}
function validateFactoryOptions(options: SearchSymbolsToolOptions): number {
if (typeof options !== 'object' || options === null) {
throw new MarketDataStoreValidationError(
'Invalid `options`: expected a SearchSymbolsToolOptions object.',
'options'
);
}
if (
typeof options.port !== 'object' ||
options.port === null ||
typeof options.port.searchSymbols !== 'function'
) {
throw new MarketDataStoreValidationError(
'Invalid `port`: expected a SymbolSearchPort implementing `searchSymbols`.',
'port'
);
}
return validateVaultCutoffTs(options.vaultContext?.vaultCutoffTs);
}
/**
* Creates the Vault-fenced `search_symbols` MCP tool backed by an injected
* read-only {@link SymbolSearchPort}.
*
* Enforces `scope: 'vault_fenced'`, requests candidates with
* `includeDelisted: true` so current delisting status cannot hide listings that
* were active as of the Vault cutoff, drops post-cutoff listings, clamps
* `lastBarDate` and masks future `delistedAt` against the cutoff UTC calendar
* date, ranks deterministically (exact ticker > ticker prefix > company name,
* breaking ties by ascending `listingId`), and caps results at `limit`.
*/
export function createSearchSymbolsTool(options: SearchSymbolsToolOptions): McpToolEntry {
const vaultCutoffTs = validateFactoryOptions(options);
const vaultCutoffDate = utcDateOf(vaultCutoffTs);
const { port } = options;
return defineMcpTool({
name: 'search_symbols',
description:
'Search Vault-fenced security-master listings by ticker symbol or company name and return numeric listing IDs.',
inputSchema: searchSymbolsInputSchema,
async handler(input: SearchSymbolsInput): Promise<McpToolCallResult> {
const candidates = await port.searchSymbols({
query: input.query,
limit: input.limit,
...(input.country !== undefined ? { country: input.country } : {}),
includeDelisted: true,
vaultCutoffTs,
});
if (!Array.isArray(candidates)) {
throw new Error('Invalid symbol search response returned by port.');
}
const normalizedQuery = input.query.toLowerCase();
const eligible: { readonly row: SymbolSearchRow; readonly rank: number }[] = [];
for (let i = 0; i < candidates.length; i += 1) {
const fenced = fenceAndProjectRow(
candidates[i] as SymbolSearchRow,
vaultCutoffDate,
input.includeDelisted
);
if (fenced !== null) {
eligible.push({ row: fenced, rank: matchRank(fenced, normalizedQuery) });
}
}
eligible.sort((a, b) => {
if (a.rank !== b.rank) {
return a.rank - b.rank;
}
return a.row.listingId - b.row.listingId;
});
const truncated = eligible.length > input.limit;
const limitCount = truncated ? input.limit : eligible.length;
const rows: SymbolSearchRow[] = [];
for (let i = 0; i < limitCount; i += 1) {
rows.push((eligible[i] as { readonly row: SymbolSearchRow }).row);
}
const payload: SearchSymbolsResultPayload = {
scope: 'vault_fenced',
vaultCutoffTs,
rowCount: rows.length,
truncated,
rows,
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
},
});
}