diff --git a/libs/research/src/mcp/tools/query-data.ts b/libs/research/src/mcp/tools/query-data.ts index a336985e..5cfdc92a 100644 --- a/libs/research/src/mcp/tools/query-data.ts +++ b/libs/research/src/mcp/tools/query-data.ts @@ -10,6 +10,7 @@ import { } from '../../market-data-store'; import { AdjFactorsSnapshotError, + type AdjFactorsSnapshotErrorCode, MarketDataStoreNotImplementedError, } from '../../market-data-store-duckdb'; import type { McpToolCallResult } from '../protocol'; @@ -18,6 +19,9 @@ import { type McpToolEntry, defineMcpTool } from '../server'; const INT32_MIN = -2_147_483_648; const INT32_MAX = 2_147_483_647; const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000; +const MS_PER_DAY = 86_400_000; +const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/; +const ISO_FRACTIONAL_RE = /\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/; /** Default maximum number of bar rows returned by `query_data`. */ export const QUERY_DATA_DEFAULT_LIMIT = 500; @@ -109,39 +113,163 @@ export interface QueryDataResultPayload { readonly rows: readonly BarRecord[]; } +const SAFE_VALIDATION_FIELDS: ReadonlySet = new Set([ + 'from', + 'to', + 'asOf', + 'date', + 'ref', + 'listingIds', + 'timeframe', + 'adjustment', + 'scope', + 'limit', +]); + +const SAFE_STORE_METHODS: ReadonlySet = new Set([ + 'bars', + 'crossSection', + 'fundamentalsAsOf', + 'events', + 'shortsAsOf', + 'macroAsOf', + 'fx', + 'universe', +]); + +const ADJ_SNAPSHOT_ERROR_MESSAGES: Readonly> = { + missing_snapshot: + 'Adjusted bars require a verified point-in-time fenced adj_factors snapshot.', + missing_metadata: 'Required adj_factors snapshot metadata is missing.', + invalid_metadata: 'adj_factors snapshot metadata is invalid.', + unsupported_version: 'adj_factors snapshot metadata version is unsupported.', + retrospective_rejected: + 'Retrospective adj_factors snapshots are rejected for point-in-time queries.', + incompatible_fence: + 'adj_factors snapshot fence does not match the query asOf or Vault cutoff.', + path_mismatch: 'adj_factors snapshot metadata does not match the configured artifact.', + unpinned_mutable_path: + 'Adjusted bars require a pinned or immutable adj_factors snapshot artifact.', +}; + function utcDateOf(epochMs: number): string { return new Date(epochMs).toISOString().slice(0, 10); } -function formatUtcIsoMs(epochMs: number): string { - return new Date(epochMs).toISOString(); +function extractExplicitSubMsMicros(raw: string): number { + const match = ISO_FRACTIONAL_RE.exec(raw); + if (match === null) { + return 0; + } + const frac = match[1] ?? ''; + if (frac.length <= 3) { + return 0; + } + const microDigits = frac.slice(3, 6).padEnd(3, '0'); + return Number(microDigits); } -function formatDomainError(err: Error): McpToolCallResult { - const firstLine = err.message - .split(/\r?\n/, 1)[0] - ?.replace(/\s+at\s+\S.*$/u, '') - .trim(); - const detail = firstLine !== undefined && firstLine.length > 0 ? firstLine : 'Query failed.'; - return { - content: [ - { - type: 'text', - text: `${err.name}: ${detail}`, - }, - ], - isError: true, - }; +function resolveToSubMsMicros(rawTo: string, clampedTo: boolean): number { + if (clampedTo || DATE_ONLY_RE.test(rawTo)) { + return 999; + } + return extractExplicitSubMsMicros(rawTo); } -function isMappedStoreError(err: unknown): err is Error { - return ( - err instanceof VaultHoldoutFenceError || - err instanceof VaultScopeNotAuthorizedError || - err instanceof MarketDataStoreValidationError || - err instanceof MarketDataStoreNotImplementedError || - err instanceof AdjFactorsSnapshotError - ); +function resolveAsOfSubMsMicros(rawAsOf: string | undefined, clampedAsOf: boolean): number { + if (clampedAsOf || rawAsOf === undefined || DATE_ONLY_RE.test(rawAsOf)) { + return 999; + } + return extractExplicitSubMsMicros(rawAsOf); +} + +function formatUtcIsoWithMicros(epochMs: number, subMsMicros: number): string { + const isoMs = new Date(epochMs).toISOString(); + if (subMsMicros === 0) { + return isoMs; + } + const extra = String(subMsMicros).padStart(3, '0'); + return `${isoMs.slice(0, -1)}${extra}Z`; +} + +function resolveCompletedUtcDate(epochMs: number, subMsMicros: number): string { + const dayStartMs = Math.floor(epochMs / MS_PER_DAY) * MS_PER_DAY; + const dayEndMs = dayStartMs + MS_PER_DAY - 1; + if (epochMs === dayEndMs && subMsMicros === 999) { + return utcDateOf(dayStartMs); + } + return utcDateOf(dayStartMs - MS_PER_DAY); +} + +function resolveUniverseDate( + toMs: number, + toSubMs: number, + asOfMs: number, + asOfSubMs: number +): string { + if (asOfMs < toMs || (asOfMs === toMs && asOfSubMs < toSubMs)) { + return resolveCompletedUtcDate(asOfMs, asOfSubMs); + } + return resolveCompletedUtcDate(toMs, toSubMs); +} + +function formatMappedStoreError(err: unknown): McpToolCallResult | null { + if (err instanceof VaultHoldoutFenceError) { + return { + content: [ + { + type: 'text', + text: 'VaultHoldoutFenceError: Requested range reaches or exceeds the Vault holdout cutoff.', + }, + ], + isError: true, + }; + } + + if (err instanceof VaultScopeNotAuthorizedError) { + return { + content: [ + { + type: 'text', + text: "VaultScopeNotAuthorizedError: Data scope 'vault_evaluation_only' is not permitted through MCP.", + }, + ], + isError: true, + }; + } + + if (err instanceof MarketDataStoreValidationError) { + const text = + err.field !== undefined && SAFE_VALIDATION_FIELDS.has(err.field) + ? `MarketDataStoreValidationError: Invalid query parameter "${err.field}".` + : 'MarketDataStoreValidationError: Query parameters failed store validation.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof MarketDataStoreNotImplementedError) { + const text = SAFE_STORE_METHODS.has(err.method) + ? `MarketDataStoreNotImplementedError: Store operation "${err.method}" is not supported for this query.` + : 'MarketDataStoreNotImplementedError: Requested store operation is not supported.'; + return { + content: [{ type: 'text', text }], + isError: true, + }; + } + + if (err instanceof AdjFactorsSnapshotError) { + const detail = Object.prototype.hasOwnProperty.call(ADJ_SNAPSHOT_ERROR_MESSAGES, err.code) + ? ADJ_SNAPSHOT_ERROR_MESSAGES[err.code] + : 'Adjusted bars snapshot verification failed.'; + return { + content: [{ type: 'text', text: `AdjFactorsSnapshotError: ${detail}` }], + isError: true, + }; + } + + return null; } function validateFactoryOptions(options: QueryDataToolOptions): void { @@ -206,12 +334,20 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry ); const effectiveLimit = input.limit; + const toSubMs = resolveToSubMsMicros(input.to, fenced.clampedTo); + const asOfSubMs = resolveAsOfSubMsMicros(input.asOf, fenced.clampedAsOf); let listingIds: number[]; if (input.universe !== undefined) { + const universeDate = resolveUniverseDate( + fenced.toMs, + toSubMs, + fenced.asOfMs, + asOfSubMs + ); const resolved = await store.universe({ ref: input.universe, - date: utcDateOf(fenced.toMs), + date: universeDate, }); if (resolved.length === 0) { const emptyPayload: QueryDataResultPayload = { @@ -238,10 +374,12 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry listingIds = [...(input.listingIds ?? [])]; } - const effectiveFencedTo = fenced.clampedTo ? formatUtcIsoMs(fenced.toMs) : input.to; + const effectiveFencedTo = fenced.clampedTo + ? formatUtcIsoWithMicros(fenced.toMs, 999) + : input.to; const effectiveFencedAsOf = fenced.clampedAsOf || input.asOf === undefined - ? formatUtcIsoMs(fenced.asOfMs) + ? formatUtcIsoWithMicros(fenced.asOfMs, 999) : input.asOf; const stream = store.bars({ @@ -297,8 +435,9 @@ export function createQueryDataTool(options: QueryDataToolOptions): McpToolEntry content: [{ type: 'text', text: JSON.stringify(payload) }], }; } catch (err: unknown) { - if (isMappedStoreError(err)) { - return formatDomainError(err); + const mapped = formatMappedStoreError(err); + if (mapped !== null) { + return mapped; } throw err; } diff --git a/libs/research/test/mcp-protocol.test.ts b/libs/research/test/mcp-protocol.test.ts index eb312d45..511a8f7e 100644 --- a/libs/research/test/mcp-protocol.test.ts +++ b/libs/research/test/mcp-protocol.test.ts @@ -250,13 +250,15 @@ describe('MCP protocol & server core', () => { expect(result.content[0]?.text).toContain('Invalid arguments for tool "echo_count"'); }); - test('throwing tool handler returns isError: true with sanitized error and zero stack trace', async () => { + test('throwing tool handler returns isError: true with sanitized error and zero stack trace or paths', async () => { const boomTool = defineMcpTool({ name: 'explode', description: 'Always throws an error.', inputSchema: z.object({}).strict(), handler() { - const err = new Error('Simulated backend failure\n at secretInternal (/srv/app/secret.ts:42:9)'); + const err = new Error( + 'Failed reading /mnt/data/stockbot/secret.parquet\n at secretInternal (/srv/app/secret.ts:42:9)' + ); err.name = 'BackendFailureError'; throw err; }, @@ -286,12 +288,140 @@ describe('MCP protocol & server core', () => { }; expect(result.isError).toBe(true); const text = result.content[0]?.text ?? ''; - expect(text).toBe('BackendFailureError: Simulated backend failure'); + expect(text).toBe('BackendFailureError: Tool execution failed.'); + expect(text).not.toContain('/mnt/data/stockbot'); expect(text).not.toContain('at '); expect(text).not.toContain('/srv/app/secret.ts'); expect(text).not.toContain('\n'); }); + test('accepts standard MCP _meta.progressToken on requests and rejects malformed _meta', async () => { + let calls = 0; + const echoTool = defineMcpTool({ + name: 'echo_msg', + description: 'Echoes a message.', + inputSchema: z.object({ msg: z.string() }).strict(), + handler(input) { + calls += 1; + return { content: [{ type: 'text', text: input.msg }] }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [echoTool], + }); + + const initResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm1', + method: 'initialize', + params: { + protocolVersion: MCP_PROTOCOL_VERSION, + _meta: { progressToken: 'init-tok' }, + }, + }) + ) + ); + expect(initResp.error).toBeUndefined(); + + const pingResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm2', + method: 'ping', + params: { _meta: { progressToken: 42 } }, + }) + ) + ); + expect(pingResp.result).toEqual({}); + + const listResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm3', + method: 'tools/list', + params: { _meta: { progressToken: 'list-tok', customFlag: true } }, + }) + ) + ); + expect(listResp.error).toBeUndefined(); + + const callResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm4', + method: 'tools/call', + params: { + name: 'echo_msg', + arguments: { msg: 'hello' }, + _meta: { progressToken: 'call-tok-1' }, + }, + }) + ) + ); + expect(calls).toBe(1); + expect(callResp.error).toBeUndefined(); + const callResult = callResp.result as { + isError?: boolean; + content: { type: string; text: string }[]; + }; + expect(callResult.isError).toBeUndefined(); + expect(callResult.content[0]?.text).toBe('hello'); + + // Invalid progressToken type -> -32602 before handler runs + const badMetaResp = parseResponse( + await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'm5', + method: 'tools/call', + params: { + name: 'echo_msg', + arguments: { msg: 'hello' }, + _meta: { progressToken: true }, + }, + }) + ) + ); + expect(calls).toBe(1); + expect(badMetaResp.error?.code).toBe(JSON_RPC_ERROR_CODES.INVALID_PARAMS); + }); + + test('raw JSON own __proto__ key in tools/call arguments is preserved and rejected by strict tool schema', async () => { + let calls = 0; + const strictTool = defineMcpTool({ + name: 'strict_tool', + description: 'Accepts only x.', + inputSchema: z.object({ x: z.number() }).strict(), + handler(input) { + calls += 1; + return { content: [{ type: 'text', text: String(input.x) }] }; + }, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [strictTool], + }); + + const rawRequest = + '{"jsonrpc":"2.0","id":"proto-check","method":"tools/call","params":{"name":"strict_tool","arguments":{"x":1,"__proto__":{"injected":true}}}}'; + const response = parseResponse(await server.handleMessage(rawRequest)); + expect(calls).toBe(0); + expect(response.error).toBeUndefined(); + const result = response.result as { isError?: boolean; content: { type: string; text: string }[] }; + expect(result.isError).toBe(true); + expect(result.content[0]?.text).toContain('Invalid arguments for tool "strict_tool"'); + }); + test('duplicate tool names throw at createMcpServer time and unsupported schemas fail fast', () => { const makeTool = () => defineMcpTool({ diff --git a/libs/research/test/mcp-query-data.test.ts b/libs/research/test/mcp-query-data.test.ts index 03722117..664e5c13 100644 --- a/libs/research/test/mcp-query-data.test.ts +++ b/libs/research/test/mcp-query-data.test.ts @@ -7,10 +7,15 @@ import { VaultScopeNotAuthorizedError, } from '../src/market-data-store'; import { + ADJ_SNAPSHOT_FORMAT_VERSION, + ADJ_SNAPSHOT_KV_PREFIX, AdjFactorsSnapshotError, type BarsQuery, + type DuckDbExecutor, + type DuckDbParam, MarketDataStoreNotImplementedError, type UniverseQuery, + createDuckDbMarketDataStore, } from '../src/market-data-store-duckdb'; import { QUERY_DATA_DEFAULT_LIMIT, @@ -439,12 +444,32 @@ describe('MCP query_data tool', () => { expect(emptyPayload.rows).toEqual([]); }); - test('maps store domain errors to isError: true naming the exact error class without stack traces', async () => { + test('maps store domain errors and unexpected errors without leaking paths or stack traces', async () => { const domainErrors: readonly [Error, string][] = [ [new VaultScopeNotAuthorizedError(), 'VaultScopeNotAuthorizedError'], - [new MarketDataStoreValidationError('Bad timeframe bound', 'from'), 'MarketDataStoreValidationError'], - [new MarketDataStoreNotImplementedError('bars', '1m not supported'), 'MarketDataStoreNotImplementedError'], - [new AdjFactorsSnapshotError('retrospective_rejected', 'Retrospective snapshot rejected'), 'AdjFactorsSnapshotError'], + [ + new MarketDataStoreValidationError( + 'Invalid curatedRoot "/mnt/data/stockbot/curated"', + 'curatedRoot' + ), + 'MarketDataStoreValidationError', + ], + [ + new MarketDataStoreValidationError('Bad from timestamp "/etc/passwd"', 'from'), + 'MarketDataStoreValidationError', + ], + [ + new MarketDataStoreNotImplementedError('bars', '1m not supported at /srv/secret/bars.parquet'), + 'MarketDataStoreNotImplementedError', + ], + [ + new AdjFactorsSnapshotError( + 'unpinned_mutable_path', + 'Refusing unpinned mutable adj_factors path "/mnt/data/stockbot/curated/adj_factors/part.parquet"', + '/mnt/data/stockbot/curated/adj_factors/part.parquet' + ), + 'AdjFactorsSnapshotError', + ], ]; for (const [err, expectedName] of domainErrors) { @@ -456,9 +481,285 @@ describe('MCP query_data tool', () => { }); expect(res.isError).toBe(true); expect(res.text).toContain(expectedName); + expect(res.text).not.toContain('/mnt/data/stockbot'); + expect(res.text).not.toContain('/srv/secret'); + expect(res.text).not.toContain('/etc/passwd'); + expect(res.text).not.toContain('part.parquet'); expect(res.text).not.toContain('\n'); expect(res.text).not.toContain('at '); } + + // Unexpected non-domain error containing a filesystem path on the first line + const unexpectedErr = new Error( + 'EACCES: permission denied, open /mnt/data/stockbot/curated/bars_1d/year=2025/part.parquet\n at open (/srv/app/store.ts:12:3)' + ); + const unexpectedFake = createFakeStore({ barsError: unexpectedErr }); + const unexpectedRes = await callQueryData(unexpectedFake, { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + }); + expect(unexpectedRes.isError).toBe(true); + expect(unexpectedRes.text).toBe('Error: Tool execution failed.'); + expect(unexpectedRes.text).not.toContain('/mnt/data/stockbot'); + expect(unexpectedRes.text).not.toContain('/srv/app/store.ts'); + }); + + test('universe lookup uses min(to, asOf) and completed UTC date so later trading cannot leak into earlier asOf', async () => { + const janBar101 = makeBar(101, Date.UTC(2025, 0, 15, 20, 0, 0), 100); + const janBar202 = makeBar(202, Date.UTC(2025, 0, 15, 20, 0, 0), 50); + const allBarsByListing = new Map([ + [101, [janBar101]], + [202, [janBar202]], + ]); + + const universeDates: string[] = []; + const store: MarketDataStore = { + async universe(q: UniverseQuery): Promise { + universeDates.push(q.date); + // Listing 202 resumed trading on 2025-03-26, so it is NOT active on 2025-03-03 + return q.date >= '2025-03-26' ? [101, 202] : [101]; + }, + bars(q: BarsQuery): AsyncIterable { + const rows = q.listingIds.flatMap(id => [...(allBarsByListing.get(id) ?? [])]); + return { + async *[Symbol.asyncIterator]() { + yield { rows }; + }, + }; + }, + 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'); + }, + }; + + const fake: FakeStoreState = { barsCalls: [], universeCalls: [], store }; + + // Date-only asOf earlier than to -> universe queried on 2025-03-03, excluding listing 202 + const dateOnlyRes = await callQueryData(fake, { + universe: 'US_EQ', + from: '2025-01-01', + to: '2025-03-28', + asOf: '2025-03-03', + }); + expect(dateOnlyRes.isError).toBe(false); + expect(universeDates).toEqual(['2025-03-03']); + const payload = JSON.parse(dateOnlyRes.text) as QueryDataResultPayload; + expect(payload.rows).toEqual([janBar101]); + + // Intraday asOf on 2025-03-03 -> uses completed UTC date 2025-03-02 + const intradayRes = await callQueryData(fake, { + universe: 'US_EQ', + from: '2025-01-01', + to: '2025-03-28', + asOf: '2025-03-03T12:00:00Z', + }); + expect(intradayRes.isError).toBe(false); + expect(universeDates).toEqual(['2025-03-03', '2025-03-02']); + }); + + test('DuckDB planner integration preserves microsecond bounds, accepts matching fenced adj_factors snapshot, and sanitizes snapshot errors', async () => { + const recordedQueries: { sql: string; params: readonly DuckDbParam[] }[] = []; + const expectedVaultCeilingMicros = VAULT_CUTOFF_TS * 1000 - 1; + const barTs = Date.UTC(2025, 2, 20, 20, 0, 0); + + const executor: DuckDbExecutor = { + async run() { + // no-op in memory + }, + async query(sql, params) { + recordedQueries.push({ sql, params }); + if (sql.includes('parquet_kv_metadata')) { + return [ + { key: `${ADJ_SNAPSHOT_KV_PREFIX}format_version`, value: String(ADJ_SNAPSHOT_FORMAT_VERSION) }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_kind`, value: 'point_in_time_fenced' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}as_of_micros`, value: 'none' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}vault_cutoff_micros`, value: String(VAULT_CUTOFF_TS * 1000) }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}rows_written`, value: '10' }, + { key: `${ADJ_SNAPSHOT_KV_PREFIX}snapshot_checksum`, value: '0x0123456789abcdef' }, + ]; + } + return [ + { + listing_id: 101, + ts: barTs, + open: 99, + high: 101, + low: 98, + close: 100, + volume: 2_000, + vwap: 100, + known_at: barTs, + }, + ]; + }, + }; + + const duckStore = createDuckDbMarketDataStore({ + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs: VAULT_CUTOFF_TS, + immutableAdjFactorsPath: '/mnt/data/stockbot/curated/snapshots/adj_2025_03_30.parquet', + executor, + }); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: duckStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + // 1. Split-adjusted bars with omitted asOf and clamped to -> forwards .999999Z matching snapshot ceiling + const splitRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-1', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01', + to: '2025-04-15', + adjustment: 'split', + }, + }, + }) + ); + const splitResp = JSON.parse(splitRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(splitResp.result.isError).toBeUndefined(); + const splitPayload = JSON.parse(splitResp.result.content[0]?.text ?? '{}') as QueryDataResultPayload; + expect(splitPayload.rowCount).toBe(1); + expect(expectedVaultCeilingMicros).toBe(Date.UTC(2025, 2, 30, 23, 59, 59, 999) * 1000 + 999); + const barsQuery1 = recordedQueries.find(q => q.sql.includes('bars_1d')); + expect(barsQuery1).toBeDefined(); + expect(barsQuery1?.params).toEqual([ + 101, + '2025-03-30T23:59:59.999999Z', + 101, + '2025-03-01T00:00:00.000Z', + '2025-03-30T23:59:59.999999Z', + '2025-03-30T23:59:59.999999Z', + ]); + + // 2. Caller-supplied sub-millisecond bounds within the fence are preserved verbatim + recordedQueries.length = 0; + const preciseRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-2', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01T00:00:00.000123Z', + to: '2025-03-20T12:34:56.123456Z', + asOf: '2025-03-25T08:09:10.654321Z', + adjustment: 'raw', + }, + }, + }) + ); + const preciseResp = JSON.parse(preciseRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(preciseResp.result.isError).toBeUndefined(); + const barsQuery2 = recordedQueries.find(q => q.sql.includes('bars_1d')); + expect(barsQuery2?.params).toEqual([ + 101, + '2025-03-01T00:00:00.000123Z', + '2025-03-20T12:34:56.123456Z', + '2025-03-25T08:09:10.654321Z', + ]); + + // 3. Unpinned mutable adj_factors path fails closed without leaking internal filesystem path + const unpinnedStore = createDuckDbMarketDataStore({ + curatedRoot: '/mnt/data/stockbot/curated', + vaultCutoffTs: VAULT_CUTOFF_TS, + executor, + }); + const unpinnedServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: unpinnedStore, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + const unpinnedRaw = await unpinnedServer.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'duck-3', + method: 'tools/call', + params: { + name: 'query_data', + arguments: { + listingIds: [101], + from: '2025-03-01', + to: '2025-03-30', + adjustment: 'split', + }, + }, + }) + ); + const unpinnedResp = JSON.parse(unpinnedRaw as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(unpinnedResp.result.isError).toBe(true); + const unpinnedText = unpinnedResp.result.content[0]?.text ?? ''; + expect(unpinnedText).toContain('AdjFactorsSnapshotError'); + expect(unpinnedText).not.toContain('/mnt/data/stockbot'); + expect(unpinnedText).not.toContain('part.parquet'); + }); + + test('raw JSON own __proto__ key in query_data arguments returns isError: true with zero store calls', async () => { + const fake = createFakeStore({ + batches: [{ rows: [makeBar(101, Date.UTC(2025, 2, 20, 20, 0, 0), 100)] }], + }); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createQueryDataTool({ + store: fake.store, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + }), + ], + }); + + const rawRequest = + '{"jsonrpc":"2.0","id":"proto-q","method":"tools/call","params":{"name":"query_data","arguments":{"listingIds":[101],"from":"2025-03-01","to":"2025-03-30","__proto__":{"scope":"vault_evaluation_only"}}}}'; + const rawResponse = await server.handleMessage(rawRequest); + const parsed = JSON.parse(rawResponse as string) as { + result: { isError?: boolean; content: { type: string; text: string }[] }; + }; + expect(parsed.result.isError).toBe(true); + expect(fake.barsCalls).toHaveLength(0); + expect(fake.universeCalls).toHaveLength(0); }); test('repeated identical calls produce byte-identical JSON output', async () => {