T-182: M2.1r — Stdio host composition for the MCP copilot: parseResearchCopilotHostConfig (injected env → validated config) + runResearchCopilotStdioHost (injected executor / store / library-reader factories → createPostgresResearchCopilotServer + createBarSessionDatesPort → runStdioServer, fail-closed, resources always closed) in libs/research/src/mcp/host/stdio-host.ts (no new deps, no live Postgres/DuckDB, no bin)

This commit is contained in:
Studio 2026-12-02 18:23:24 -05:00
parent 6138230252
commit 1236647fa0
4 changed files with 1898 additions and 0 deletions

View file

@ -283,6 +283,24 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
- **`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.
- **`createPostgresResearchCopilotServer(options)`** (exported from `@stock-bot/research/mcp` alongside `PostgresResearchCopilotServerOptions` and `PostgresResearchCopilotExecutor`) wires one shared PostgreSQL executor into `createPostgresSymbolSearchPort`, `createPostgresTrialRefPort`, `createPostgresFindingWritePort`, `createPostgresKnowledgeReaders`, `createPostgresListingCalendarPort` + `createExchangeCalendarResolver`, and `trial_ledger`, while keeping `store`, `listLibraryCards`, `sessionDates` (with optional `earlyCloses`), `newId`, and `now` caller-supplied. `vaultContext.vaultCutoffTs` is the single authoritative Vault cutoff for all Vault-fenced tools and `trial_ledger` visibility lookups. When `schema` is supplied, the schema-aware adapters qualify their tables with `"<schema>".`, while `trial_ledger` writes and cluster DSR reads resolve through the executor's `search_path`.
### Stdio Host Composition
- **`parseResearchCopilotHostConfig(env)`** and **`runResearchCopilotStdioHost(deps)`** (exported from `@stock-bot/research/mcp` alongside `ResearchCopilotHostConfig`, `ResearchCopilotHostConfigError`, `ResearchCopilotStdioHostDeps`, `RESEARCH_COPILOT_HOST_NAME`, and `RESEARCH_COPILOT_HOST_VERSION`) provide a pure, dependency-free stdio host layer (`libs/research/src/mcp/host/stdio-host.ts`) with no `pg`, DuckDB, `node:*`, or bare `process` references.
- **Environment variables (`RESEARCH_MCP_*`):** Unrelated keys are ignored; unknown `RESEARCH_MCP_*` keys, missing required variables, blank values, and malformed fields throw `ResearchCopilotHostConfigError` naming the variable without exposing raw values or credentials.
| Variable | Required | Format |
| --- | --- | --- |
| `RESEARCH_MCP_POSTGRES_URL` | Yes | `postgres://` or `postgresql://` URL with non-empty host (never echoed in errors) |
| `RESEARCH_MCP_POSTGRES_SCHEMA` | No | PostgreSQL identifier `^[a-z_][a-z0-9_]*$` |
| `RESEARCH_MCP_CURATED_ROOT` | Yes | Non-blank path string for curated Parquet datasets (validated by the store factory) |
| `RESEARCH_MCP_VAULT_CUTOFF_TS` | Yes | Strict ISO-8601 UTC instant with seconds and `Z` suffix, optional ms (e.g. `2025-06-01T00:00:00Z`) |
| `RESEARCH_MCP_PRINCIPAL_ID` | Yes | `operator` or `agent:<lowercase-uuid>` (UUID v1–8, RFC variant) |
| `RESEARCH_MCP_LIBRARY_ROOT` | Yes | Non-blank directory path containing `library.yml` (validated by the reader factory) |
| `RESEARCH_MCP_SESSION_REFERENCE_LISTINGS` | Yes | JSON object `{ "<calendarCode>": [<positive INT32>, ...] }` (non-empty, distinct IDs), e.g. `{"XNYS":[101,102],"XTSE":[201]}` |
| `RESEARCH_MCP_EARLY_CLOSES` | No | JSON object `{ "<calendarCode>": { "<YYYY-MM-DD>": <1..960 ET min> } }` within `1976-01-01..=2030-12-31`, e.g. `{"XNYS":{"2024-11-29":780}}` |
- **Usage, single Vault cutoff & cleanup ownership:** Pass the parsed `config` to `runResearchCopilotStdioHost({ config, openExecutor, openStore, createLibraryCardReader, newId, now, stdio? })`. The host acquires `openExecutor` → `openStore` → `createLibraryCardReader`, builds `createBarSessionDatesPort` and `createPostgresResearchCopilotServer` (`stock-bot-research-copilot` / `0.1.0`) with `vaultContext: { vaultCutoffTs: config.vaultCutoffTs }`, and starts `runStdioServer` only after all setup succeeds. Callers' `openStore(config)` factory must configure its `MarketDataStore` with the same `config.vaultCutoffTs` so store queries and session-date derivation share one cutoff. Each factory owns internal cleanup on its own failed startup; once a handle is returned, the host awaits `close()` on every acquired handle exactly once in reverse acquisition order on EOF or error, preserving safe primary errors and replacing credential-bearing or uninspectable failures with fixed stage-specific errors. Keep all startup and runtime diagnostics off `stdout` (use `stderr` or structured logs outside stdio) so `stdout` carries only newline-delimited JSON-RPC frames.
### Remaining M2 MCP Items (Later Tasks)
- SSE/HTTP transport wrapper in `apps/stock/web-api`.