T-138: M2.1f — MCP copilot file_finding tool: validated, append-only empirical finding / dead-end filing via an injected FindingWritePort in libs/research/src/mcp/tools/

This commit is contained in:
Studio 2026-12-01 07:33:48 -05:00
parent 46d4c59132
commit 2eefa9f168
4 changed files with 1523 additions and 1 deletions

View file

@ -218,8 +218,13 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
- **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars.
- **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`.
### `file_finding` Tool (Append-Only)
- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message.
- **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`.
### Remaining M2 MCP Items (Later Tasks)
- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`.
- SSE/HTTP transport wrapper in `apps/stock/web-api`.
- Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters.

View file

@ -3,6 +3,7 @@ export * from './server';
export * from './stdio';
export * from './tools/analyze-signal';
export * from './tools/event-study';
export * from './tools/file-finding';
export * from './tools/query-data';
export * from './tools/read-knowledge';
export * from './tools/search-symbols';

View file

@ -0,0 +1,416 @@
import { z } from 'zod';
import type { McpToolCallResult } from '../protocol';
import { type McpToolEntry, defineMcpTool } from '../server';
import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge';
import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input';
/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */
export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const;
export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number];
/** Initial server-assigned review status for every newly filed finding or dead end. */
export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const;
export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS;
/** Hard maximum character length of a trimmed `file_finding` title. */
export const FILE_FINDING_MAX_TITLE_LENGTH = 256;
/** Hard maximum character length of a trimmed `file_finding` summary. */
export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH;
/** Hard maximum character length of a trimmed trial or evidence reference string. */
export const FILE_FINDING_MAX_REF_LENGTH = 256;
/** Hard maximum number of raw `trialRefs` accepted before deduplication. */
export const FILE_FINDING_MAX_TRIAL_REFS = 32;
/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */
export const FILE_FINDING_MAX_EVIDENCE_REFS = 32;
/** Hard maximum character length of a trimmed `idempotencyKey`. */
export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128;
/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */
export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.';
/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */
export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF =
'One or more referenced trials are unavailable in the research-visible trial ledger.';
/** Fixed tool error message when an idempotency key is reused with a different payload. */
export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT =
'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.';
/** Fixed tool error message when trial lookup, metadata generation, or append fails. */
export const FILE_FINDING_ERROR_FILING_FAILED =
'Failed to file finding due to a storage or lookup error.';
/**
* Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}.
*
* Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'`
* so filed records are directly readable via `read_knowledge` while director approval
* happens out-of-band.
*/
export interface FiledFindingRecord extends FindingRecord {
readonly kind: FileFindingKind;
readonly status: FileFindingInitialStatus;
}
/** Normalized caller-supplied fields compared for idempotency equality. */
export type FiledFindingComparablePayload = Pick<
FiledFindingRecord,
'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs'
>;
/**
* Discriminated outcome returned by {@link FindingWritePort.appendFinding}.
*
* - `'created'`: A new record was appended.
* - `'replayed'`: An existing record with the same `idempotencyKey` and
* identical normalized payload (`kind`, `title`, `summary`, `trialRefs`,
* `evidenceRefs`) was found; zero rows were appended and the stored `id`
* and `createdAt` are returned.
* - `'conflict'`: An existing record with the same `idempotencyKey` has a
* different normalized payload; zero rows were appended.
*/
export type AppendFindingResult =
| {
readonly status: 'created';
readonly id: string;
readonly createdAt: string;
}
| {
readonly status: 'replayed';
readonly id: string;
readonly createdAt: string;
}
| {
readonly status: 'conflict';
};
/**
* Append-only write port injected into {@link createFileFindingTool}.
*
* Port contract:
* - Append-only by construction: exposes only {@link appendFinding} (no update
* or delete methods).
* - When `idempotencyKey` is supplied, the port must atomically compare and
* append within its configured key namespace:
* - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and
* `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`).
* - On an identical payload match, return `{ status: 'replayed', id, createdAt }`
* with the originally stored `id` and `createdAt` without appending a new row.
* - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows.
* - When `idempotencyKey` is omitted (`undefined`), each call is independent and
* appends a new row, returning `{ status: 'created', id, createdAt }`.
*/
export interface FindingWritePort {
appendFinding(
record: FiledFindingRecord,
idempotencyKey?: string
): Promise<AppendFindingResult>;
}
/**
* Read-only trial visibility lookup port injected into {@link createFileFindingTool}.
*
* Bound at composition to the caller's research-visible `trial_ledger` and active
* Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings
* from `trial_ledger` receipts without numeric coercion) and returns `true` only when
* the trial exists and is research-visible. Unknown and Vault-only refs both return
* `false`.
*/
export interface TrialRefLookupPort {
hasResearchVisibleTrial(trialRef: string): Promise<boolean> | boolean;
}
/** Server-side injected configuration for {@link createFileFindingTool}. */
export interface FileFindingToolOptions {
readonly port: FindingWritePort;
readonly trialLookup: TrialRefLookupPort;
readonly newId: () => string;
readonly now: () => Date | number;
}
/** Structured JSON receipt serialized into the `file_finding` MCP text result. */
export interface FileFindingResultPayload {
readonly id: string;
readonly createdAt: string;
readonly created: boolean;
}
function compareStrings(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
function normalizeRefSet(refs: readonly string[]): readonly string[] {
const unique = Array.from(new Set(refs));
unique.sort(compareStrings);
return unique;
}
function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
/**
* Compares two normalized filing payloads for idempotency equality across
* `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding
* server-generated `id`, `createdAt`, and `status`).
*/
export function areFiledFindingPayloadsEqual(
a: FiledFindingComparablePayload,
b: FiledFindingComparablePayload
): boolean {
return (
a.kind === b.kind &&
a.title === b.title &&
a.summary === b.summary &&
areStringArraysEqual(a.trialRefs, b.trialRefs) &&
areStringArraysEqual(a.evidenceRefs, b.evidenceRefs)
);
}
const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH);
/**
* Strict Zod input schema for the `file_finding` MCP tool.
*
* Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and
* Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`).
* `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed
* message so caller-supplied key names are never echoed.
*
* `title` and `summary` must describe research-visible evidence only; `evidenceRefs`
* are opaque snapshot identifiers that the tool stores without dereferencing.
*/
export const fileFindingInputSchema = z
.object({
kind: z
.enum(FILE_FINDING_KINDS, {
errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }),
})
.describe("Filing classification: 'finding' or 'dead_end'."),
title: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_TITLE_LENGTH)
.describe(
`Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).`
),
summary: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_SUMMARY_LENGTH)
.describe(
`Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).`
),
trialRefs: z
.array(refStringSchema)
.min(1)
.max(FILE_FINDING_MAX_TRIAL_REFS)
.transform(normalizeRefSet)
.describe(
`Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).`
),
evidenceRefs: z
.array(refStringSchema)
.max(FILE_FINDING_MAX_EVIDENCE_REFS)
.default([])
.transform(normalizeRefSet)
.describe(
`Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).`
),
idempotencyKey: z
.string()
.trim()
.min(1)
.max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH)
.optional()
.describe(
`Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).`
),
})
.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS);
export type FileFindingInput = z.infer<typeof fileFindingInputSchema>;
function toolError(message: string): McpToolCallResult {
return {
content: [{ type: 'text', text: message }],
isError: true,
};
}
function validateNonEmptyString(value: unknown): string | null {
if (typeof value !== 'string' || value.trim().length === 0) {
return null;
}
return value;
}
function formatUtcIsoTimestamp(raw: Date | number): string | null {
const epochMs = raw instanceof Date ? raw.getTime() : raw;
if (
typeof epochMs !== 'number' ||
!Number.isFinite(epochMs) ||
Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS
) {
return null;
}
return new Date(epochMs).toISOString();
}
function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions {
if (typeof options !== 'object' || options === null) {
throw new Error('Invalid `options`: expected a FileFindingToolOptions object.');
}
if (
typeof options.port !== 'object' ||
options.port === null ||
typeof options.port.appendFinding !== 'function'
) {
throw new Error(
'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.'
);
}
if (
typeof options.trialLookup !== 'object' ||
options.trialLookup === null ||
typeof options.trialLookup.hasResearchVisibleTrial !== 'function'
) {
throw new Error(
'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.'
);
}
if (typeof options.newId !== 'function') {
throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.');
}
if (typeof options.now !== 'function') {
throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.');
}
return options;
}
/**
* Creates the append-only `file_finding` MCP tool backed by an injected
* {@link FindingWritePort} and read-only {@link TrialRefLookupPort}.
*
* Verifies every unique `trialRef` against the research-visible trial ledger
* before generating server-controlled metadata (`id`, `createdAt`,
* `status: 'pending_review'`) or calling `appendFinding`. Returns only the
* explicitly projected `{ id, createdAt, created }` receipt on success and fixed
* sanitized `isError` messages on failure.
*/
export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry {
const validated = validateFactoryOptions(options);
const { port, trialLookup, newId, now } = validated;
return defineMcpTool({
name: 'file_finding',
description:
'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.',
inputSchema: fileFindingInputSchema,
async handler(input: FileFindingInput): Promise<McpToolCallResult> {
// Verify every unique research-visible trial ref before generating metadata or writing.
for (let i = 0; i < input.trialRefs.length; i += 1) {
const trialRef = input.trialRefs[i] as string;
let visible: unknown;
try {
visible = await trialLookup.hasResearchVisibleTrial(trialRef);
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (typeof visible !== 'boolean') {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (!visible) {
return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF);
}
}
let id: string | null;
let createdAt: string | null;
try {
id = validateNonEmptyString(newId());
createdAt = formatUtcIsoTimestamp(now());
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (id === null || createdAt === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const record: FiledFindingRecord = {
id,
kind: input.kind,
title: input.title,
status: FILE_FINDING_INITIAL_STATUS,
createdAt,
summary: input.summary,
trialRefs: [...input.trialRefs],
evidenceRefs: [...input.evidenceRefs],
};
let outcome: AppendFindingResult;
try {
outcome = await port.appendFinding(record, input.idempotencyKey);
} catch {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (typeof outcome !== 'object' || outcome === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
if (outcome.status === 'conflict') {
return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT);
}
if (outcome.status !== 'created' && outcome.status !== 'replayed') {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const receiptId = validateNonEmptyString(outcome.id);
const receiptCreatedAt = validateNonEmptyString(outcome.createdAt);
if (receiptId === null || receiptCreatedAt === null) {
return toolError(FILE_FINDING_ERROR_FILING_FAILED);
}
const payload: FileFindingResultPayload = {
id: receiptId,
createdAt: receiptCreatedAt,
created: outcome.status === 'created',
};
return {
content: [{ type: 'text', text: JSON.stringify(payload) }],
};
},
});
}

File diff suppressed because it is too large Load diff