T-205: M2.1v (port to master) — Runnable stdio entrypoint for the MCP research copilot: scripts/research-copilot-mcp.ts + mcp:research-copilot package script, ported from studio/auto-db2c48b5 (T-196) onto master's existing factories (no new deps, no SSE, no lib rewrites)
This commit is contained in:
parent
b49ed59f40
commit
ee61d3b7ae
4 changed files with 836 additions and 0 deletions
332
scripts/test/research-copilot-mcp-defaults.test.ts
Normal file
332
scripts/test/research-copilot-mcp-defaults.test.ts
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { BarBatch, BarQuery, MarketDataStore } from '@stock-bot/research/market-data-store';
|
||||
import { MarketDataStoreNotImplementedError } from '@stock-bot/research/market-data-store-duckdb';
|
||||
import {
|
||||
type LibraryCardReaderHandle,
|
||||
MCP_PROTOCOL_VERSION,
|
||||
type PostgresResearchCopilotExecutor,
|
||||
type ReadKnowledgeResultPayload,
|
||||
RESEARCH_COPILOT_TOOL_NAMES,
|
||||
type StdioInput,
|
||||
type StdioOutput,
|
||||
} from '@stock-bot/research/mcp';
|
||||
import {
|
||||
RESEARCH_COPILOT_HOST_ERROR_LINE,
|
||||
runResearchCopilotMcp,
|
||||
} from '../research-copilot-mcp';
|
||||
|
||||
const FAKE_PASSWORD = 's3cr@t-default-pw#42';
|
||||
const FAKE_ENCODED_PASSWORD = encodeURIComponent(FAKE_PASSWORD);
|
||||
const VALID_AGENT_PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555';
|
||||
const VALID_CUTOFF_ISO = '2025-06-01T00:00:00Z';
|
||||
const FIXED_NOW_MS = Date.UTC(2025, 4, 15, 12, 0, 0, 0);
|
||||
|
||||
function createMemoryWriter(): {
|
||||
readonly stream: StdioOutput;
|
||||
text(): string;
|
||||
} {
|
||||
const chunks: string[] = [];
|
||||
return {
|
||||
stream: {
|
||||
write(chunk: string): boolean {
|
||||
chunks.push(chunk);
|
||||
return true;
|
||||
},
|
||||
},
|
||||
text: () => chunks.join(''),
|
||||
};
|
||||
}
|
||||
|
||||
function createMemoryInput(lines: readonly string[]): StdioInput {
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<string> {
|
||||
for (const line of lines) {
|
||||
yield `${line}\n`;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeExecutor(): PostgresResearchCopilotExecutor {
|
||||
return {
|
||||
async query<Row = Record<string, unknown>>(): Promise<{ readonly rows: readonly Row[] }> {
|
||||
return { rows: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeStore(): MarketDataStore {
|
||||
return {
|
||||
async *bars(q: BarQuery): AsyncIterable<BarBatch> {
|
||||
yield {
|
||||
listingId: q.listingIds[0] ?? 0,
|
||||
timeframe: q.timeframe,
|
||||
rows: [],
|
||||
};
|
||||
},
|
||||
async crossSection() {
|
||||
throw new MarketDataStoreNotImplementedError('crossSection');
|
||||
},
|
||||
async fundamentalsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('fundamentalsAsOf');
|
||||
},
|
||||
async events() {
|
||||
throw new MarketDataStoreNotImplementedError('events');
|
||||
},
|
||||
async shortsAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('shortsAsOf');
|
||||
},
|
||||
async macroAsOf() {
|
||||
throw new MarketDataStoreNotImplementedError('macroAsOf');
|
||||
},
|
||||
async fx() {
|
||||
throw new MarketDataStoreNotImplementedError('fx');
|
||||
},
|
||||
async universe() {
|
||||
return [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeLibraryReader(): LibraryCardReaderHandle {
|
||||
return {
|
||||
async listLibraryCards() {
|
||||
return [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('scripts/research-copilot-mcp.ts default factory wiring', () => {
|
||||
test('default createLibraryCardReader resolves master createLibraryCardReader + createNodeLibraryCardFs over a temp dir', async () => {
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-mcp-lib-'));
|
||||
try {
|
||||
await mkdir(join(tempDir, 'cards', 'quant'), { recursive: true });
|
||||
await writeFile(
|
||||
join(tempDir, 'library.yml'),
|
||||
'id: research-lib\nsections:\n quant: Quantitative Methods\n',
|
||||
'utf8'
|
||||
);
|
||||
await writeFile(
|
||||
join(tempDir, 'cards', 'quant', 'dsr-basics.md'),
|
||||
[
|
||||
'---',
|
||||
'title: "Deflated Sharpe Ratio"',
|
||||
'summary: "Adjusts Sharpe for multiple testing."',
|
||||
'matches: ["dsr", "sharpe"]',
|
||||
'---',
|
||||
'',
|
||||
'Use DSR to account for trial count.',
|
||||
].join('\n'),
|
||||
'utf8'
|
||||
);
|
||||
|
||||
const stdout = createMemoryWriter();
|
||||
const stderr = createMemoryWriter();
|
||||
const closed: string[] = [];
|
||||
|
||||
const input = createMemoryInput([
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: MCP_PROTOCOL_VERSION,
|
||||
capabilities: {},
|
||||
clientInfo: { name: 'defaults-test', version: '1.0.0' },
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method: 'notifications/initialized',
|
||||
}),
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 2,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'read_knowledge',
|
||||
arguments: {
|
||||
source: 'library',
|
||||
id: 'research-lib:quant/dsr-basics',
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const exitCode = await runResearchCopilotMcp({
|
||||
env: {
|
||||
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
|
||||
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
|
||||
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
|
||||
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
|
||||
RESEARCH_MCP_LIBRARY_ROOT: tempDir,
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
|
||||
},
|
||||
input,
|
||||
output: stdout.stream,
|
||||
stderr: stderr.stream,
|
||||
openExecutor: () => ({
|
||||
executor: createFakeExecutor(),
|
||||
close: () => {
|
||||
closed.push('executor');
|
||||
},
|
||||
}),
|
||||
openStore: () => ({
|
||||
store: createFakeStore(),
|
||||
close: () => {
|
||||
closed.push('store');
|
||||
},
|
||||
}),
|
||||
// Intentionally omit createLibraryCardReader to exercise the default factory.
|
||||
newId: () => '00000000-0000-4000-8000-000000000002',
|
||||
now: () => FIXED_NOW_MS,
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stderr.text()).toBe('');
|
||||
expect(closed).toEqual(['store', 'executor']);
|
||||
|
||||
const responses = stdout
|
||||
.text()
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as Record<string, unknown>);
|
||||
expect(responses).toHaveLength(2);
|
||||
|
||||
const callResp = responses[1] as {
|
||||
id: number;
|
||||
result: {
|
||||
isError?: boolean;
|
||||
content: Array<{ type: string; text: string }>;
|
||||
};
|
||||
};
|
||||
expect(callResp.id).toBe(2);
|
||||
expect(callResp.result.isError).not.toBe(true);
|
||||
const payload = JSON.parse(callResp.result.content[0]!.text) as ReadKnowledgeResultPayload;
|
||||
expect(payload.rowCount).toBe(1);
|
||||
expect(payload.rows).toHaveLength(1);
|
||||
const firstRow = payload.rows[0];
|
||||
expect(firstRow?.source).toBe('library');
|
||||
if (firstRow?.source === 'library') {
|
||||
expect(firstRow.id).toBe('research-lib:quant/dsr-basics');
|
||||
expect(firstRow.title).toBe('Deflated Sharpe Ratio');
|
||||
}
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('default openExecutor resolves master openResearchCopilotExecutor and fails closed without opening a DB socket', async () => {
|
||||
// Passes parseResearchCopilotHostConfig (valid scheme + host), but fails
|
||||
// openResearchCopilotExecutor synchronously (missing database path) before creating pg.Pool.
|
||||
const urlWithoutDatabase = `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433`;
|
||||
const stdout = createMemoryWriter();
|
||||
const stderr = createMemoryWriter();
|
||||
let openStoreCalled = false;
|
||||
|
||||
const exitCode = await runResearchCopilotMcp({
|
||||
env: {
|
||||
RESEARCH_MCP_POSTGRES_URL: urlWithoutDatabase,
|
||||
RESEARCH_MCP_CURATED_ROOT: '/tmp/unused-curated-root',
|
||||
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
|
||||
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
|
||||
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
|
||||
},
|
||||
input: createMemoryInput([]),
|
||||
output: stdout.stream,
|
||||
stderr: stderr.stream,
|
||||
// Intentionally omit openExecutor to exercise lazy import of openResearchCopilotExecutor.
|
||||
openStore: () => {
|
||||
openStoreCalled = true;
|
||||
return { store: createFakeStore(), close: () => undefined };
|
||||
},
|
||||
createLibraryCardReader: () => createFakeLibraryReader(),
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(1);
|
||||
expect(stdout.text()).toBe('');
|
||||
expect(stderr.text()).toBe(RESEARCH_COPILOT_HOST_ERROR_LINE);
|
||||
expect(stderr.text()).not.toContain(FAKE_PASSWORD);
|
||||
expect(stderr.text()).not.toContain(FAKE_ENCODED_PASSWORD);
|
||||
expect(stderr.text()).not.toContain(urlWithoutDatabase);
|
||||
expect(openStoreCalled).toBe(false);
|
||||
});
|
||||
|
||||
test('default openStore resolves master openResearchCopilotStore (in-memory DuckDB) and closes cleanly', async () => {
|
||||
const tempCuratedRoot = await mkdtemp(join(tmpdir(), 'stockbot-mcp-curated-'));
|
||||
try {
|
||||
const stdout = createMemoryWriter();
|
||||
const stderr = createMemoryWriter();
|
||||
const closed: string[] = [];
|
||||
|
||||
const input = createMemoryInput([
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: MCP_PROTOCOL_VERSION,
|
||||
capabilities: {},
|
||||
clientInfo: { name: 'defaults-store-test', version: '1.0.0' },
|
||||
},
|
||||
}),
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method: 'notifications/initialized',
|
||||
}),
|
||||
JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
id: 2,
|
||||
method: 'tools/list',
|
||||
params: {},
|
||||
}),
|
||||
]);
|
||||
|
||||
const exitCode = await runResearchCopilotMcp({
|
||||
env: {
|
||||
RESEARCH_MCP_POSTGRES_URL: `postgresql://research_ro:${FAKE_ENCODED_PASSWORD}@127.0.0.1:5433/trading_bot_dev`,
|
||||
RESEARCH_MCP_CURATED_ROOT: tempCuratedRoot,
|
||||
RESEARCH_MCP_VAULT_CUTOFF_TS: VALID_CUTOFF_ISO,
|
||||
RESEARCH_MCP_PRINCIPAL_ID: VALID_AGENT_PRINCIPAL,
|
||||
RESEARCH_MCP_LIBRARY_ROOT: '/tmp/unused-library-root',
|
||||
RESEARCH_MCP_SESSION_REFERENCE_LISTINGS: JSON.stringify({ XNYS: [101] }),
|
||||
},
|
||||
input,
|
||||
output: stdout.stream,
|
||||
stderr: stderr.stream,
|
||||
openExecutor: () => ({
|
||||
executor: createFakeExecutor(),
|
||||
close: () => {
|
||||
closed.push('executor');
|
||||
},
|
||||
}),
|
||||
// Intentionally omit openStore to exercise lazy import of openResearchCopilotStore.
|
||||
createLibraryCardReader: () => createFakeLibraryReader(),
|
||||
newId: () => '00000000-0000-4000-8000-000000000003',
|
||||
now: () => FIXED_NOW_MS,
|
||||
});
|
||||
|
||||
expect(exitCode).toBe(0);
|
||||
expect(stderr.text()).toBe('');
|
||||
expect(closed).toEqual(['executor']);
|
||||
|
||||
const responses = stdout
|
||||
.text()
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map(line => JSON.parse(line) as Record<string, unknown>);
|
||||
expect(responses).toHaveLength(2);
|
||||
const listResp = responses[1] as {
|
||||
id: number;
|
||||
result: { tools: Array<{ name: string }> };
|
||||
};
|
||||
expect(listResp.result.tools.map(t => t.name)).toEqual([...RESEARCH_COPILOT_TOOL_NAMES]);
|
||||
} finally {
|
||||
await rm(tempCuratedRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue