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

@ -0,0 +1,779 @@
/**
* Dependency-free stdio host composition for the MCP research copilot.
*
* Parses `RESEARCH_MCP_*` environment variables into a strict typed
* {@link ResearchCopilotHostConfig} and composes injected PostgreSQL executor,
* market data store, and library-card reader factories with
* {@link createBarSessionDatesPort}, {@link createPostgresResearchCopilotServer},
* and {@link runStdioServer}.
*
* Pure and dependency-free: zero `node:*` imports, zero bare `process` access,
* no `pg` dependency, and no DuckDB driver import.
*/
import { z } from 'zod';
import type { MarketDataStore } from '../../market-data-store';
import {
MAX_ECMASCRIPT_EPOCH_MS,
isValidInt32,
parseCalendarDayKey,
} from '../../panel-shared';
import {
type BarSessionDatesPortOptions,
createBarSessionDatesPort,
} from '../adapters/bar-session-dates';
import {
EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET,
EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE,
EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET,
EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE,
type EarlyCloseOverrides,
} from '../adapters/exchange-calendars';
import {
type PostgresResearchCopilotExecutor,
createPostgresResearchCopilotServer,
} from '../adapters/postgres-copilot';
import type { McpServer } from '../server';
import { type StdioServerOptions, runStdioServer } from '../stdio';
import type { KnowledgePort } from '../tools/read-knowledge';
/** Environment variable prefix owned by {@link parseResearchCopilotHostConfig}. */
export const RESEARCH_MCP_ENV_PREFIX = 'RESEARCH_MCP_';
/** Headless MCP server name announced during `initialize`. */
export const RESEARCH_COPILOT_HOST_NAME = 'stock-bot-research-copilot';
/** Headless MCP server version announced during `initialize`. */
export const RESEARCH_COPILOT_HOST_VERSION = '0.1.0';
const ENV_POSTGRES_URL = 'RESEARCH_MCP_POSTGRES_URL';
const ENV_POSTGRES_SCHEMA = 'RESEARCH_MCP_POSTGRES_SCHEMA';
const ENV_CURATED_ROOT = 'RESEARCH_MCP_CURATED_ROOT';
const ENV_VAULT_CUTOFF_TS = 'RESEARCH_MCP_VAULT_CUTOFF_TS';
const ENV_PRINCIPAL_ID = 'RESEARCH_MCP_PRINCIPAL_ID';
const ENV_LIBRARY_ROOT = 'RESEARCH_MCP_LIBRARY_ROOT';
const ENV_SESSION_REFERENCE_LISTINGS = 'RESEARCH_MCP_SESSION_REFERENCE_LISTINGS';
const ENV_EARLY_CLOSES = 'RESEARCH_MCP_EARLY_CLOSES';
const SCHEMA_IDENT_RE = /^[a-z_][a-z0-9_]*$/;
const AGENT_PRINCIPAL_RE =
/^agent:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const STRICT_UTC_INSTANT_RE =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?Z$/;
const nonBlankEnvString = z.string().refine(value => value.trim().length > 0, {
message: 'blank',
});
const rawHostEnvSchema = z
.object({
[ENV_POSTGRES_URL]: nonBlankEnvString,
[ENV_POSTGRES_SCHEMA]: nonBlankEnvString.optional(),
[ENV_CURATED_ROOT]: nonBlankEnvString,
[ENV_VAULT_CUTOFF_TS]: nonBlankEnvString,
[ENV_PRINCIPAL_ID]: nonBlankEnvString,
[ENV_LIBRARY_ROOT]: nonBlankEnvString,
[ENV_SESSION_REFERENCE_LISTINGS]: nonBlankEnvString,
[ENV_EARLY_CLOSES]: nonBlankEnvString.optional(),
})
.strict();
/** Validated configuration parsed from `RESEARCH_MCP_*` environment variables. */
export interface ResearchCopilotHostConfig {
readonly postgresUrl: string;
readonly postgresSchema?: string;
readonly curatedRoot: string;
readonly vaultCutoffTs: number;
readonly principalId: string;
readonly libraryRoot: string;
readonly referenceListingIds: BarSessionDatesPortOptions['referenceListingIds'];
readonly earlyCloses?: EarlyCloseOverrides;
}
/**
* Typed configuration error thrown by {@link parseResearchCopilotHostConfig}.
*
* Always names the offending `RESEARCH_MCP_*` variable with a fixed reason and
* never embeds raw environment values, DSNs, JSON parser output, or Zod dumps.
*/
export class ResearchCopilotHostConfigError extends RangeError {
readonly variable: string;
constructor(variable: string, message: string) {
super(message);
this.name = 'ResearchCopilotHostConfigError';
this.variable = variable;
Object.setPrototypeOf(this, new.target.prototype);
}
}
/** Managed PostgreSQL executor handle returned by `deps.openExecutor`. */
export interface ManagedPostgresExecutor {
readonly executor: PostgresResearchCopilotExecutor;
close(): Promise<void> | void;
}
/** Managed market data store handle returned by `deps.openStore`. */
export interface ManagedMarketDataStore {
readonly store: MarketDataStore;
close(): Promise<void> | void;
}
/** Library-card reader handle returned by `deps.createLibraryCardReader`. */
export interface LibraryCardReaderHandle {
readonly listLibraryCards: KnowledgePort['listLibraryCards'];
}
/** Injected dependencies for {@link runResearchCopilotStdioHost}. */
export interface ResearchCopilotStdioHostDeps {
readonly config: ResearchCopilotHostConfig;
readonly openExecutor: (
config: ResearchCopilotHostConfig
) => Promise<ManagedPostgresExecutor> | ManagedPostgresExecutor;
readonly openStore: (
config: ResearchCopilotHostConfig
) => Promise<ManagedMarketDataStore> | ManagedMarketDataStore;
readonly createLibraryCardReader: (
config: ResearchCopilotHostConfig
) => Promise<LibraryCardReaderHandle> | LibraryCardReaderHandle;
readonly newId: () => string;
readonly now: () => Date | number;
readonly stdio?: StdioServerOptions;
}
type HostStage =
| 'executor_open'
| 'store_open'
| 'library_reader'
| 'server_init'
| 'stdio_serve'
| 'cleanup';
const STAGE_ERROR_MESSAGES: Readonly<Record<HostStage, string>> = {
executor_open: 'Research copilot stdio host failed while opening the PostgreSQL executor.',
store_open: 'Research copilot stdio host failed while opening the market data store.',
library_reader: 'Research copilot stdio host failed while creating the library card reader.',
server_init: 'Research copilot stdio host failed while initializing the MCP server.',
stdio_serve: 'Research copilot stdio host failed while serving MCP stdio.',
cleanup: 'Research copilot stdio host failed while closing host resources.',
};
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
if (typeof value !== 'object' || value === null) {
return false;
}
const proto: unknown = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function defineDataProperty<T>(target: Record<string, T>, key: string, value: T): void {
Object.defineProperty(target, key, {
value,
enumerable: true,
writable: true,
configurable: true,
});
}
function parsePostgresUrl(raw: string): string {
if (raw !== raw.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL without surrounding whitespace.`
);
}
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a valid postgres:// or postgresql:// URL.`
);
}
if (
(parsed.protocol !== 'postgres:' && parsed.protocol !== 'postgresql:') ||
parsed.hostname.length === 0
) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_URL,
`Invalid configuration variable "${ENV_POSTGRES_URL}": expected a postgres:// or postgresql:// URL with a non-empty host.`
);
}
return raw;
}
function parsePostgresSchema(raw: string): string {
if (!SCHEMA_IDENT_RE.test(raw)) {
throw new ResearchCopilotHostConfigError(
ENV_POSTGRES_SCHEMA,
`Invalid configuration variable "${ENV_POSTGRES_SCHEMA}": expected a PostgreSQL identifier matching ^[a-z_][a-z0-9_]*$.`
);
}
return raw;
}
function parsePrincipalId(raw: string): string {
if (raw !== 'operator' && !AGENT_PRINCIPAL_RE.test(raw)) {
throw new ResearchCopilotHostConfigError(
ENV_PRINCIPAL_ID,
`Invalid configuration variable "${ENV_PRINCIPAL_ID}": expected "operator" or "agent:<lowercase-uuid>".`
);
}
return raw;
}
function parseVaultCutoffTs(raw: string): number {
const match = STRICT_UTC_INSTANT_RE.exec(raw);
if (match === null) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": expected a strict ISO-8601 UTC instant ending in Z.`
);
}
const year = Number(match[1]);
const month = Number(match[2]);
const day = Number(match[3]);
const hour = Number(match[4]);
const minute = Number(match[5]);
const second = Number(match[6]);
const fracRaw = match[7];
const millis = fracRaw === undefined ? 0 : Number(fracRaw.padEnd(3, '0'));
if (
month < 1 ||
month > 12 ||
day < 1 ||
day > 31 ||
hour > 23 ||
minute > 59 ||
second > 59
) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
);
}
const epochMs = Date.UTC(year, month - 1, day, hour, minute, second, millis);
if (!Number.isSafeInteger(epochMs) || Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is out of supported epoch range.`
);
}
const check = new Date(epochMs);
if (
check.getUTCFullYear() !== year ||
check.getUTCMonth() !== month - 1 ||
check.getUTCDate() !== day ||
check.getUTCHours() !== hour ||
check.getUTCMinutes() !== minute ||
check.getUTCSeconds() !== second ||
check.getUTCMilliseconds() !== millis
) {
throw new ResearchCopilotHostConfigError(
ENV_VAULT_CUTOFF_TS,
`Invalid configuration variable "${ENV_VAULT_CUTOFF_TS}": timestamp is not a valid UTC calendar instant.`
);
}
return epochMs;
}
function parseReferenceListingIds(
raw: string
): BarSessionDatesPortOptions['referenceListingIds'] {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected valid JSON.`
);
}
if (!isPlainObjectRecord(parsed)) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": expected a JSON object mapping calendar codes to listing ID arrays.`
);
}
const result: Record<string, readonly number[]> = {};
const entries = Object.entries(parsed);
for (let i = 0; i < entries.length; i += 1) {
const [calendarCode, rawIds] = entries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": calendar codes must be non-empty trimmed strings.`
);
}
if (!Array.isArray(rawIds) || rawIds.length === 0) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": each calendar must map to a non-empty array of positive INT32 listing IDs.`
);
}
const copiedIds: number[] = [];
const seen = new Set<number>();
for (let j = 0; j < rawIds.length; j += 1) {
const id: unknown = rawIds[j];
if (!isValidInt32(id) || id <= 0) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs must be positive 32-bit integers.`
);
}
if (seen.has(id)) {
throw new ResearchCopilotHostConfigError(
ENV_SESSION_REFERENCE_LISTINGS,
`Invalid configuration variable "${ENV_SESSION_REFERENCE_LISTINGS}": listing IDs within a calendar must be distinct.`
);
}
seen.add(id);
copiedIds.push(id);
}
defineDataProperty(result, calendarCode, copiedIds);
}
return result;
}
function parseEarlyClosesEnv(raw: string): EarlyCloseOverrides {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected valid JSON.`
);
}
if (!isPlainObjectRecord(parsed)) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": expected a JSON object mapping calendar codes to date/minute overrides.`
);
}
const result: Record<string, Readonly<Record<string, number>>> = {};
const calendarEntries = Object.entries(parsed);
for (let i = 0; i < calendarEntries.length; i += 1) {
const [calendarCode, rawDates] = calendarEntries[i] as [string, unknown];
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": calendar codes must be non-empty trimmed strings.`
);
}
if (!isPlainObjectRecord(rawDates)) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": each calendar must map to an object of YYYY-MM-DD dates and Eastern close minutes.`
);
}
const dates: Record<string, number> = {};
const dateEntries = Object.entries(rawDates);
for (let j = 0; j < dateEntries.length; j += 1) {
const [dateStr, minute] = dateEntries[j] as [string, unknown];
parseCalendarDayKey(dateStr, ENV_EARLY_CLOSES, () =>
new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must be valid YYYY-MM-DD calendar dates.`
)
);
if (
dateStr < EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE ||
dateStr > EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE
) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": override dates must fall within ${EXCHANGE_CALENDAR_MIN_SUPPORTED_DATE}..=${EXCHANGE_CALENDAR_MAX_SUPPORTED_DATE}.`
);
}
if (
typeof minute !== 'number' ||
!Number.isSafeInteger(minute) ||
minute < EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET ||
minute > EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET
) {
throw new ResearchCopilotHostConfigError(
ENV_EARLY_CLOSES,
`Invalid configuration variable "${ENV_EARLY_CLOSES}": close minutes must be integers from ${EXCHANGE_CALENDAR_MIN_CLOSE_MINUTE_ET} through ${EXCHANGE_CALENDAR_MAX_CLOSE_MINUTE_ET}.`
);
}
defineDataProperty(dates, dateStr, minute);
}
defineDataProperty(result, calendarCode, dates);
}
return result;
}
/**
* Purely parses and validates `RESEARCH_MCP_*` environment variables into a
* typed {@link ResearchCopilotHostConfig}.
*
* Unrelated environment keys are ignored. Unknown `RESEARCH_MCP_*` keys,
* missing required variables, blank values, and malformed fields fail closed
* with {@link ResearchCopilotHostConfigError} naming the variable without
* exposing raw values or credentials.
*/
export function parseResearchCopilotHostConfig(
env: Readonly<Record<string, string | undefined>>
): ResearchCopilotHostConfig {
if (typeof env !== 'object' || env === null) {
throw new ResearchCopilotHostConfigError(
RESEARCH_MCP_ENV_PREFIX,
'Invalid environment object: expected a key-value record.'
);
}
const scopedEnv: Record<string, unknown> = {};
const entries = Object.entries(env);
for (let i = 0; i < entries.length; i += 1) {
const [key, value] = entries[i] as [string, unknown];
if (key.startsWith(RESEARCH_MCP_ENV_PREFIX) && value !== undefined) {
defineDataProperty(scopedEnv, key, value);
}
}
const parsedEnv = rawHostEnvSchema.safeParse(scopedEnv);
if (!parsedEnv.success) {
const firstIssue = parsedEnv.error.issues[0];
if (firstIssue !== undefined) {
if (firstIssue.code === 'unrecognized_keys') {
const unknownKey = firstIssue.keys[0] ?? RESEARCH_MCP_ENV_PREFIX;
throw new ResearchCopilotHostConfigError(
unknownKey,
`Unknown configuration variable "${unknownKey}".`
);
}
const variable =
typeof firstIssue.path[0] === 'string' ? firstIssue.path[0] : RESEARCH_MCP_ENV_PREFIX;
if (firstIssue.code === 'invalid_type' && firstIssue.received === 'undefined') {
throw new ResearchCopilotHostConfigError(
variable,
`Missing required configuration variable "${variable}".`
);
}
if (firstIssue.code === 'custom') {
throw new ResearchCopilotHostConfigError(
variable,
`Invalid configuration variable "${variable}": value must not be empty or whitespace.`
);
}
throw new ResearchCopilotHostConfigError(
variable,
`Invalid configuration variable "${variable}": expected a non-empty string.`
);
}
throw new ResearchCopilotHostConfigError(
RESEARCH_MCP_ENV_PREFIX,
'Invalid research copilot host configuration.'
);
}
const data = parsedEnv.data;
const postgresUrl = parsePostgresUrl(data[ENV_POSTGRES_URL]);
const postgresSchema =
data[ENV_POSTGRES_SCHEMA] !== undefined
? parsePostgresSchema(data[ENV_POSTGRES_SCHEMA])
: undefined;
const curatedRoot = data[ENV_CURATED_ROOT].trim();
const vaultCutoffTs = parseVaultCutoffTs(data[ENV_VAULT_CUTOFF_TS]);
const principalId = parsePrincipalId(data[ENV_PRINCIPAL_ID]);
const libraryRoot = data[ENV_LIBRARY_ROOT].trim();
const referenceListingIds = parseReferenceListingIds(data[ENV_SESSION_REFERENCE_LISTINGS]);
const earlyCloses =
data[ENV_EARLY_CLOSES] !== undefined
? parseEarlyClosesEnv(data[ENV_EARLY_CLOSES])
: undefined;
return {
postgresUrl,
...(postgresSchema !== undefined ? { postgresSchema } : {}),
curatedRoot,
vaultCutoffTs,
principalId,
libraryRoot,
referenceListingIds,
...(earlyCloses !== undefined ? { earlyCloses } : {}),
};
}
function collectSecretNeedles(postgresUrl: string): readonly string[] {
const needles = new Set<string>();
if (postgresUrl.length > 0) {
needles.add(postgresUrl);
}
try {
const parsed = new URL(postgresUrl);
if (parsed.href.length > 0) {
needles.add(parsed.href);
}
if (parsed.password.length > 0) {
needles.add(parsed.password);
try {
const decoded = decodeURIComponent(parsed.password);
if (decoded.length > 0) {
needles.add(decoded);
}
} catch {
// Malformed percent-encoding in password: raw password needle is already covered.
}
}
} catch {
// Non-URL postgresUrl passed directly to runResearchCopilotStdioHost: raw string is covered.
}
return Array.from(needles);
}
function containsAnyNeedle(text: string, needles: readonly string[]): boolean {
for (let i = 0; i < needles.length; i += 1) {
if (text.includes(needles[i] as string)) {
return true;
}
}
return false;
}
function isErrorSafeToSurface(
error: unknown,
needles: readonly string[],
visited: Set<unknown> = new Set(),
depth = 0
): error is Error {
if (!(error instanceof Error) || depth > 8) {
return false;
}
if (visited.has(error)) {
return true;
}
visited.add(error);
try {
const message = error.message;
if (typeof message !== 'string' || containsAnyNeedle(message, needles)) {
return false;
}
const stack = error.stack;
if (typeof stack === 'string' && containsAnyNeedle(stack, needles)) {
return false;
}
const cause = (error as { readonly cause?: unknown }).cause;
if (cause !== undefined && !isErrorSafeToSurface(cause, needles, visited, depth + 1)) {
return false;
}
return true;
} catch {
return false;
}
}
function sanitizeHostError(
error: unknown,
stage: HostStage,
needles: readonly string[]
): Error {
if (isErrorSafeToSurface(error, needles)) {
return error;
}
return new Error(STAGE_ERROR_MESSAGES[stage]);
}
function validateHostDeps(deps: ResearchCopilotStdioHostDeps): void {
if (typeof deps !== 'object' || deps === null) {
throw new Error('Invalid `deps`: expected a ResearchCopilotStdioHostDeps object.');
}
if (typeof deps.config !== 'object' || deps.config === null) {
throw new Error('Invalid `deps.config`: expected a ResearchCopilotHostConfig object.');
}
if (typeof deps.openExecutor !== 'function') {
throw new Error('Invalid `deps.openExecutor`: expected a callable factory function.');
}
if (typeof deps.openStore !== 'function') {
throw new Error('Invalid `deps.openStore`: expected a callable factory function.');
}
if (typeof deps.createLibraryCardReader !== 'function') {
throw new Error(
'Invalid `deps.createLibraryCardReader`: expected a callable factory function.'
);
}
if (typeof deps.newId !== 'function') {
throw new Error('Invalid `deps.newId`: expected a callable ID generator function.');
}
if (typeof deps.now !== 'function') {
throw new Error('Invalid `deps.now`: expected a callable clock function.');
}
}
/**
* Composes and runs the headless MCP research copilot over stdio using
* caller-injected resource factories.
*
* - Acquires resources sequentially (`openExecutor` -> `openStore` ->
* `createLibraryCardReader`) before serving any stdio input.
* - Uses `config.vaultCutoffTs` as the single authoritative Vault cutoff; the
* caller's `openStore` factory must configure the store with that same cutoff.
* - Always closes every acquired resource exactly once in reverse acquisition
* order on EOF or error, preserving the primary failure when safe and
* replacing credential-bearing or uninspectable errors with a fixed
* stage-specific error without a raw `cause`.
*/
export async function runResearchCopilotStdioHost(
deps: ResearchCopilotStdioHostDeps
): Promise<void> {
validateHostDeps(deps);
const { config } = deps;
const secretNeedles = collectSecretNeedles(
typeof config.postgresUrl === 'string' ? config.postgresUrl : ''
);
const closers: Array<() => Promise<void> | void> = [];
let primaryError: { readonly error: unknown; readonly stage: HostStage } | null = null;
try {
let executorHandle: ManagedPostgresExecutor;
try {
executorHandle = await deps.openExecutor(config);
} catch (error) {
primaryError = { error, stage: 'executor_open' };
throw error;
}
if (
typeof executorHandle !== 'object' ||
executorHandle === null ||
typeof executorHandle.close !== 'function'
) {
const error = new Error(
'Invalid executor handle: expected an object with executor and close().'
);
primaryError = { error, stage: 'executor_open' };
throw error;
}
closers.push(() => executorHandle.close());
let storeHandle: ManagedMarketDataStore;
try {
storeHandle = await deps.openStore(config);
} catch (error) {
primaryError = { error, stage: 'store_open' };
throw error;
}
if (
typeof storeHandle !== 'object' ||
storeHandle === null ||
typeof storeHandle.close !== 'function'
) {
const error = new Error(
'Invalid store handle: expected an object with store and close().'
);
primaryError = { error, stage: 'store_open' };
throw error;
}
closers.push(() => storeHandle.close());
let libraryReader: LibraryCardReaderHandle;
try {
libraryReader = await deps.createLibraryCardReader(config);
} catch (error) {
primaryError = { error, stage: 'library_reader' };
throw error;
}
if (
typeof libraryReader !== 'object' ||
libraryReader === null ||
typeof libraryReader.listLibraryCards !== 'function'
) {
const error = new Error(
'Invalid library card reader: expected an object with listLibraryCards().'
);
primaryError = { error, stage: 'library_reader' };
throw error;
}
let server: McpServer;
try {
const sessionDates = createBarSessionDatesPort({
store: storeHandle.store,
referenceListingIds: config.referenceListingIds,
});
server = createPostgresResearchCopilotServer({
name: RESEARCH_COPILOT_HOST_NAME,
version: RESEARCH_COPILOT_HOST_VERSION,
executor: executorHandle.executor,
...(config.postgresSchema !== undefined ? { schema: config.postgresSchema } : {}),
store: storeHandle.store,
vaultContext: { vaultCutoffTs: config.vaultCutoffTs },
principalId: config.principalId,
listLibraryCards: libraryReader.listLibraryCards,
sessionDates,
...(config.earlyCloses !== undefined ? { earlyCloses: config.earlyCloses } : {}),
newId: deps.newId,
now: deps.now,
});
} catch (error) {
primaryError = { error, stage: 'server_init' };
throw error;
}
try {
await runStdioServer(server, deps.stdio);
} catch (error) {
primaryError = { error, stage: 'stdio_serve' };
throw error;
}
} catch (error) {
if (primaryError === null) {
primaryError = { error, stage: 'server_init' };
}
}
let firstCloseError: { readonly error: unknown } | null = null;
for (let i = closers.length - 1; i >= 0; i -= 1) {
try {
await closers[i]?.();
} catch (closeErr) {
if (firstCloseError === null) {
firstCloseError = { error: closeErr };
}
}
}
if (primaryError !== null) {
throw sanitizeHostError(primaryError.error, primaryError.stage, secretNeedles);
}
if (firstCloseError !== null) {
throw sanitizeHostError(firstCloseError.error, 'cleanup', secretNeedles);
}
}

View file

@ -14,3 +14,4 @@ export * from './tools/read-knowledge';
export * from './tools/search-symbols';
export * from './adapters/postgres-copilot';
export * from './adapters/bar-session-dates';
export * from './host/stdio-host';