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): preserve MCP result context

xuzini-xzn4f6fd026fe0e
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 b5bf21045f..6e47278237 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
@@ -184,6 +184,17 @@ function latestToolResultContent(request: Record<string, unknown>): string {
function scriptedAnthropicTurn(requestBody: string): string {
const toolResultCount = countToolResults(requestBody);
+ if (requestBody.includes('verify MCP structured result')) {
+ const scenario = requestBody.includes('structured failure') ? 'failure'
+ : requestBody.includes('rich failure') ? 'rich-failure' : 'success';
+ const calls = [
+ { name: 'cindy_mcp_list_tools', input: { server: 'cindy_workspace', tool: 'result_payload' } },
+ { name: 'cindy_mcp_call_tool', input: { server: 'cindy_workspace', tool: 'result_payload', args: { scenario } } },
+ ];
+ const call = calls[toolResultCount];
+ return call ? anthropicToolTurn(toolResultCount + 1, call.name, call.input)
+ : anthropicTextTurn(3, 'Result received');
+ }
if (requestBody.includes('local host tool isolation')) {
const calls = [
{ name: 'cindy_mcp_list_tools', input: {} },
@@ -625,6 +636,19 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
})}]};
});
} else if (isWorkspace) {
+ server.registerTool('result_payload', {
+ description: 'Return structured workspace data', inputSchema: { scenario: z.enum(['success', 'failure', 'rich-failure']) },
+ }, async ({ scenario }) => ({
+ content: scenario === 'rich-failure' ? [
+ { type: 'text' as const, text: 'Screenshot of the failing input' },
+ { type: 'image' as const, mimeType: 'image/png',
+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aifoAAAAASUVORK5CYII=' },
+ { type: 'text' as const, text: 'Correct the highlighted field' },
+ ] : [],
+ structuredContent: { status: scenario, resultCanary: 'MCP_STRUCTURED_MODEL_CANARY' },
+ ...(scenario !== 'success' ? { isError: true } : {}),
+ _meta: { privateCanary: 'MCP_CLIENT_ONLY_CANARY' },
+ }));
server.registerTool(
'status',
{ description: 'Read the workspace status', inputSchema: {} },
@@ -1133,6 +1157,30 @@ describe.skipIf(!piAvailable)('PiAgent × cindy-bridge (real pi + MCP bridge + p
},
);
+ it.each(['success', 'failure', 'rich-failure'] as const)(
+ 'preserves MCP structured %s data in the real Pi model request',
+ { timeout: 90_000 },
+ async (scenario) => {
+ const { requests } = await runOneTurn('bypassPermissions',
+ async () => ({ kind: 'permission', behavior: 'allow' }), 'local-multi',
+ 'verify MCP structured result ' + (scenario === 'failure' ? 'structured failure'
+ : scenario === 'rich-failure' ? 'rich failure' : 'success'));
+ expect(requests).toHaveLength(3);
+ const messages = requests.at(-1)!.messages as Array<{ content: Array<Record<string, unknown>> }>;
+ const result = messages.flatMap(message => message.content).filter(block => block.type === 'tool_result').at(-1)!;
+ expect(JSON.stringify(result.content)).toContain('MCP_STRUCTURED_MODEL_CANARY');
+ expect(Boolean(result.is_error)).toBe(scenario !== 'success');
+ if (scenario === 'rich-failure') {
+ const blocks = result.content as Array<Record<string, unknown>>;
+ expect(blocks.map(block => block.type)).toEqual(['text', 'image', 'text', 'text']);
+ expect(blocks[0].text).toBe('Screenshot of the failing input');
+ expect(blocks[1].source).toMatchObject({ type: 'base64', media_type: 'image/png' });
+ expect(blocks[2].text).toBe('Correct the highlighted field');
+ }
+ expect(JSON.stringify(requests)).not.toContain('MCP_CLIENT_ONLY_CANARY');
+ },
+ );
+
it(
"sends a typed teammate message directly without MCP discovery",
{ timeout: 90_000 },
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 813b9bc027..1376df0f04 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
@@ -65,6 +65,49 @@ describe('Pi MCP request lifecycle', () => {
expect(exact.tools[0].inputSchema.properties.value.type).toBe('string');
});
+ it.each([false, true])('keeps structured data model-visible (isError=%s) without exposing private metadata', async (isError) => {
+ const structuredContent = { answer: 42, nextStep: 'retry-after-refresh' };
+ const { call } = gatewayWithFetch(vi.fn(async () => Response.json({ result: {
+ content: [], structuredContent, isError, _meta: { secret: 'client-only' },
+ } })));
+ const result = await call();
+ expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(structuredContent) }]);
+ expect(result.details).toEqual(structuredContent);
+ expect(Boolean(result.isError)).toBe(isError);
+ expect(JSON.stringify(result)).not.toContain('client-only');
+ });
+
+ it('preserves ordered rich error content and appends missing structured data', async () => {
+ const content = [
+ { type: 'text', text: 'Failure screenshot follows' },
+ { type: 'image', data: 'fixture-image', mimeType: 'image/png' },
+ { type: 'text', text: 'The highlighted input needs correction' },
+ ];
+ const { call } = gatewayWithFetch(vi.fn(async () => Response.json({ result: {
+ content, structuredContent: { field: 'email' }, isError: true,
+ } })));
+ await expect(call()).resolves.toMatchObject({
+ isError: true, content: [...content, { type: 'text', text: '{"field":"email"}' }],
+ });
+ });
+
+ it('does not duplicate structured data already serialized in a text block', async () => {
+ const structuredContent = { answer: 42 };
+ const content = [{ type: 'text', text: JSON.stringify(structuredContent, null, 2) }];
+ const { call } = gatewayWithFetch(vi.fn(async () => Response.json({ result: { content, structuredContent } })));
+ await expect(call()).resolves.toEqual({ content, details: structuredContent });
+ });
+
+ it.each([
+ { content: [], expected: [{ type: 'text', text: '(empty result)' }] },
+ { content: [{ type: 'text', text: 'unchanged' }], expected: [{ type: 'text', text: 'unchanged' }] },
+ { content: [{ type: 'resource_link', uri: 'fixture://report', name: 'report' }],
+ expected: [{ type: 'text', text: '{"type":"resource_link","uri":"fixture://report","name":"report"}' }] },
+ ])('keeps the existing unstructured conversion for $content', async ({ content, expected }) => {
+ const { call } = gatewayWithFetch(vi.fn(async () => Response.json({ result: { content } })));
+ await expect(call()).resolves.toEqual({ content: expected, details: {} });
+ });
+
it('waits for card interaction beyond five minutes with one explicit deadline', async () => {
vi.useFakeTimers();
let complete!: (response: Response) => void;
@@ -126,6 +169,8 @@ describe('Pi MCP request lifecycle', () => {
const business = gatewayWithFetch(vi.fn(async () => Response.json({ result: {
isError: true, content: [{ type: 'text', text: 'Plugin unavailable' }],
} })));
- await expect(business.call()).rejects.toThrow(/^Plugin unavailable$/);
+ await expect(business.call()).resolves.toMatchObject({
+ isError: true, content: [{ type: 'text', text: 'Plugin unavailable' }],
+ });
});
});
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 2330159113..28a7210c76 100644
--- a/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
+++ b/packages/maker-core/src/agents/pi/cindy-bridge-source.ts
@@ -2847,7 +2847,7 @@ class McpHttpClient {
}
}
-function mcpContentToPi(content: unknown): Array<Record<string, unknown>> {
+function mcpContentToPi(content: unknown, structuredContent?: unknown): Array<Record<string, unknown>> {
const out: Array<Record<string, unknown>> = [];
if (Array.isArray(content)) {
for (const item of content) {
@@ -2862,6 +2862,17 @@ function mcpContentToPi(content: unknown): Array<Record<string, unknown>> {
}
}
}
+ // Pi details are for rendering/state, not model input. Keep MCP's structured
+ // result visible without duplicating the JSON text supplied by many servers.
+ if (structuredContent !== undefined) {
+ const text = JSON.stringify(structuredContent);
+ const alreadyIncluded = out.some((item) => {
+ if (item.type !== 'text' || typeof item.text !== 'string') return false;
+ if (item.text === text) return true;
+ try { return JSON.stringify(JSON.parse(item.text)) === text; } catch { return false; }
+ });
+ if (!alreadyIncluded) out.push({ type: 'text', text });
+ }
if (out.length === 0) out.push({ type: 'text', text: '(empty result)' });
return out;
}
@@ -3414,6 +3425,7 @@ class CindyMcpGateway {
private async executeResolvedCall(resolved: ResolvedMcpGatewayCall, signal?: AbortSignal): Promise<{
content: Array<Record<string, unknown>>;
details: unknown;
+ isError?: boolean;
}> {
let result: any;
try {
@@ -3429,17 +3441,11 @@ class CindyMcpGateway {
? '. 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',
- );
- }
- return { content, details: result?.structuredContent ?? {} };
+ return {
+ content: mcpContentToPi(result?.content, result?.structuredContent),
+ details: result?.structuredContent ?? {},
+ ...(result?.isError ? { isError: true } : {}),
+ };
}
private async executeCall(params: unknown, signal?: AbortSignal, toolCallId?: string): Promise<{