Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(pi): bind MCP approvals and recover incomplete SSE responses

Chris4f4e7c49a537
diff --git a/docs/dev-rules/pi-harness.md b/docs/dev-rules/pi-harness.md
index 7810d0984c..9fc2fb3e09 100644
--- a/docs/dev-rules/pi-harness.md
+++ b/docs/dev-rules/pi-harness.md
@@ -78,6 +78,8 @@ Cindy 以 `pi --mode rpc` spawn pi 二进制(JSONL/stdio),`translator.ts` 把 pi
按服务重新 initialize + tools/list,复用既有启动期限;并发等待共享一次握手,取消只退出
当前等待。恢复不自动重放 tools/call,不重启 Pi 或其它服务;新工具表替换旧表,定义改变
或删除时拒绝用旧定义继续调用。只恢复启动快照里的服务,不热加载配置变更。
+ 工具批准按 toolCallId 绑定审批时的定义指纹;即使同批前面的发现已披露新定义,也不得
+ 沿用旧批准。SSE 在匹配响应前结束或失效时同样标记连接需恢复,不重放原操作。
- **plan 模式**:自动挂载 Pi 分发包自带的 plan-mode 扩展,无需用户另装。UI 勾选是下一条
消息的一次性意图,与原生运行态分开;`StartSessionOptions.planMode` 设置起始档,
`SendOptions.planMode` 快照决定本轮,切档与 prompt 在同一 RPC 串行段执行。发送后消耗
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.ts
index fcd5a696cb..fe114e3775 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
@@ -430,7 +430,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
const modelRequestBodies: string[] = [];
const modelRequests: Array<Record<string, unknown>> = [];
const opaqueTurnCaptures: Array<{ sessionId: string; provider: string; cwd: string }> = [];
- let recoveryMode: 'disconnect' | 'expired' = 'disconnect';
+ let recoveryMode: 'disconnect' | 'expired' | 'sse-eof' = 'disconnect';
let recoveryWrites = 0;
const recoveryCalls: string[] = [];
const recoveryHandshakes: Array<string | string[] | undefined> = [];
@@ -472,6 +472,11 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
if (body.params.arguments.text === 'write') {
if (recoveryMode === 'expired') { res.writeHead(404).end(); return; }
recoveryWrites++;
+ if (recoveryMode === 'sse-eof') {
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.end('data: {"method":"notifications/progress"}\n\n');
+ return;
+ }
res.destroy();
return;
}
@@ -1092,7 +1097,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
}
}
- it.each(['disconnect', 'expired'] as const)('recovers MCP %s through real Pi without replaying a write', { timeout: 90_000 }, async (mode) => {
+ it.each(['disconnect', 'expired', 'sse-eof'] as const)('recovers MCP %s through real Pi without replaying a write', { timeout: 90_000 }, async (mode) => {
recoveryMode = mode;
recoveryWrites = 0;
recoveryCalls.length = 0;
@@ -1104,7 +1109,7 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
}, 'recovery', 'recover MCP transport', false, 'recovery-' + mode);
expect(recoveryCalls).toEqual(['write', 'inspect']);
expect(recoveryHandshakes).toEqual([undefined, undefined]);
- expect(recoveryWrites).toBe(mode === 'disconnect' ? 1 : 0);
+ expect(recoveryWrites).toBe(mode === 'expired' ? 0 : 1);
expect(approvals.filter(name => name === 'mcp__recovery__echo')).toHaveLength(2);
expect(requestBodies.at(-1)).toContain('not replayed');
expect(requestBodies.at(-1)).toContain('writes=' + recoveryWrites);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
index fa58883b38..7133b22472 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-mcp-client.test.ts
@@ -7,9 +7,12 @@ import { CINDY_BRIDGE_EXTENSION_SOURCE } from '../cindy-bridge-source.js';
// Execute the generated extension's actual client and registered gateway. Pi
// loads this standalone source, so importing a parallel client would miss bugs.
const source = CINDY_BRIDGE_EXTENSION_SOURCE;
+const hookStart = source.indexOf(" pi.on('tool_call', async");
+const hookEnd = source.indexOf('\n });', hookStart) + '\n });'.length;
const compiled = ts.transpileModule(
source.slice(source.indexOf('const CINDY_MCP_LIST_TOOLS'), source.indexOf('// Pi 内置 find 依赖 fd'))
- + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway; globalThis.connect = connectServer;',
+ + '\nglobalThis.Client = McpHttpClient; globalThis.Gateway = CindyMcpGateway; globalThis.connect = connectServer;'
+ + '\nglobalThis.installApproval = (mcpGateway, pi) => {' + source.slice(hookStart, hookEnd) + '\n};',
{ compilerOptions: { module: ts.ModuleKind.None, target: ts.ScriptTarget.ES2022 } },
).outputText;
@@ -19,6 +22,13 @@ function gatewayWithFetch(fetchImpl: typeof fetch) {
// 沙箱没有模块系统:bridge 顶部的 node:crypto import 在切片后丢失,
// 指纹计算用的 createHash 必须由宿主注入。
setTimeout, clearTimeout, createHash,
+ guestToolGate: null, toolsDisabledForTurn: () => false,
+ currentPermissionState: () => ({ mode: 'ask' }),
+ FILE_WRITE_BUILTINS: new Set(), READONLY_BUILTINS: new Set(),
+ CINDY_HOSTED: null, SUBAGENT_RUN_DIR_ENV: 'fixture-run-dir',
+ resolveFileWriteTargetPath: () => null, isCindyShellTool: () => false,
+ resolvedCredentialEvidenceForHost: () => [],
+ PERMISSION_TITLE: 'permission', PERMISSION_ALLOW: 'allow',
};
runInNewContext(compiled, context);
// These unit cases inject fetch to verify response and cancellation semantics
@@ -39,7 +49,12 @@ function gatewayWithFetch(fetchImpl: typeof fetch) {
registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', { server: 'cindy', tool: 'ghost_call' });
const call = (signal?: AbortSignal) => registered.find(t => t.name === 'cindy_mcp_call_tool')
.execute('call', { server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'demo' } }, signal);
+ let approvalHook: any;
+ context.installApproval(gateway, { on: (_event: string, handler: unknown) => { approvalHook = handler; } });
return { call, gateway, client,
+ approve: () => approvalHook({ toolName: 'cindy_mcp_call_tool', toolCallId: 'call',
+ input: { server: 'cindy', tool: 'ghost_call', args: { ghost_id: 'demo' } } },
+ { ui: { input: async () => 'allow' } }),
connect: () => context.connect({ name: 'cindy', url: 'https://example.test/mcp' }, 'fake-token'),
resultHook: (event: unknown) => resultHooks[0]?.(event),
list: (params: unknown = {}, signal?: AbortSignal) => registered.find(t => t.name === 'cindy_mcp_list_tools').execute('list', params, signal) };
@@ -48,6 +63,38 @@ function gatewayWithFetch(fetchImpl: typeof fetch) {
afterEach(() => vi.useRealTimers());
describe('Pi MCP request lifecycle', () => {
+ // r4411121969: previous recovery tests changed definitions inside execute;
+ // this unit drives the real approval hook before a preceding discovery replaces it.
+ it('rejects a changed definition discovered after approval and permits a freshly approved call', async () => {
+ const fetchImpl = vi.fn(async () => Response.json({ result: { content: [{ type: 'text', text: 'ok' }] } }));
+ const h = gatewayWithFetch(fetchImpl);
+ await h.approve();
+ h.client.needsReconnect = true;
+ h.gateway.registerReconnect('cindy', async () => ({ client: h.client,
+ tools: [{ name: 'ghost_call', description: 'New operation', inputSchema: { type: 'object' } }],
+ }));
+ await h.list({ server: 'cindy', tool: 'ghost_call' });
+ await expect(h.call()).rejects.toThrow('tool definition changed');
+ expect(fetchImpl).not.toHaveBeenCalled();
+ h.client.needsReconnect = false;
+ await h.approve();
+ await expect(h.call()).resolves.toMatchObject({ content: [{ text: 'ok' }] });
+ expect(fetchImpl).toHaveBeenCalledTimes(1);
+ });
+
+ // r4411121974: a clean SSE EOF without this request's response must invalidate
+ // the connection, unlike a completed matching response on an open stream.
+ it('recovers on discovery immediately after an SSE stream ends without its response', async () => {
+ const h = gatewayWithFetch(vi.fn(async () => new Response('data: {"method":"notifications/progress"}\n\n',
+ { headers: { 'content-type': 'text/event-stream' } })));
+ const connect = vi.fn(async () => ({ client: h.client, tools: [{ name: 'ready' }] }));
+ h.gateway.registerReconnect('cindy', connect);
+ await expect(h.call()).rejects.toThrow('invalid SSE response');
+ expect(h.client.needsReconnect).toBe(true);
+ expect((await h.list({ server: 'cindy' })).details.tools[0].name).toBe('ready');
+ expect(connect).toHaveBeenCalledTimes(1);
+ });
+
// A transport failure can follow a successful write. Recover the connection
// for a later explicit request, without replaying that ambiguous operation.
it('recovers a lost response on the next call with one handshake and no replay', async () => {
diff --git a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
index ccb5d25179..c7feaa1c6f 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -2930,7 +2930,10 @@ class McpHttpClient {
/** 按 SSE event 增量取当前 JSON-RPC response;server 保持流打开也不阻塞。 */
private async readSseResponse(res: Response, id: number): Promise<any> {
const reader = res.body?.getReader();
- if (!reader) throw new McpBridgeError('invalid SSE response');
+ if (!reader) {
+ this.needsReconnect = true;
+ throw new McpBridgeError('invalid SSE response');
+ }
const decoder = new TextDecoder();
let buffered = '';
const parseEvent = (eventText: string): any | null => {
@@ -2967,11 +2970,13 @@ class McpHttpClient {
if (msg) return msg;
}
if (buffered.length > 1_048_576) {
+ this.needsReconnect = true;
throw new McpBridgeError('invalid SSE response');
}
if (done) {
const msg = parseEvent(buffered);
if (msg) return msg;
+ this.needsReconnect = true;
throw new McpBridgeError('invalid SSE response');
}
}
@@ -3159,6 +3164,7 @@ class CindyMcpGateway {
private readonly disclosedSchemas = new Map<string, string>();
/** 本次调用跳过了权限询问(hook 未披露即放行):按 toolCallId 记账,execute 见此标记一律回路标。 */
private readonly permissionSkippedCalls = new Set<string>();
+ private readonly approvedDefinitions = new Map<string, string>();
private disclosureNotePending = false;
private botMemoryFacadeEnabled = false;
private botHelperFacadeEnabled = false;
@@ -3470,6 +3476,14 @@ class CindyMcpGateway {
return this.disclosedSchemas.get(key) === this.schemaFingerprint(call.tool);
}
+ approvalDefinition(call: ResolvedMcpGatewayCall): string {
+ return mcpGatewayKey(call.tool.serverName, call.tool.name) + ':' + this.schemaFingerprint(call.tool);
+ }
+
+ rememberApproval(toolCallId: unknown, definition: string): void {
+ if (typeof toolCallId === 'string' && toolCallId) this.approvedDefinitions.set(toolCallId, definition);
+ }
+
/**
* Sorted, prompt-ready server/tool names worth re-surfacing after compaction:
* only tools that still exist AND whose stored fingerprint still matches the
@@ -3645,7 +3659,7 @@ class CindyMcpGateway {
JSON.stringify(this.unavailable()).slice(0, 4_000);
}
- private async executeResolvedCall(resolved: ResolvedMcpGatewayCall, signal?: AbortSignal): Promise<{
+ private async executeResolvedCall(resolved: ResolvedMcpGatewayCall, signal?: AbortSignal, approvedDefinition?: string): Promise<{
content: Array<Record<string, unknown>>;
details: unknown;
isError?: boolean;
@@ -3656,7 +3670,9 @@ class CindyMcpGateway {
const current = this.tools.get(mcpGatewayKey(resolved.tool.serverName, resolved.tool.name));
// Approval and disclosure happened against the original definition.
// Never execute a replacement definition under that earlier approval.
- if (!current || (current !== resolved.tool && this.schemaFingerprint(current) !== this.schemaFingerprint(resolved.tool))) {
+ if (!current
+ || (approvedDefinition !== undefined && this.approvalDefinition({ ...resolved, tool: current }) !== approvedDefinition)
+ || (current !== resolved.tool && this.schemaFingerprint(current) !== this.schemaFingerprint(resolved.tool))) {
throw new McpBridgeError('tool definition changed; inspect it with cindy_mcp_list_tools and call again');
}
resolved = { ...resolved, tool: current };
@@ -3690,8 +3706,13 @@ class CindyMcpGateway {
}> {
// 这次调用没问过权限(hook 判未披露时跳过)→ 一律回路标,不看披露状态。
const permissionSkipped = this.consumePermissionSkipped(toolCallId);
+ const approvedDefinition = toolCallId ? this.approvedDefinitions.get(toolCallId) : undefined;
+ if (toolCallId) this.approvedDefinitions.delete(toolCallId);
const resolved = this.resolveCall(params);
if (!resolved) throw new Error(this.unknownCallMessage(params));
+ if (approvedDefinition !== undefined && this.approvalDefinition(resolved) !== approvedDefinition) {
+ throw new McpBridgeError('tool definition changed; inspect it with cindy_mcp_list_tools and call again');
+ }
if (this.requiresNameEnvelope(resolved.tool) && typeof recordInput(resolved.args).name !== 'string') {
// 该工具的 schema 自己声明了必填的字符串 name(即 Cindy 通用 call_tool 的 {name, args}
// 信封), 而模型没给 —— 多半是把内层字段平铺进来了。工具名无法猜, 但正确形态可以一次
@@ -3727,7 +3748,7 @@ class CindyMcpGateway {
);
throw new Error(this.disclosureSignpost(resolved));
}
- return this.executeResolvedCall(resolved, signal);
+ return this.executeResolvedCall(resolved, signal, approvedDefinition);
}
private async executeDirectHelperTool(name: string, params: unknown, signal?: AbortSignal): Promise<{
@@ -3769,6 +3790,8 @@ class CindyMcpGateway {
}
register(pi: any, options: { botMemoryFacade?: boolean } = {}): void {
+ // Aborted turns may approve a call that Pi never executes.
+ pi.on?.('agent_end', () => { this.approvedDefinitions.clear(); });
pi.on?.('tool_result', (event: any) => {
const failure = this.failedResults.get(event.content) ?? this.failedResults.get(event.details);
if (failure) {
@@ -5091,6 +5114,10 @@ export default async function cindyBridge(piApi: any) {
}
const permissionToolName = gatewayCall?.qualifiedName ?? event.toolName;
const permissionInput = gatewayCall?.args ?? event.input ?? {};
+ // Capture before waiting: an earlier discovery in this batch can replace
+ // and disclose the catalog between this approval hook and execute().
+ const approvedDefinition = event.toolName === CINDY_MCP_CALL_TOOL && gatewayCall
+ ? mcpGateway.approvalDefinition(gatewayCall) : undefined;
let decision: string | undefined;
try {
// input() is used as a private request/response envelope rather than a
@@ -5122,6 +5149,7 @@ export default async function cindyBridge(piApi: any) {
reason: permissionDenialReason(decision),
};
}
+ if (approvedDefinition !== undefined) mcpGateway.rememberApproval(event.toolCallId, approvedDefinition);
if (
FILE_WRITE_BUILTINS.has(event.toolName)
&& writeTargetResolved !== null