Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
perf(pi): 按需加载 MCP 与项目知识上下文 (#3352)
Chris Zhange6c1762cb563
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/projectContextInject.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/projectContextInject.test.tsnew file mode 100644index 0000000000..9e35ec3ee9--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/projectContextInject.test.ts@@ -0,0 +1,56 @@+import { promises as fs } from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it } from 'vitest';++import { tryInjectProjectContext } from '../projectContextInject.js';++const tempDirs: string[] = [];++async function makeProject(toc?: string): Promise<string> {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-project-context-'));+ tempDirs.push(dir);+ if (toc !== undefined) {+ const knowledgeDir = path.join(dir, '.cindy', 'project-knowledge');+ await fs.mkdir(knowledgeDir, { recursive: true });+ await fs.writeFile(path.join(knowledgeDir, 'TOC.md'), toc, 'utf8');+ }+ return dir;+}++afterEach(async () => {+ await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })));+});++describe('tryInjectProjectContext', () => {+ it('injects one compact on-demand pointer instead of the TOC body', async () => {+ const sentinel = 'LARGE_TOC_BODY_MUST_NOT_ENTER_STARTUP_CONTEXT';+ const workingDir = await makeProject(`# Project Knowledge\n\n${sentinel}\n${'x'.repeat(20_000)}`);++ const result = await tryInjectProjectContext(workingDir);++ expect(result.injected).toBe(true);+ expect(result.content).toContain('.cindy/project-knowledge/TOC.md');+ expect(result.content).toContain('read that file');+ expect(result.content).not.toContain(sentinel);+ expect(result.content?.length).toBeLessThan(300);+ expect(result).toEqual({+ injected: true,+ content: [+ '<project-context-toc>',+ 'Project Knowledge is available at .cindy/project-knowledge/TOC.md.',+ 'When project or module knowledge is relevant, read that file and follow its links on demand.',+ '</project-context-toc>',+ ].join('\n'),+ });+ });++ it('skips missing and empty TOC files without blocking session creation', async () => {+ const missing = await tryInjectProjectContext(await makeProject());+ const empty = await tryInjectProjectContext(await makeProject(' \n'));++ expect(missing).toEqual({ injected: false, reason: 'no-toc-file' });+ expect(empty).toEqual({ injected: false, reason: 'empty-toc-file' });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/projectContextInject.ts b/apps/desktop/src/main/maker-ipc/projectContextInject.tsindex 09f9c6c031..3680a61e57 100644--- a/apps/desktop/src/main/maker-ipc/projectContextInject.ts+++ b/apps/desktop/src/main/maker-ipc/projectContextInject.ts@@ -1,13 +1,13 @@/*** project-context inject helper(main 进程)*- * 在 createSession IPC 之前调用,向 systemPrompt 注入一段「项目模块知识 TOC + 摘要」,- * 引导 agent 用 Read 工具按需打开完整 .md 文件取细节。+ * 在 createSession IPC 之前调用,向 systemPrompt 注入一个稳定的项目知识入口,+ * 引导 agent 仅在相关时用 Read 工具打开 TOC.md,再按需读取完整 .md 文件。** 数据源唯一性:直接读 `.cindy/project-knowledge/TOC.md`。这是* `project-context` CLI 在 init/update/refresh 时预生成的派生物,跟 manifest 和各- * 模块 .md 一起入 git、由 CI 集中维护。desktop 端不做任何 markdown 解析、不做- * 摘要抽取、不感知 manifest schema —— 渲染逻辑统一在 `packages/project-context/src/toc.ts`。+ * 模块 .md 一起入 git、由 CI 集中维护。desktop 端只确认 TOC 存在且非空,不把正文+ * 预载进每个会话,也不解析 markdown / manifest schema。** 读不到 TOC.md(文件缺失 / 空 / IO 错)= 该工作目录没有可用的项目知识库,* 直接返回 `injected: false` 不注入;session 仍可正常创建。这是有意行为:@@ -24,6 +24,7 @@ import { migrateLegacyXdmakerDir } from '../utils/legacyXdmakerMigration.js';const log = createLogger('project-context-inject');const TOC_REL_PATH = path.join('.cindy', 'project-knowledge', 'TOC.md');+const TOC_PROMPT_PATH = '.cindy/project-knowledge/TOC.md';const CACHE_TTL_MS = 5_000;const cache = new Map<string, { result: InjectResult; ts: number }>();@@ -70,12 +71,16 @@ async function readToc(workingDir: string): Promise<InjectResult> {} catch {return { injected: false, reason: 'no-toc-file' };}- const trimmed = raw.trim();- if (!trimmed) {+ if (!raw.trim()) {return { injected: false, reason: 'empty-toc-file' };}- const content = `<project-context-toc>\n${trimmed}\n</project-context-toc>`;- log.debug('project-context inject from TOC.md', { bytes: content.length });+ const content = [+ '<project-context-toc>',+ `Project Knowledge is available at ${TOC_PROMPT_PATH}.`,+ 'When project or module knowledge is relevant, read that file and follow its links on demand.',+ '</project-context-toc>',+ ].join('\n');+ log.debug('project-context inject pointer to TOC.md', { bytes: content.length });return { injected: true, content };}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 1bce782559..02992deef4 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -7061,7 +7061,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)* 自动开启——任何 session 创建都会尝试读 cwd 下 .cindy/project-knowledge/,存在就注入;* 不再依赖 renderer 显式开关。tryInjectProjectContext silently fallback——目录缺失 / 文件* 读失败都走 injected:false 分支,不抛错也不阻塞 session 创建。- * 副作用:mutate o.userPrompt(追加 wrapper);返回是否真的注入了内容。+ * 副作用:mutate o.userPrompt(追加按需读取 TOC 的短 wrapper);返回是否真的注入了入口。*/async function applyProjectContextInjection(o: CreateOpts): Promise<boolean> {if (!o.workingDir) return false;diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.tsindex 48911eaa21..5b4744c7fa 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/codexEnvironment.test.ts@@ -342,6 +342,18 @@ describe('codexEnvironment', () => {expect(cfg.extraArgs.some((a) => a.includes('sk-123'))).toBe(false);});+ it('keeps Codex on direct mcp_servers config instead of the Pi gateway', async () => {+ const cfg = await getCodexExtraSpawnConfig({+ mcpProviders: [testProvider(), remoteHttpProvider()],+ logger: noopLogger(),+ });++ expect(cfg.extraArgs.some((arg) => arg.startsWith('mcp_servers.cindy_test.'))).toBe(true);+ expect(cfg.extraArgs.some((arg) => arg.startsWith('mcp_servers.themis.'))).toBe(true);+ expect(cfg.extraArgs.join('\n')).not.toContain('cindy_mcp_list_tools');+ expect(cfg.extraArgs.join('\n')).not.toContain('cindy_mcp_call_tool');+ });+// server 名可能来自用户可控来源(自定义 MCP id、插件身份卡)。普通 `{}` 上// `map['__proto__'] = cfg` 命中的是原型 setter:该 server 不出现在 Object.entries 里,// 于是在 Codex 侧静默消失,同一份配置却在 Claude 侧正常工作。diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.mdindex 614ecf96e9..e02e421600 100644--- a/docs/dev-rules/pi-harness.md+++ b/docs/dev-rules/pi-harness.md@@ -45,9 +45,13 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi真值仅经 Pi 父进程专用 env 传递,`CINDY_PI_MCP_BRIDGE` 只存 env 引用;这些 env 与描述符都会在 bash spawn 边界剥离。bridge 并行执行外部 server 启动探测,每个 server 的`initialize + tools/list` 总预算为 10s(低于 Pi RPC 30s ready 门槛);探测完成后实际工具- 调用保留 600s 长预算。SSE response 按 event 增量消费,不等待 server 关闭持续流。工具注册- 为 `mcp__<server>__<tool>`。配置新增、修改、禁用或删除对下一新建/重启会话生效;旧活动- 会话保留启动时 generation 快照至 close。+ 调用保留 600s 长预算。SSE response 按 event 增量消费,不等待 server 关闭持续流。Pi 模型侧+ 始终只注册 `cindy_mcp_list_tools` 与 `cindy_mcp_call_tool` 两个稳定网关 schema;完整工具目录与+ input schema 留在 bridge 内部。先发现名称/描述,再按具体 server + tool 取单个 schema,+ 未检查 schema 的调用在 bridge 内 fail closed,不会触达 MCP 或弹权限框。Host 审批、策略与变更捕获仍使用真实+ `mcp__<server>__<tool>` identity 和真实参数,不能退化成对网关包装器授权。Claude Code 与+ Codex 保持各自的直接 MCP 注册方式,不经过此 Pi 专属网关。配置新增、修改、禁用或删除对+ 下一新建/重启会话生效;旧活动会话保留启动时 generation 快照至 close。- **plan 模式**:挂 pi 自带 plan-mode 扩展,`/plan` toggle 驱动;Cindy 维护镜像态并在 resume时从 `get_entries` 校正。diff --git a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.tsindex c168c0679d..a216b4295d 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/mcp-approval-policy.test.ts@@ -959,6 +959,32 @@ describe('a custom server cannot take over a builtin name', () => {await handle.close();});+ it('keeps Claude on direct per-server MCP registration instead of the Pi gateway', async () => {+ const configDir = await makeTempDir();+ process.env.CLAUDE_CONFIG_DIR = configDir;+ const workingDir = await makeTempDir();+ sdkMock.query.mockReturnValue(createFakeQuery());++ const agent = new ClaudeCodeAgent(createDeps(() => 'prompt', [+ 'cindy_browser',+ 'cindy_contacts',+ ]));+ const handle = await agent.startSession({+ sessionId: 'session-direct-mcp-contract',+ model: 'claude-opus-4-6',+ workingDir,+ permissionMode: 'default',+ });++ const mcpServers = sdkMock.query.mock.calls.at(-1)?.[0]?.options?.mcpServers as+ | Record<string, unknown>+ | undefined;+ expect(Object.keys(mcpServers ?? {}).sort()).toEqual(['cindy_browser', 'cindy_contacts']);+ expect(Object.keys(mcpServers ?? {})).not.toContain('cindy_mcp_list_tools');+ expect(Object.keys(mcpServers ?? {})).not.toContain('cindy_mcp_call_tool');+ await handle.close();+ });+it('treats an unsafe object-key server name as an ordinary key', async () => {const configDir = await makeTempDir();process.env.CLAUDE_CONFIG_DIR = configDir;diff --git a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.tsindex 217494d592..a52c386cae 100644--- a/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/cindyBridgeSource.test.ts@@ -1055,8 +1055,23 @@ describe('cindy-bridge extension source', () => {expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on('tool_call'");expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('FILE_WRITE_BUILTINS.has(event.toolName)');expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("pi.on('tool_result'");- expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("event.toolName !== 'bash'");- expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("startsWith('mcp__')");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("captureToolName !== 'bash'");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("String(captureToolName ?? '').startsWith('mcp__')");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('captureToolName = gatewayCall?.qualifiedName');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('captureInput = gatewayCall?.args');+ });++ it('exposes a constant two-tool MCP gateway while preserving the real MCP identity for approval', () => {+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("const CINDY_MCP_LIST_TOOLS = 'cindy_mcp_list_tools'");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("const CINDY_MCP_CALL_TOOL = 'cindy_mcp_call_tool'");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('mcpGateway.register(pi)');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain("qualifiedName: 'mcp__' + serverName + '__' + toolName");+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('private readonly disclosedSchemas');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('mcpGateway.isSchemaDisclosed(resolvedGatewayCall)');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('Inspect this tool before execution');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('permissionToolName = gatewayCall?.qualifiedName');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).toContain('permissionInput = gatewayCall?.args');+ expect(CINDY_BRIDGE_EXTENSION_SOURCE).not.toContain("name: qualifiedName,\n label: server.name + ': ' + tool.name");});it('resolves the bash package home across reloads with a tamper-proof stash and keeps the package token out of globalThis', () => {diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.tsindex 9dee3c5ea7..9d58e98e36 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-bridge.integration.test.ts@@ -4,15 +4,15 @@** 拓扑(全本地,无网络):* 真 pi 二进制 ──RPC──▶ PiAgent- * │ HTTP(streamable MCP, SDK) ──▶ 假 MCP server(注册一个 cindy_echo 工具)- * │ HTTP(anthropic SSE) ──▶ 假网关(脚本化两轮:先 tool_use 调 cindy_echo,- * │ 拿到 tool_result 后再出最终 text)+ * │ HTTP(streamable MCP, SDK) ──▶ 假 MCP server(覆盖多 server、多参数形状与同名工具)+ * │ HTTP(anthropic SSE) ──▶ 假网关(脚本化三轮:先发现、再经稳定网关调用,+ * │ 拿到真实 tool_result 后再出最终 text)* PiAgent.interactionResolver ◀── extension_ui_request(权限询问)** 断言:- * 1. 模型发起的 tool_use 打到假 MCP server(工具确实经 cindy-bridge 注册+转发)- * 2. ask 档下该工具触发 interactionResolver;allow → 工具执行、最终 text 含回显- * 3. deny 场景:另一会话 resolver 返回 deny → 工具不执行,MCP server 未被命中+ * 1. 模型启动面只有两个稳定网关 schema,不再含每个 mcp__<server>__<tool>+ * 2. list_tools → call_tool 真正打到假 MCP server,多工具连续调用仍全部可达+ * 3. ask 档下 Host 仍看到真实 MCP identity;allow/deny 与错误修正链保持成立** pi 二进制缺失时 skip。*/@@ -81,46 +81,48 @@ function sseEvent(event: string, data: unknown): string {return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;}-// ── 假网关:脚本化两轮 anthropic Messages 流 ─────────────────────────────────-// 第 1 次请求(messages 里没有 tool_result)→ 出 tool_use 调 cindy_echo。-// 第 2 次请求(已带 tool_result)→ 出最终 text。-function anthropicTurn(hasToolResult: boolean, toolName: string): string {- if (!hasToolResult) {- return (- sseEvent('message_start', {- type: 'message_start',- message: {- id: 'msg_1', type: 'message', role: 'assistant', model: 'pi-test-model',- content: [], stop_reason: null, usage: { input_tokens: 20, output_tokens: 0 },- },- }) +- sseEvent('content_block_start', {- type: 'content_block_start', index: 0,- content_block: { type: 'tool_use', id: 'toolu_1', name: toolName, input: {} },- }) +- sseEvent('content_block_delta', {- type: 'content_block_delta', index: 0,- delta: { type: 'input_json_delta', partial_json: JSON.stringify({ text: 'hello-pi' }) },- }) +- sseEvent('content_block_stop', { type: 'content_block_stop', index: 0 }) +- sseEvent('message_delta', {- type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 },- }) +- sseEvent('message_stop', { type: 'message_stop' })- );- }+function anthropicToolTurn(+ sequence: number,+ toolName: string,+ input: Record<string, unknown>,+): string {+ return (+ sseEvent('message_start', {+ type: 'message_start',+ message: {+ id: `msg_${sequence}`, type: 'message', role: 'assistant', model: 'pi-test-model',+ content: [], stop_reason: null, usage: { input_tokens: 20, output_tokens: 0 },+ },+ }) ++ sseEvent('content_block_start', {+ type: 'content_block_start', index: 0,+ content_block: { type: 'tool_use', id: `toolu_${sequence}`, name: toolName, input: {} },+ }) ++ sseEvent('content_block_delta', {+ type: 'content_block_delta', index: 0,+ delta: { type: 'input_json_delta', partial_json: JSON.stringify(input) },+ }) ++ sseEvent('content_block_stop', { type: 'content_block_stop', index: 0 }) ++ sseEvent('message_delta', {+ type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: 5 },+ }) ++ sseEvent('message_stop', { type: 'message_stop' })+ );+}++function anthropicTextTurn(sequence: number, text: string): string {return (sseEvent('message_start', {type: 'message_start',message: {- id: 'msg_2', type: 'message', role: 'assistant', model: 'pi-test-model',+ id: `msg_${sequence}`, type: 'message', role: 'assistant', model: 'pi-test-model',content: [], stop_reason: null, usage: { input_tokens: 30, output_tokens: 0 },},}) +sseEvent('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }) +sseEvent('content_block_delta', {type: 'content_block_delta', index: 0,- delta: { type: 'text_delta', text: 'tool said: ECHO[hello-pi]' },+ delta: { type: 'text_delta', text },}) +sseEvent('content_block_stop', { type: 'content_block_stop', index: 0 }) +sseEvent('message_delta', {@@ -130,6 +132,126 @@ function anthropicTurn(hasToolResult: boolean, toolName: string): string {);}+function countToolResults(requestBody: string): number {+ return (requestBody.match(/"type":"tool_result"/g) ?? []).length;+}++function latestToolResultContent(request: Record<string, unknown>): string {+ const messages = request.messages as Array<{+ content?: Array<{ type?: string; content?: string }>;+ }> | undefined;+ for (const message of [...(messages ?? [])].reverse()) {+ const result = [...(message.content ?? [])].reverse().find((item) => item.type === 'tool_result');+ if (result?.content !== undefined) return result.content;+ }+ throw new Error('model request did not contain a tool_result');+}++function scriptedAnthropicTurn(requestBody: string): string {+ const toolResultCount = countToolResults(requestBody);+ if (requestBody.includes('multi command MCP workflow')) {+ const turns: Array<{ name: string; input: Record<string, unknown> }> = [+ { name: 'cindy_mcp_list_tools', input: {} },+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_workspace', tool: 'status' } },+ { name: 'cindy_mcp_call_tool', input: { server: 'cindy_workspace', tool: 'status', args: {} } },+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_workspace', tool: 'sum' } },+ {+ name: 'cindy_mcp_call_tool',+ input: { server: 'cindy_workspace', tool: 'sum', args: { values: [3, 5, 8] } },+ },+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_workspace', tool: 'configure' } },+ {+ name: 'cindy_mcp_call_tool',+ input: {+ server: 'cindy_workspace',+ tool: 'configure',+ args: { options: { retries: 2, flags: ['safe', 'fast'] } },+ },+ },+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_workspace', tool: 'lookup' } },+ {+ name: 'cindy_mcp_call_tool',+ input: { server: 'cindy_workspace', tool: 'lookup', args: { query: 'release-notes' } },+ },+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_contacts', tool: 'lookup' } },+ {+ name: 'cindy_mcp_call_tool',+ input: { server: 'cindy_contacts', tool: 'lookup', args: { query: 'Ada' } },+ },+ ];+ const next = turns[toolResultCount];+ return next+ ? anthropicToolTurn(toolResultCount + 1, next.name, next.input)+ : anthropicTextTurn(+ turns.length + 1,+ 'workflow complete: READY, SUM[16], CONFIGURED[2:safe,fast], WORKSPACE[release-notes], CONTACT[Ada]',+ );+ }+ if (requestBody.includes('unknown gateway tool')) {+ return toolResultCount === 0+ ? anthropicToolTurn(1, 'cindy_mcp_call_tool', {+ server: 'missing_server',+ tool: 'missing_tool',+ args: {},+ })+ : anthropicTextTurn(2, 'unknown tool rejected safely');+ }+ if (requestBody.includes('inspect unavailable MCP')) {+ return toolResultCount === 0+ ? anthropicToolTurn(1, 'cindy_mcp_list_tools', {})+ : anthropicTextTurn(2, 'unavailable servers reported');+ }+ if (requestBody.includes('call without schema inspection')) {+ if (toolResultCount === 0) {+ return anthropicToolTurn(1, 'cindy_mcp_call_tool', {+ server: 'cindy_echo', tool: 'echo', args: { text: 'hello-pi' },+ });+ }+ if (toolResultCount === 1) {+ return anthropicToolTurn(2, 'cindy_mcp_list_tools', {+ server: 'cindy_echo', tool: 'echo',+ });+ }+ if (toolResultCount === 2) {+ return anthropicToolTurn(3, 'cindy_mcp_call_tool', {+ server: 'cindy_echo', tool: 'echo', args: { text: 'hello-pi' },+ });+ }+ return anthropicTextTurn(4, 'blind call was gated safely');+ }+ if (requestBody.includes('invalid args then correct')) {+ if (toolResultCount === 0) return anthropicToolTurn(1, 'cindy_mcp_list_tools', {});+ if (toolResultCount === 1) {+ return anthropicToolTurn(2, 'cindy_mcp_list_tools', {+ server: 'cindy_echo', tool: 'echo',+ });+ }+ if (toolResultCount === 2) {+ return anthropicToolTurn(3, 'cindy_mcp_call_tool', {+ server: 'cindy_echo', tool: 'echo', args: {},+ });+ }+ if (toolResultCount === 3) {+ return anthropicToolTurn(4, 'cindy_mcp_call_tool', {+ server: 'cindy_echo', tool: 'echo', args: { text: 'hello-pi' },+ });+ }+ return anthropicTextTurn(5, 'tool said: ECHO[hello-pi]');+ }+ if (toolResultCount === 0) return anthropicToolTurn(1, 'cindy_mcp_list_tools', {});+ if (toolResultCount === 1) {+ return anthropicToolTurn(2, 'cindy_mcp_list_tools', {+ server: 'cindy_echo', tool: 'echo',+ });+ }+ if (toolResultCount === 2) {+ return anthropicToolTurn(3, 'cindy_mcp_call_tool', {+ server: 'cindy_echo', tool: 'echo', args: { text: 'hello-pi' },+ });+ }+ return anthropicTextTurn(4, 'tool said: ECHO[hello-pi]');+}+describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + permission gate)', () => {let gateway: Server;let gatewayUrl = '';@@ -141,28 +263,37 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pconst REMOTE_ERROR_CANARY = 'remote-error-body-secret-canary';let agentHome = '';const echoCalls: Array<{ text: unknown }> = [];+ const statusCalls: Array<Record<string, never>> = [];+ const sumCalls: Array<{ values: number[] }> = [];+ const configureCalls: Array<{ options: { retries: number; flags: string[] } }> = [];+ const workspaceLookupCalls: Array<{ query: string }> = [];+ const contactsLookupCalls: Array<{ query: string }> = [];// 记录假 MCP server 收到的请求 URL —— 断言真 pi(经 cindy-bridge fetch)把// host 下发的 `?session=<id>` 原样带到每个 MCP 请求上(orca 身份路由的 pi 侧半)。const seenMcpUrls: string[] = [];const seenRemoteHeaders: Array<{ authorization?: string; apiKey?: string }> = [];const paginatedListCursors: Array<string | undefined> = [];const timedOutPaginationCursors: Array<string | undefined> = [];+ const modelRequestBodies: string[] = [];+ const modelRequests: Array<Record<string, unknown>> = [];+ const opaqueTurnCaptures: Array<{ sessionId: string; provider: string; cwd: string }> = [];beforeAll(async () => {agentHome = mkdtempSync(path.join(tmpdir(), 'pi-mcp-int-'));- // 假网关:按 messages 是否含 tool_result 决定出哪一轮。+ // 假网关:按 user prompt + tool_result 数量脚本化发现、调用、纠错与终答。gateway = createServer(async (req, res) => {const body = await readBody(req);- const hasToolResult = body.includes('tool_result') || body.includes('toolResult');+ modelRequestBodies.push(body);+ modelRequests.push(JSON.parse(body) as Record<string, unknown>);res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' });- res.end(anthropicTurn(hasToolResult, 'mcp__cindy_echo__echo'));+ res.end(scriptedAnthropicTurn(body));});await new Promise<void>((r) => gateway.listen(0, '127.0.0.1', r));const gAddr = gateway.address();if (typeof gAddr === 'object' && gAddr) gatewayUrl = `http://127.0.0.1:${gAddr.port}`;- // 假 MCP server(streamable-HTTP + bearer + 单工具 echo),与 codexHttpBridge 同构。+ // 假 MCP server(streamable-HTTP + bearer + 多路工具),与 codexHttpBridge 同构。mcpHttp = createServer(async (req: IncomingMessage, res: ServerResponse) => {seenMcpUrls.push(req.url ?? '');const auth = req.headers.authorization ?? '';@@ -335,15 +466,71 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pres.writeHead(401).end('unauthorized');return;}- const server = new McpServer({ name: 'cindy_echo', version: '1.0.0' });- server.registerTool(- 'echo',- { description: 'Echo text back in uppercase', inputSchema: { text: z.string() } },- async ({ text }) => {- echoCalls.push({ text });- return { content: [{ type: 'text', text: `ECHO[${text}]` }] };- },- );+ const isWorkspace = req.url?.includes('/workspace') ?? false;+ const isContacts = req.url?.includes('/contacts') ?? false;+ const server = new McpServer({+ name: isWorkspace ? 'cindy_workspace' : isContacts ? 'cindy_contacts' : 'cindy_echo',+ version: '1.0.0',+ });+ if (isWorkspace) {+ server.registerTool(+ 'status',+ { description: 'Read the workspace status', inputSchema: {} },+ async (args) => {+ statusCalls.push(args);+ return { content: [{ type: 'text', text: 'READY' }] };+ },+ );+ server.registerTool(+ 'sum',+ { description: 'Sum a list of numbers', inputSchema: { values: z.array(z.number()) } },+ async ({ values }) => {+ sumCalls.push({ values });+ return { content: [{ type: 'text', text: `SUM[${values.reduce((total, value) => total + value, 0)}]` }] };+ },+ );+ server.registerTool(+ 'configure',+ {+ description: 'Apply nested workspace options',+ inputSchema: {+ options: z.object({ retries: z.number().int(), flags: z.array(z.string()) }),+ },+ },+ async ({ options }) => {+ configureCalls.push({ options });+ return {+ content: [{ type: 'text', text: `CONFIGURED[${options.retries}:${options.flags.join(',')}]` }],+ };+ },+ );+ server.registerTool(+ 'lookup',+ { description: 'Look up a workspace resource', inputSchema: { query: z.string() } },+ async ({ query }) => {+ workspaceLookupCalls.push({ query });+ return { content: [{ type: 'text', text: `WORKSPACE[${query}]` }] };+ },+ );+ } else if (isContacts) {+ server.registerTool(+ 'lookup',+ { description: 'Look up a contact', inputSchema: { query: z.string() } },+ async ({ query }) => {+ contactsLookupCalls.push({ query });+ return { content: [{ type: 'text', text: `CONTACT[${query}]` }] };+ },+ );+ } else {+ server.registerTool(+ 'echo',+ { description: 'Echo text back in uppercase', inputSchema: { text: z.string() } },+ async ({ text }) => {+ echoCalls.push({ text });+ return { content: [{ type: 'text', text: `ECHO[${text}]` }] };+ },+ );+ }const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });res.on('close', () => { void transport.close(); void server.close(); });await server.connect(transport);@@ -362,7 +549,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p});function buildDeps(- bridgeMode: 'local' | 'remote' | 'remote-sse' | 'remote-paginated' | 'remote-failures' = 'local',+ bridgeMode: 'local' | 'local-multi' | 'remote' | 'remote-sse' | 'remote-paginated' | 'remote-failures' = 'local',logger: Logger = noopLogger,): AgentDeps {return {@@ -375,6 +562,10 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pruntimeConfig: { endpoint: gatewayUrl },binaryPath: PI_BINARY,logger,+ turnChangeCapture: {+ beforeKnownFileWrite: async () => {},+ noteOpaqueWrite: (input) => opaqueTurnCaptures.push(input),+ },capabilityAdditions: {availableModels: [{ id: 'pi-test-model', displayName: 'Pi Test', contextWindow: 200_000, efforts: [], defaultEffort: null },@@ -503,6 +694,20 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pmcpEnv: { CINDY_PI_REMOTE_MCP_SECRET_0: `Bearer ${REMOTE_BEARER}` },};}+ if (bridgeMode === 'local-multi') {+ const sessionQuery = ctx?.sessionId+ ? `?session=${encodeURIComponent(ctx.sessionId)}`+ : '';+ return {+ mcpBridge: {+ token: MCP_TOKEN,+ servers: [+ { name: 'cindy_workspace', url: `${mcpUrl}/workspace${sessionQuery}` },+ { name: 'cindy_contacts', url: `${mcpUrl}/contacts${sessionQuery}` },+ ],+ },+ };+ }return {mcpBridge: {token: MCP_TOKEN,@@ -523,10 +728,18 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pasync function runOneTurn(permissionMode: 'ask' | 'bypassPermissions',resolver: (req: InteractionRequest) => Promise<InteractionDecision>,- bridgeMode: 'local' | 'remote' | 'remote-sse' | 'remote-paginated' = 'local',- ): Promise<{ events: AgentEvent[]; permissionAsked: boolean }> {+ bridgeMode: 'local' | 'local-multi' | 'remote' | 'remote-sse' | 'remote-paginated' = 'local',+ prompt = 'call the echo tool',+ ): Promise<{+ events: AgentEvent[];+ permissionAsked: boolean;+ requestBodies: string[];+ requests: Array<Record<string, unknown>>;+ }> {const agent = new PiAgent(buildDeps(bridgeMode));const cwd = mkdtempSync(path.join(tmpdir(), 'pi-mcp-cwd-'));+ const requestStart = modelRequests.length;+ const requestBodyStart = modelRequestBodies.length;let handle: AgentSessionHandle | null = null;let permissionAsked = false;try {@@ -547,9 +760,14 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pif (ev.type === 'done') break;}})();- await handle.send({ type: 'user', content: 'call the echo tool' });+ await handle.send({ type: 'user', content: prompt });await done;- return { events, permissionAsked };+ return {+ events,+ permissionAsked,+ requestBodies: modelRequestBodies.slice(requestBodyStart),+ requests: modelRequests.slice(requestStart),+ };} finally {await handle?.close();rmSync(cwd, { recursive: true, force: true });@@ -562,10 +780,12 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pasync () => {echoCalls.length = 0;seenMcpUrls.length = 0;- const { events, permissionAsked } = await runOneTurn('ask', async (req) => {+ opaqueTurnCaptures.length = 0;+ const { events, permissionAsked, requestBodies, requests } = await runOneTurn('ask', async (req) => {expect(req.kind).toBe('permission');if (req.kind === 'permission') {expect(req.toolName).toBe('mcp__cindy_echo__echo');+ expect(req.input).toEqual({ text: 'hello-pi' });}return { kind: 'permission', behavior: 'allow' };});@@ -573,6 +793,27 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pexpect(permissionAsked).toBe(true);expect(echoCalls.length).toBeGreaterThan(0);expect(echoCalls[0]?.text).toBe('hello-pi');+ await waitFor(() => opaqueTurnCaptures.length === 1);+ expect(opaqueTurnCaptures[0]).toMatchObject({+ sessionId: 'mcp-itest-ask',+ provider: 'pi',+ });+ expect(requestBodies[1]).toContain('cindy_echo');+ expect(requestBodies[1]).toContain('Echo text back in uppercase');+ expect(requestBodies[1]).not.toContain('inputSchema');+ expect(requestBodies[2]).toContain('inputSchema');+ expect(requestBodies[2]).toContain('"required"');+ expect(requestBodies[2]).toContain('"text"');++ const firstTools = requests[0]?.tools as Array<{ name?: string }> | undefined;+ const firstToolNames = firstTools?.map((tool) => tool.name) ?? [];+ expect(firstToolNames).toContain('cindy_mcp_list_tools');+ expect(firstToolNames).toContain('cindy_mcp_call_tool');+ expect(firstToolNames).not.toContain('mcp__cindy_echo__echo');+ expect(firstToolNames.filter((name) => name?.startsWith('cindy_mcp_'))).toEqual([+ 'cindy_mcp_list_tools',+ 'cindy_mcp_call_tool',+ ]);// 真 pi(经 cindy-bridge)必须把 host 下发的 `?session=<sessionId>` 原样带到// MCP 请求上 —— 这是 orca 身份路由能在真 pi 上生效的 pi 侧前提。@@ -589,6 +830,203 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p},);+ it(+ 'executes five real tools across two MCP servers in one Pi workflow without mixing same-name tools',+ { timeout: 90_000 },+ async () => {+ statusCalls.length = 0;+ sumCalls.length = 0;+ configureCalls.length = 0;+ workspaceLookupCalls.length = 0;+ contactsLookupCalls.length = 0;+ seenMcpUrls.length = 0;+ const permissionRequests: Array<{ toolName: string; input: unknown }> = [];++ const { events, requestBodies, requests } = await runOneTurn(+ 'ask',+ async (req) => {+ expect(req.kind).toBe('permission');+ if (req.kind === 'permission') {+ permissionRequests.push({ toolName: req.toolName, input: req.input });+ }+ return { kind: 'permission', behavior: 'allow' };+ },+ 'local-multi',+ 'run the multi command MCP workflow',+ );++ expect(statusCalls).toEqual([{}]);+ expect(sumCalls).toEqual([{ values: [3, 5, 8] }]);+ expect(configureCalls).toEqual([{ options: { retries: 2, flags: ['safe', 'fast'] } }]);+ expect(workspaceLookupCalls).toEqual([{ query: 'release-notes' }]);+ expect(contactsLookupCalls).toEqual([{ query: 'Ada' }]);+ expect(permissionRequests).toEqual([+ { toolName: 'mcp__cindy_workspace__status', input: {} },+ { toolName: 'mcp__cindy_workspace__sum', input: { values: [3, 5, 8] } },+ {+ toolName: 'mcp__cindy_workspace__configure',+ input: { options: { retries: 2, flags: ['safe', 'fast'] } },+ },+ { toolName: 'mcp__cindy_workspace__lookup', input: { query: 'release-notes' } },+ { toolName: 'mcp__cindy_contacts__lookup', input: { query: 'Ada' } },+ ]);++ const startupToolNames = (requests[0]?.tools as Array<{ name?: string }> | undefined)+ ?.map((tool) => tool.name) ?? [];+ expect(startupToolNames.filter((name) => name?.startsWith('cindy_mcp_'))).toEqual([+ 'cindy_mcp_list_tools',+ 'cindy_mcp_call_tool',+ ]);+ expect(startupToolNames.some((name) => name?.startsWith('mcp__'))).toBe(false);++ const discoveryResult = latestToolResultContent(requests[1] ?? {});+ expect(discoveryResult).toContain('cindy_workspace');+ expect(discoveryResult).toContain('cindy_contacts');+ expect(discoveryResult).not.toContain('inputSchema');+ const inspectedResults = [2, 4, 6, 8, 10].map((index) =>+ JSON.parse(latestToolResultContent(requests[index] ?? {})) as {+ tools?: Array<{ server?: string; name?: string; description?: string; inputSchema?: unknown }>;+ }+ );+ expect(inspectedResults.map((result) => result.tools?.[0])).toMatchObject([+ { server: 'cindy_workspace', name: 'status', inputSchema: { type: 'object', properties: {} } },+ {+ server: 'cindy_workspace',+ name: 'sum',+ inputSchema: {+ type: 'object',+ properties: { values: { type: 'array', items: { type: 'number' } } },+ required: ['values'],+ },+ },+ {+ server: 'cindy_workspace',+ name: 'configure',+ inputSchema: {+ type: 'object',+ properties: {+ options: {+ type: 'object',+ properties: {+ retries: { type: 'integer' },+ flags: { type: 'array', items: { type: 'string' } },+ },+ required: ['retries', 'flags'],+ },+ },+ required: ['options'],+ },+ },+ { server: 'cindy_workspace', name: 'lookup', description: 'Look up a workspace resource' },+ { server: 'cindy_contacts', name: 'lookup', description: 'Look up a contact' },+ ]);+ const finalRequestBody = requestBodies.at(-1) ?? '';+ for (const result of [+ 'READY',+ 'SUM[16]',+ 'CONFIGURED[2:safe,fast]',+ 'WORKSPACE[release-notes]',+ 'CONTACT[Ada]',+ ]) {+ expect(finalRequestBody).toContain(result);+ }+ expect(seenMcpUrls.some((url) => url.includes('/workspace?session=mcp-itest-ask'))).toBe(true);+ expect(seenMcpUrls.some((url) => url.includes('/contacts?session=mcp-itest-ask'))).toBe(true);++ const finalText = events+ .filter((event) => event.type === 'text')+ .map((event) => event.data as { text: string; isFinal?: boolean })+ .filter((data) => data.isFinal)+ .map((data) => data.text)+ .join('');+ expect(finalText).toContain('workflow complete');+ expect(finalText).toContain('CONTACT[Ada]');+ },+ );++ it(+ 'invalid MCP args expose the selected schema and let Pi correct the call without losing the capability',+ { timeout: 90_000 },+ async () => {+ echoCalls.length = 0;+ const { events, permissionAsked, requestBodies } = await runOneTurn(+ 'bypassPermissions',+ async () => ({ kind: 'permission', behavior: 'deny' }),+ 'local',+ 'invalid args then correct',+ );++ expect(permissionAsked).toBe(false);+ expect(echoCalls).toEqual([{ text: 'hello-pi' }]);+ expect(requestBodies.some((body) =>+ body.includes('Expected args schema') && body.includes('"required"') && body.includes('"text"')+ )).toBe(true);+ const finalText = events+ .filter((event) => event.type === 'text')+ .map((event) => event.data as { text: string; isFinal?: boolean })+ .filter((data) => data.isFinal)+ .map((data) => data.text)+ .join('');+ expect(finalText).toContain('ECHO[hello-pi]');+ },+ );++ it(+ 'unknown gateway targets fail before MCP execution and do not prompt for a fake wrapper capability',+ { timeout: 90_000 },+ async () => {+ echoCalls.length = 0;+ const { events, permissionAsked, requestBodies } = await runOneTurn(+ 'ask',+ async () => ({ kind: 'permission', behavior: 'deny' }),+ 'local',+ 'unknown gateway tool',+ );++ expect(permissionAsked).toBe(false);+ expect(echoCalls).toHaveLength(0);+ expect(requestBodies.some((body) => body.includes('Unknown Cindy MCP tool'))).toBe(true);+ const finalText = events+ .filter((event) => event.type === 'text')+ .map((event) => event.data as { text: string; isFinal?: boolean })+ .filter((data) => data.isFinal)+ .map((data) => data.text)+ .join('');+ expect(finalText).toContain('unknown tool rejected safely');+ },+ );++ it(+ 'known tools cannot execute or prompt until their exact input schema has been inspected',+ { timeout: 90_000 },+ async () => {+ echoCalls.length = 0;+ opaqueTurnCaptures.length = 0;+ let permissionCount = 0;+ const { permissionAsked, requestBodies } = await runOneTurn(+ 'ask',+ async (req) => {+ permissionCount += 1;+ expect(req.kind).toBe('permission');+ if (req.kind === 'permission') {+ expect(req.toolName).toBe('mcp__cindy_echo__echo');+ expect(req.input).toEqual({ text: 'hello-pi' });+ }+ return { kind: 'permission', behavior: 'allow' };+ },+ 'local',+ 'call without schema inspection',+ );++ expect(permissionAsked).toBe(true);+ expect(permissionCount).toBe(1);+ expect(echoCalls).toEqual([{ text: 'hello-pi' }]);+ expect(requestBodies[1]).toContain('Inspect this tool before execution');+ expect(requestBodies[2]).toContain('inputSchema');+ await waitFor(() => opaqueTurnCaptures.length === 1);+ },+ );+it('direct remote HTTP: uses env-backed bearer/custom headers instead of the localhost bridge token',{ timeout: 90_000 },@@ -678,7 +1116,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pasync () => {echoCalls.length = 0;paginatedListCursors.length = 0;- const { events, permissionAsked } = await runOneTurn(+ const { events, permissionAsked, requestBodies, requests } = await runOneTurn('bypassPermissions',async () => ({ kind: 'permission', behavior: 'deny' }),'remote-paginated',@@ -687,6 +1125,15 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pexpect(permissionAsked).toBe(false);expect(paginatedListCursors).toEqual([undefined, 'page-2', 'page-3']);expect(echoCalls).toEqual([{ text: 'hello-pi' }]);+ expect(requestBodies[1]).toContain('page_one');+ expect(requestBodies[1]).toContain('page_two');+ expect(requestBodies[1]).toContain('echo');+ expect(requestBodies[1]).not.toContain('inputSchema');+ expect(requestBodies[2]).toContain('inputSchema');+ const startupToolNames = (requests[0]?.tools as Array<{ name?: string }> | undefined)+ ?.map((tool) => tool.name) ?? [];+ expect(startupToolNames.filter((name) => name?.startsWith('cindy_mcp_'))).toHaveLength(2);+ expect(startupToolNames.some((name) => name?.startsWith('mcp__'))).toBe(false);const finalText = events.filter((event) => event.type === 'text').map((event) => event.data as { text: string; isFinal?: boolean })@@ -706,6 +1153,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + ptimedOutPaginationCursors.length = 0;const agent = new PiAgent(buildDeps('remote-failures', logger));const cwd = mkdtempSync(path.join(tmpdir(), 'pi-mcp-failure-cwd-'));+ const requestBodyStart = modelRequestBodies.length;let handle: AgentSessionHandle | null = null;try {handle = await agent.startSession({@@ -714,6 +1162,15 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pmodel: 'pi-test-model',permissionMode: 'bypassPermissions',});+ const events: AgentEvent[] = [];+ const done = (async () => {+ for await (const event of handle!.events()) {+ events.push(event);+ if (event.type === 'done') break;+ }+ })();+ await handle.send({ type: 'user', content: 'inspect unavailable MCP' });+ await done;await waitFor(() => {const logs = JSON.stringify(entries);return logs.includes('HTTP 401')@@ -727,8 +1184,20 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + pexpect(logs).toContain('connect stalling_body_remote failed: request timed out');expect(logs).toContain('connect paginated_timeout_remote failed: request timed out');expect(timedOutPaginationCursors).toEqual([undefined, 'slow-page']);+ const requestBodies = modelRequestBodies.slice(requestBodyStart);+ expect(requestBodies.some((body) =>+ body.includes('unavailableServers')+ && body.includes('rejecting_remote')+ && body.includes('slow_remote')+ )).toBe(true);+ expect(events.some((event) =>+ event.type === 'text'+ && (event.data as { text?: string; isFinal?: boolean }).isFinal+ && (event.data as { text?: string }).text?.includes('unavailable servers reported')+ )).toBe(true);for (const forbidden of [REMOTE_BEARER, REMOTE_API_KEY, REMOTE_ERROR_CANARY, mcpUrl]) {expect(logs).not.toContain(forbidden);+ expect(requestBodies.join('\n')).not.toContain(forbidden);}} finally {await handle?.close();@@ -742,6 +1211,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p{ timeout: 90_000 },async () => {echoCalls.length = 0;+ opaqueTurnCaptures.length = 0;const { permissionAsked } = await runOneTurn('ask', async () => ({kind: 'permission',behavior: 'deny',@@ -749,6 +1219,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p}));expect(permissionAsked).toBe(true);expect(echoCalls.length).toBe(0);+ expect(opaqueTurnCaptures).toHaveLength(0);},);});diff --git a/packages/maker-core/src/agents/pi/auto-review-policy.ts b/packages/maker-core/src/agents/pi/auto-review-policy.tsindex 415e244928..03d5cfd934 100644--- a/packages/maker-core/src/agents/pi/auto-review-policy.ts+++ b/packages/maker-core/src/agents/pi/auto-review-policy.ts@@ -26,7 +26,7 @@ import { CINDY_SUBAGENT_TOOL_NAME } from './cindy-subagent-source.js';export type PiAutoReviewVerdict = ReviewVerdict;export interface PiAutoReviewContext {- /** pi 工具名(内置小写:bash/edit/write/read/…;桥接 MCP 为 mcp__<server>__<tool>)。 */+ /** pi 内置工具名,或 bridge 从稳定网关还原出的 mcp__<server>__<tool> 真实身份。 */toolName: string;/** 工具入参(bridge 透传的原始对象)。 */input: Record<string, unknown>;diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.tsindex df9b1d0e7e..b21fe84723 100644--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts@@ -10,8 +10,8 @@* 读不到一律按 ask(fail-closed)。* 2. MCP 桥:CINDY_PI_MCP_BRIDGE 指向 host 的 localhost bridge,或用户显式配置的* 外部 Streamable HTTP MCP。外部认证只保存 env 引用,真值留在 Pi 父进程 env;- * 对每个 server 走 initialize → 分页 tools/list,把工具注册成 pi 工具- * (mcp__<server>__<tool>),execute 转发 tools/call。+ * 对每个 server 走 initialize → 分页 tools/list,但模型侧只注册两个稳定网关工具。+ * 调用时再按 server/tool 路由,并把真实 mcp__<server>__<tool> 身份交给 Host 审批与审计。* 3. 会话树:注册 Cindy 私有 command,把 RPC prompt 桥到 ctx.navigateTree。** 协议说明(@modelcontextprotocol/sdk StreamableHTTPServerTransport):@@ -2157,6 +2157,23 @@ interface McpServerRef {};}+const CINDY_MCP_LIST_TOOLS = 'cindy_mcp_list_tools';+const CINDY_MCP_CALL_TOOL = 'cindy_mcp_call_tool';++interface ConnectedMcpTool {+ serverName: string;+ name: string;+ description: string;+ inputSchema: Record<string, unknown>;+ client: McpHttpClient;+}++interface ResolvedMcpGatewayCall {+ qualifiedName: string;+ args: Record<string, unknown>;+ tool: ConnectedMcpTool;+}+class McpBridgeError extends Error {}function safeMcpFailure(error: unknown): string {@@ -2398,7 +2415,274 @@ function mcpContentToPi(content: unknown): Array<Record<string, unknown>> {return out;}-async function connectServer(pi: any, server: McpServerRef, token: string): Promise<number> {+function mcpGatewayKey(serverName: string, toolName: string): string {+ return serverName + '\u0000' + toolName;+}++function recordInput(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' && !Array.isArray(value)+ ? value as Record<string, unknown>+ : {};+}++function schemaHint(schema: Record<string, unknown>): string {+ let rendered = '{}';+ try {+ rendered = JSON.stringify(schema);+ } catch {+ rendered = '{}';+ }+ return rendered.length <= 16_000 ? rendered : rendered.slice(0, 15_999) + '…';+}++class CindyMcpGateway {+ private readonly tools = new Map<string, ConnectedMcpTool>();+ private readonly unavailableServers = new Map<string, string>();+ private readonly disclosedSchemas = new Set<string>();++ add(serverName: string, client: McpHttpClient, tools: any[]): void {+ for (const rawTool of tools) {+ if (!rawTool || typeof rawTool !== 'object' || typeof rawTool.name !== 'string' || !rawTool.name) {+ continue;+ }+ const inputSchema = rawTool.inputSchema && typeof rawTool.inputSchema === 'object'+ ? rawTool.inputSchema as Record<string, unknown>+ : { type: 'object', properties: {}, additionalProperties: true };+ this.tools.set(mcpGatewayKey(serverName, rawTool.name), {+ serverName,+ name: rawTool.name,+ description: typeof rawTool.description === 'string' && rawTool.description.length > 0+ ? rawTool.description+ : 'MCP tool ' + rawTool.name + ' from ' + serverName,+ inputSchema,+ client,+ });+ }+ }++ get size(): number {+ return this.tools.size;+ }++ markUnavailable(serverName: string, reason: string): void {+ this.unavailableServers.set(serverName, reason);+ }++ resolveCall(input: unknown): ResolvedMcpGatewayCall | null {+ const record = recordInput(input);+ const serverName = typeof record.server === 'string' ? record.server : '';+ const toolName = typeof record.tool === 'string' ? record.tool : '';+ if (!serverName || !toolName) return null;+ const tool = this.tools.get(mcpGatewayKey(serverName, toolName));+ if (!tool) return null;+ return {+ qualifiedName: 'mcp__' + serverName + '__' + toolName,+ args: recordInput(record.args),+ tool,+ };+ }++ isSchemaDisclosed(call: ResolvedMcpGatewayCall): boolean {+ return this.disclosedSchemas.has(mcpGatewayKey(call.tool.serverName, call.tool.name));+ }++ list(serverName?: string): Array<{ server: string; name: string; description: string }> {+ return [...this.tools.values()]+ .filter((tool) => !serverName || tool.serverName === serverName)+ .sort((a, b) => a.serverName.localeCompare(b.serverName) || a.name.localeCompare(b.name))+ .map((tool) => ({+ server: tool.serverName,+ name: tool.name,+ description: tool.description,+ }));+ }++ availableServers(): string[] {+ return [...new Set([...this.tools.values()].map((tool) => tool.serverName))].sort();+ }++ unavailable(): Array<{ server: string; reason: string }> {+ return [...this.unavailableServers.entries()]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([server, reason]) => ({ server, reason }));+ }++ private listResult(params: unknown): { content: Array<Record<string, unknown>>; details: unknown } {+ const input = recordInput(params);+ const serverName = typeof input.server === 'string' && input.server.length > 0+ ? input.server+ : undefined;+ const toolName = typeof input.tool === 'string' && input.tool.length > 0+ ? input.tool+ : undefined;+ const tools = this.list(serverName);+ const unavailableReason = serverName+ ? this.unavailableServers.get(serverName)+ : undefined;+ const unavailableServers = this.unavailable();+ let payload: unknown;+ if (toolName && !serverName) {+ payload = {+ ok: false,+ errorCode: 'SERVER_REQUIRED',+ reason: 'Pass both server and tool to inspect one input schema.',+ availableServers: this.availableServers(),+ };+ } else if (serverName && unavailableReason) {+ payload = {+ ok: false,+ errorCode: 'SERVER_UNAVAILABLE',+ requested: serverName,+ reason: unavailableReason,+ availableServers: this.availableServers(),+ };+ } else if (serverName && toolName) {+ const selected = this.tools.get(mcpGatewayKey(serverName, toolName));+ if (!selected) {+ payload = {+ ok: false,+ errorCode: 'UNKNOWN_TOOL',+ requested: { server: serverName, tool: toolName },+ availableTools: tools.map((tool) => tool.name),+ };+ } else {+ this.disclosedSchemas.add(mcpGatewayKey(serverName, toolName));+ payload = {+ ok: true,+ tools: [{+ server: selected.serverName,+ name: selected.name,+ description: selected.description,+ inputSchema: selected.inputSchema,+ }],+ };+ }+ } else if (serverName && tools.length === 0) {+ payload = {+ ok: false,+ errorCode: 'UNKNOWN_SERVER',+ requested: serverName,+ availableServers: this.availableServers(),+ unavailableServers,+ };+ } else {+ payload = {+ ok: true,+ tools,+ ...(unavailableServers.length > 0 ? { unavailableServers } : {}),+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(payload) }],+ details: payload,+ };+ }++ private unknownCallMessage(params: unknown): string {+ const input = recordInput(params);+ const serverName = typeof input.server === 'string' ? input.server : '';+ const scoped = this.list(serverName || undefined);+ const available = (scoped.length > 0 ? scoped : this.list()).map((tool) => ({+ server: tool.server,+ name: tool.name,+ }));+ return 'Unknown Cindy MCP tool. Call cindy_mcp_list_tools first. Available: ' ++ JSON.stringify(available).slice(0, 12_000) + '. Unavailable servers: ' ++ JSON.stringify(this.unavailable()).slice(0, 4_000);+ }++ private async executeCall(params: unknown): Promise<{+ content: Array<Record<string, unknown>>;+ details: unknown;+ }> {+ const resolved = this.resolveCall(params);+ if (!resolved) throw new Error(this.unknownCallMessage(params));+ if (!this.isSchemaDisclosed(resolved)) {+ throw new Error(+ 'Inspect this tool before execution by calling cindy_mcp_list_tools with ' ++ JSON.stringify({ server: resolved.tool.serverName, tool: resolved.tool.name }) + '.',+ );+ }+ let result: any;+ try {+ result = await resolved.tool.client.request('tools/call', {+ name: resolved.tool.name,+ arguments: resolved.args,+ });+ } catch (error) {+ throw new Error(+ 'MCP tool ' + resolved.tool.serverName + '/' + resolved.tool.name + ' failed: ' ++ safeMcpFailure(error) + '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema),+ );+ }+ const content = mcpContentToPi(result?.content);+ if (result?.isError) {+ const message = content+ .map((item) => (typeof item.text === 'string' ? item.text : ''))+ .join('\n')+ .trim();+ throw new Error(+ (message.length > 0 ? message : 'MCP tool returned an error') ++ '. Expected args schema: ' + schemaHint(resolved.tool.inputSchema),+ );+ }+ return { content, details: result?.structuredContent ?? {} };+ }++ register(pi: any): void {+ pi.registerTool({+ name: CINDY_MCP_LIST_TOOLS,+ label: 'Discover Cindy MCP tools',+ description:+ 'List every connected Cindy/MCP capability without loading their parameter schemas into startup context. ' ++ 'Omit arguments to discover names and descriptions. Before invoking a tool, pass its exact server and tool ' ++ 'names here once to inspect that single input schema, then use cindy_mcp_call_tool.',+ parameters: {+ type: 'object',+ properties: {+ server: {+ type: 'string',+ description: 'Optional exact server name. Omit to list tools from every connected server.',+ },+ tool: {+ type: 'string',+ description: 'Optional exact tool name. Requires server and returns that tool\'s input schema.',+ },+ },+ additionalProperties: false,+ },+ execute: async (_toolCallId: string, params: unknown) => this.listResult(params),+ });++ pi.registerTool({+ name: CINDY_MCP_CALL_TOOL,+ label: 'Call a Cindy MCP tool',+ description:+ 'Invoke a tool after inspecting its exact input schema with cindy_mcp_list_tools. Pass the exact server and ' ++ 'tool names plus args as an object. If the server rejects the arguments, the error repeats that schema.',+ parameters: {+ type: 'object',+ properties: {+ server: { type: 'string', description: 'Exact server name from cindy_mcp_list_tools.' },+ tool: { type: 'string', description: 'Exact tool name from cindy_mcp_list_tools.' },+ args: {+ type: 'object',+ description: 'Arguments for the selected tool as a JSON object.',+ additionalProperties: true,+ },+ },+ required: ['server', 'tool', 'args'],+ additionalProperties: false,+ },+ execute: async (_toolCallId: string, params: unknown) => this.executeCall(params),+ });+ }+}++async function connectServer(server: McpServerRef, token: string): Promise<{+ client: McpHttpClient;+ tools: any[];+}> {const client = new McpHttpClient(server, token);await client.initialize();const tools: any[] = [];@@ -2416,41 +2700,7 @@ async function connectServer(pi: any, server: McpServerRef, token: string): Promcursor = nextCursor;}client.finishStartup();- for (const tool of tools) {- const qualifiedName = 'mcp__' + server.name + '__' + tool.name;- const parameters =- tool.inputSchema && typeof tool.inputSchema === 'object'- ? tool.inputSchema- : { type: 'object', properties: {}, additionalProperties: true };- try {- pi.registerTool({- name: qualifiedName,- label: server.name + ': ' + tool.name,- description: typeof tool.description === 'string' && tool.description.length > 0- ? tool.description- : 'MCP tool ' + tool.name + ' from ' + server.name,- parameters,- async execute(_toolCallId: string, params: unknown) {- const result = await client.request('tools/call', {- name: tool.name,- arguments: params ?? {},- });- const content = mcpContentToPi(result?.content);- if (result?.isError) {- const text = content- .map((c) => (typeof c.text === 'string' ? c.text : ''))- .join('\n')- .trim();- throw new Error(text.length > 0 ? text : 'MCP tool ' + tool.name + ' failed');- }- return { content, details: result?.structuredContent ?? {} };- },- });- } catch (err) {- console.error('[cindy-bridge] register ' + qualifiedName + ' failed: ' + String(err));- }- }- return tools.length;+ return { client, tools };}// Pi 内置 find 依赖 fd;PI_OFFLINE=1 时缺失后不会下载。Cindy 已随 Desktop 校验并@@ -2525,6 +2775,7 @@ function rgGlob(}export default async function cindyBridge(pi: any) {+ const mcpGateway = new CindyMcpGateway();// bash 隔离 home 经 resolveBashPackageHome 解析(首次加载读删 + 防篡改 stash,// 扩展重载(#3070)经双重验证取回,而不是拿到 undefined 让 bash 永久 fail-closed)。// 包管理 token 是 bearer 凭证,保持读一次即删、仅闭包持有 —— 不进 globalThis@@ -2914,7 +3165,26 @@ export default async function cindyBridge(pi: any) {// issues a one-shot store grant. Let it reach that boundary in every mode.if (event.toolName === 'cindy_pi_extension') return;if (permission.mode === 'bypassPermissions') return;+ // MCP discovery/one-tool schema inspection only returns metadata already+ // supplied by connected servers. It is the read-only half of the gateway+ // and never executes a capability, so Ask/Auto should not interrupt the user.+ if (event.toolName === CINDY_MCP_LIST_TOOLS) return;if (READONLY_BUILTINS.has(event.toolName) && !credentialRead) return;+ // Pi sees one stable gateway schema, while Host policy and approval UI must+ // continue seeing the real MCP identity and real arguments. That preserves+ // every existing per-server policy without loading each schema at startup.+ const resolvedGatewayCall = event.toolName === CINDY_MCP_CALL_TOOL+ ? mcpGateway.resolveCall(event.input)+ : null;+ const gatewayCall = resolvedGatewayCall && mcpGateway.isSchemaDisclosed(resolvedGatewayCall)+ ? resolvedGatewayCall+ : null;+ // Invalid, unknown, or not-yet-inspected gateway input cannot execute a+ // capability. Let execute() return its deterministic discovery/schema error+ // without showing a misleading permission prompt for the wrapper itself.+ if (event.toolName === CINDY_MCP_CALL_TOOL && !gatewayCall) return;+ const permissionToolName = gatewayCall?.qualifiedName ?? event.toolName;+ const permissionInput = gatewayCall?.args ?? event.input ?? {};let decision: string | undefined;try {// input() is used as a private request/response envelope rather than a@@ -2923,8 +3193,8 @@ export default async function cindyBridge(pi: any) {decision = await ctx.ui.input(PERMISSION_TITLE,JSON.stringify({- toolName: event.toolName,- input: event.input ?? {},+ toolName: permissionToolName,+ input: permissionInput,resolvedCredentialPaths: credentialEvidenceForHost,}),);@@ -2944,14 +3214,22 @@ export default async function cindyBridge(pi: any) {});pi.on('tool_result', async (event: any, ctx: any) => {- if (event.toolName !== 'bash' && !String(event.toolName ?? '').startsWith('mcp__')) return;+ const resolvedGatewayCall = event.toolName === CINDY_MCP_CALL_TOOL+ ? mcpGateway.resolveCall(event.input)+ : null;+ const gatewayCall = resolvedGatewayCall && mcpGateway.isSchemaDisclosed(resolvedGatewayCall)+ ? resolvedGatewayCall+ : null;+ const captureToolName = gatewayCall?.qualifiedName ?? event.toolName;+ const captureInput = gatewayCall?.args ?? event.input ?? {};+ if (captureToolName !== 'bash' && !String(captureToolName ?? '').startsWith('mcp__')) return;try {await ctx.ui.confirm(TURN_CHANGE_CAPTURE_TITLE,JSON.stringify({- toolName: event.toolName,+ toolName: captureToolName,toolUseId: event.toolCallId,- input: event.input ?? {},+ input: captureInput,}),);} catch {@@ -3303,15 +3581,29 @@ export default async function cindyBridge(pi: any) {return;}const token = cfg.token ?? '';+ const servers = Array.isArray(cfg.servers) ? cfg.servers : [];// 全部 server 并行启动:每个 remote 有独立短预算,多个黑洞 provider 也只占一份// startup window,不会串行叠加到 Pi RPC 的 30s ready 超时。- await Promise.all((cfg.servers ?? []).map(async (server) => {+ await Promise.all(servers.map(async (server) => {try {- const count = await connectServer(pi, server, token);- console.error('[cindy-bridge] connected ' + server.name + ' (' + count + ' tools)');+ const connected = await connectServer(server, token);+ mcpGateway.add(server.name, connected.client, connected.tools);+ console.error('[cindy-bridge] connected ' + server.name + ' (' + connected.tools.length + ' tools)');} catch (err) {+ mcpGateway.markUnavailable(server.name, safeMcpFailure(err));console.error('[cindy-bridge] connect ' + server.name + ' failed: ' + safeMcpFailure(err));}}));+ // Keep the capability surface constant at two schemas. Even when every+ // configured server failed startup, discovery remains callable and reports an+ // empty set instead of making MCP capability disappear silently.+ if (servers.length > 0) {+ try {+ mcpGateway.register(pi);+ console.error('[cindy-bridge] MCP gateway ready (' + mcpGateway.size + ' tools)');+ } catch (err) {+ console.error('[cindy-bridge] MCP gateway registration failed: ' + String(err));+ }+ }}`;diff --git a/packages/project-context/README.md b/packages/project-context/README.mdindex 24e2a7440a..ab77da0a31 100644--- a/packages/project-context/README.md+++ b/packages/project-context/README.md@@ -367,7 +367,7 @@ MVP 内置一个 adapter:`claude-code`。### Cindy Desktop(本仓库默认 harness,开箱即用)-Cindy Desktop 已内置自动注入:每次创建新 cc-agent / codex session 时,main 进程会探测 cwd 下是否有 `.cindy/project-knowledge/TOC.md`,存在就把这份预渲染 TOC 包成 `<project-context-toc>` wrapper 注入,缺失则 silently skip。+Cindy Desktop 已内置自动入口:每次创建新的 Claude Code、Codex 或 Pi session 时,main 进程会探测 cwd 下是否有 `.cindy/project-knowledge/TOC.md`。存在且非空时,只把这个文件的短路径提示包成 `<project-context-toc>` wrapper;agent 在任务相关时再读取 TOC 和对应知识文件。TOC 正文不再占用每个 session 的启动上下文,缺失则 silently skip。- **无需任何 UI 开关**:所有用户默认启用(不再走"实验功能"入口)- **目录探测**:以 cwd 为根,命中 `.cindy/project-knowledge/TOC.md` 才触发diff --git a/packages/project-context/src/toc.ts b/packages/project-context/src/toc.tsindex f7c4812883..aceae512d5 100644--- a/packages/project-context/src/toc.ts+++ b/packages/project-context/src/toc.ts@@ -2,10 +2,9 @@* TOC renderer + writer.** Generates `.cindy/project-knowledge/TOC.md`, a pre-rendered index of all- * module/concern knowledge files plus per-entry short summaries. Consumers- * (currently apps/desktop) inject this verbatim into agent system prompts at- * session-create time, replacing the older "read every .md and extract summary- * on the fly" path.+ * module/concern knowledge files plus per-entry short summaries. Consumers use+ * it as the stable on-demand entrypoint; Cindy Desktop injects only its path at+ * session-create time instead of preloading the full body.** Why pre-render (vs. dynamic extraction in the consumer):* - Knowledge files are themselves CI-generated artifacts (update / refresh@@ -14,7 +13,7 @@* distributed to users via pull. No drift, no per-user IO at session start.* - PR review surfaces summary regressions (e.g. agent leaking meta-narration* into "是什么") in the TOC.md diff, before users see bad data.- * - Consumers stay trivial: `fs.readFile(TOC.md)` + a wrapper tag.+ * - Consumers stay trivial: confirm TOC.md exists, then expose its stable path.** Source of truth for each summary is the FIRST PARAGRAPH of the `## 是什么` H2* section in the module's .md. If that section is missing or empty, the entry