Skip to content

Commit b18c626

Browse files
committed
fix(code-mode): align final tool result contracts
1 parent e83ca73 commit b18c626

30 files changed

Lines changed: 1556 additions & 803 deletions

‎docs/tools/code-mode.md‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -712,9 +712,12 @@ schema whose hint exposes stable metadata, text, cache state, and nested spill
712712
metadata; `web_search` declares its exact normalized results/answer/error/raw
713713
union as a complete quick-index hint. Filesystem contracts return structured
714714
read text, image, truncation, and optional-not-found outcomes; explicit edit
715-
change state plus diff/patch data; and apply-patch path summaries. When the
716-
quick index declares the fields, one cell can compose discovery and delivery
717-
without a separate inspection turn:
715+
change state plus diff/patch data; and apply-patch path summaries. Missing
716+
canonical daily notes (`memory/YYYY-MM-DD.md`) return an optional `not_found`
717+
result even when `optional` is omitted; other missing paths throw unless
718+
`optional: true` is explicitly supplied. When the quick index declares the
719+
fields, one cell can compose discovery and delivery without a separate
720+
inspection turn:
718721

719722
```javascript
720723
const listed = await conversations_list({ query: "build bot" });
@@ -781,12 +784,16 @@ tool metadata:
781784

782785
```typescript
783786
type McpToolResult = {
784-
content?: unknown[];
787+
content: unknown[];
785788
structuredContent?: unknown;
786789
isError?: boolean;
787-
[key: string]: unknown;
788790
};
789791

792+
type McpResourcesListResult = { resources: unknown[]; nextCursor?: string };
793+
type McpResourcesReadResult = { contents: unknown[] };
794+
type McpPromptsListResult = { prompts: unknown[]; nextCursor?: string };
795+
type McpPromptsGetResult = { messages: unknown[]; description?: string };
796+
790797
declare namespace MCP.github {
791798
/** Return this TypeScript-style API header. */
792799
function $api(toolName?: string, options?: { schema?: boolean }): Promise<McpApiHeader>;
@@ -806,6 +813,15 @@ declare namespace MCP.github {
806813
}
807814
```
808815

816+
MCP tool calls return their original JSON-safe content blocks, including block
817+
annotations and block-level `_meta`, plus top-level `structuredContent` and
818+
`isError` when provided. Top-level MCP `_meta` and private app metadata never
819+
enter the guest. An MCP application failure with `isError: true` still resolves
820+
as a result, so guest code can inspect and recover from it. Resource and prompt
821+
operations instead return their native MCP shapes: `resources.list()` returns
822+
`resources`, `resources.read()` returns `contents`, `prompts.list()` returns
823+
`prompts`, and `prompts.get()` returns `messages` with an optional `description`.
824+
809825
Declaration files are virtual, not written under the workspace or state
810826
directory. For each code-mode `exec` call, OpenClaw builds the run-scoped tool
811827
catalog, keeps the visible MCP entries, renders `mcp/index.d.ts` plus one

‎extensions/qa-lab/src/providers/mock-openai/server.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1155,10 +1155,17 @@ async function buildResponsesPayload(
11551155
language: "javascript",
11561156
code: useApiFiles
11571157
? [
1158-
'const files = await API.list("mcp");',
1159-
'const root = await API.read("mcp/index.d.ts");',
1160-
'const api = await API.read("mcp/fixture.d.ts");',
1161-
'const result = await MCP.fixture.lookupNote({ id: "alpha" });',
1158+
"const [files, root, api, result, failure, resources, resource, prompts, prompt] = await Promise.all([",
1159+
' API.list("mcp"), API.read("mcp/index.d.ts"), API.read("mcp/fixture.d.ts"),',
1160+
' MCP.fixture.lookupNote({ id: "alpha" }), MCP.fixture.lookupNote({ id: "missing" }),',
1161+
' MCP.fixture.resources.list(), MCP.fixture.resources.read({ uri: "memo://fixture/alpha" }),',
1162+
' MCP.fixture.prompts.list(), MCP.fixture.prompts.get({ name: "fixture_brief", arguments: { id: "alpha" } }),',
1163+
"]);",
1164+
'if (result.structuredContent?.note !== "fixture-note-alpha" || result.isError !== false) throw new Error("MCP success lost its top-level result shape");',
1165+
'if (failure.structuredContent?.note !== "missing-note" || failure.isError !== true) throw new Error("MCP resolved failure lost its top-level result shape");',
1166+
'if (result._meta !== undefined || result.content?.[0]?._meta?.proof !== "fixture-content-metadata") throw new Error("MCP result metadata crossed the wrong boundary");',
1167+
'if (!resources.resources?.some((entry) => entry.uri === "memo://fixture/alpha") || resource.contents?.[0]?.text !== "fixture-note-alpha") throw new Error("MCP resources lost their native result shape");',
1168+
'if (!prompts.prompts?.some((entry) => entry.name === "fixture_brief") || prompt.messages?.[0]?.content?.text !== "fixture-note-alpha") throw new Error("MCP prompts lost their native result shape");',
11621169
"return {",
11631170
' marker: "MCP_CODE_MODE_FILE_TOOL_RESULT",',
11641171
" files: files.files.map((file) => file.path),",

‎scripts/e2e/lib/mcp-code-mode-probe-server.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,37 @@ server.tool(
2929
{
3030
id: z.string().describe("Fixture note id to look up."),
3131
},
32+
async ({ id }) => {
33+
const note = notes.get(id);
34+
return {
35+
content: [{
36+
type: "text",
37+
text: note ?? "missing-note",
38+
annotations: { audience: ["assistant"] },
39+
_meta: { proof: "fixture-content-metadata" },
40+
}],
41+
structuredContent: { id, note: note ?? "missing-note" },
42+
isError: note === undefined,
43+
_meta: { private: "fixture-private-metadata" },
44+
};
45+
},
46+
);
47+
48+
server.registerResource(
49+
"fixture_note",
50+
"memo://fixture/alpha",
51+
{ description: "Fixture alpha note", mimeType: "text/plain" },
52+
async (uri) => ({
53+
contents: [{ uri: uri.href, mimeType: "text/plain", text: notes.get("alpha") }],
54+
}),
55+
);
56+
57+
server.registerPrompt(
58+
"fixture_brief",
59+
{ description: "A fixture note briefing", argsSchema: { id: z.string() } },
3260
async ({ id }) => ({
33-
content: [{ type: "text", text: notes.get(id) ?? "missing-note" }],
61+
description: "A fixture note briefing",
62+
messages: [{ role: "user", content: { type: "text", text: notes.get(id) ?? "missing-note" } }],
3463
}),
3564
);
3665

‎src/agents/agent-bundle-mcp-manager.requester-connect.test.ts‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,12 @@ import { createSessionMcpRuntimeManager } from "./agent-bundle-mcp-manager.js";
33
import { materializeBundleMcpToolsForRun } from "./agent-bundle-mcp-materialize.js";
44
import type { CreateSessionMcpRuntime } from "./agent-bundle-mcp-runtime-shared.js";
55
import type { McpToolCatalog, SessionMcpRuntime } from "./agent-bundle-mcp-types.js";
6+
import { applyCodeModeCatalog } from "./code-mode.js";
7+
import {
8+
createCodeModeHarness,
9+
resetCodeModeTestState,
10+
runUntilCompleted,
11+
} from "./code-mode.test-support.js";
612

713
const oauthStatus = vi.hoisted(() => vi.fn());
814
const startAuthorization = vi.hoisted(() => vi.fn());
@@ -87,6 +93,7 @@ describe("requester MCP connect runtime", () => {
8793

8894
afterEach(async () => {
8995
await manager.disposeAll();
96+
resetCodeModeTestState();
9097
});
9198

9299
it("materializes connect before authorization and real tools on the next message", async () => {
@@ -126,6 +133,40 @@ describe("requester MCP connect runtime", () => {
126133
},
127134
},
128135
});
136+
startAuthorization
137+
.mockResolvedValueOnce({
138+
status: "redirect",
139+
authorizationUrl: "https://auth.example/authorize?state=opaque",
140+
})
141+
.mockResolvedValueOnce({ status: "authorized" });
142+
const codeMode = createCodeModeHarness();
143+
applyCodeModeCatalog({
144+
tools: [...codeMode.tools, ...disconnected.tools],
145+
config: codeMode.config,
146+
catalogRef: codeMode.catalogRef,
147+
});
148+
const guest = await runUntilCompleted({
149+
execTool: codeMode.tools[0]!,
150+
waitTool: codeMode.tools[1]!,
151+
code: "return { signIn: await MCP.calendar.connect(), connected: await MCP.calendar.connect() };",
152+
});
153+
expect(guest.status, JSON.stringify(guest)).toBe("completed");
154+
expect(guest.value).toEqual({
155+
signIn: {
156+
content: [
157+
{
158+
type: "text",
159+
text: expect.stringContaining("https://auth.example/authorize?state=opaque"),
160+
},
161+
],
162+
isError: false,
163+
},
164+
connected: {
165+
content: [{ type: "text", text: expect.stringContaining('"calendar" is connected') }],
166+
isError: false,
167+
},
168+
});
169+
expect(disconnected.tools[0]?.resultContentSource).toBe("network");
129170
await disconnected.dispose();
130171

131172
oauthStatus.mockResolvedValue({ state: "authorized" });
@@ -138,4 +179,46 @@ describe("requester MCP connect runtime", () => {
138179
);
139180
await connected.dispose();
140181
});
182+
183+
it("returns requester connection configuration failures as failed MCP guest results", async () => {
184+
const runtime = await manager.getOrCreate({
185+
sessionId: "session-connect-missing-origin",
186+
workspaceDir: "/workspace",
187+
requesterSenderId: "alice",
188+
cfg: {
189+
mcp: {
190+
servers: {
191+
calendar: {
192+
url: "https://mcp.example/rpc",
193+
transport: "streamable-http",
194+
auth: "oauth",
195+
oauth: { identity: "per-requester" },
196+
},
197+
},
198+
},
199+
},
200+
});
201+
const materialized = await materializeBundleMcpToolsForRun({ runtime });
202+
const direct = await materialized.tools[0]!.execute("connect-direct", {});
203+
expect(direct.details).toMatchObject({ status: "error", mcpServer: "calendar" });
204+
205+
const codeMode = createCodeModeHarness();
206+
applyCodeModeCatalog({
207+
tools: [...codeMode.tools, ...materialized.tools],
208+
config: codeMode.config,
209+
catalogRef: codeMode.catalogRef,
210+
});
211+
const guest = await runUntilCompleted({
212+
execTool: codeMode.tools[0]!,
213+
waitTool: codeMode.tools[1]!,
214+
code: "return await MCP.calendar.connect();",
215+
});
216+
expect(guest.status, JSON.stringify(guest)).toBe("completed");
217+
expect(guest.value).toEqual({
218+
content: [{ type: "text", text: expect.stringContaining("gateway.publicOrigin") }],
219+
isError: true,
220+
});
221+
expect(guest.value).not.toHaveProperty("details");
222+
await materialized.dispose();
223+
});
141224
});

‎src/agents/agent-bundle-mcp-materialize.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,15 @@ import type {
2020
McpToolCatalog,
2121
SessionMcpRuntime,
2222
} from "./agent-bundle-mcp-types.js";
23-
import { projectMcpCallToolResult } from "./mcp-content.js";
23+
import {
24+
projectMcpCallToolResult,
25+
setMcpCodeModeGuestResult,
26+
setMcpCodeModeGuestResultFromAgentResult,
27+
} from "./mcp-content.js";
2428
import { isMcpToolAllowed } from "./mcp-tool-filter.js";
2529
import { buildMcpAppCanvasPayload, fetchMcpAppView } from "./mcp-ui-resource.js";
2630
import type { AgentToolResult } from "./runtime/index.js";
31+
import { toToolSearchJsonSafe } from "./tool-search-json.js";
2732
import type { AnyAgentTool } from "./tools/common.js";
2833
function isAppOnlyTool(tool: McpCatalogTool): boolean {
2934
return tool.uiVisibility !== undefined && !tool.uiVisibility.includes("model");
@@ -111,11 +116,21 @@ function toJsonAgentToolResult(params: {
111116
operation: string;
112117
value: unknown;
113118
}): AgentToolResult<unknown> {
114-
return {
119+
const publicValue = toToolSearchJsonSafe(
120+
params.operation === "resources_list" && Array.isArray(params.value)
121+
? { resources: params.value }
122+
: params.operation === "prompts_list" && Array.isArray(params.value)
123+
? { prompts: params.value }
124+
: params.value,
125+
);
126+
if (isRecord(publicValue)) {
127+
delete publicValue._meta;
128+
}
129+
const result: AgentToolResult<unknown> = {
115130
content: [
116131
{
117132
type: "text",
118-
text: JSON.stringify(params.value, null, 2),
133+
text: JSON.stringify(publicValue, null, 2),
119134
},
120135
],
121136
details: {
@@ -124,6 +139,7 @@ function toJsonAgentToolResult(params: {
124139
untrustedMcpOutput: true,
125140
},
126141
};
142+
return setMcpCodeModeGuestResult(result, publicValue);
127143
}
128144

129145
function requireStringArg(input: unknown, key: string): string {
@@ -192,6 +208,7 @@ function addMcpUtilityTool(params: {
192208
description: params.description,
193209
parameters: normalizeToolParameterSchema(params.parameters as never),
194210
executionMode: params.executionMode,
211+
...(params.execute ? { resultContentSource: "network" as const } : {}),
195212
execute:
196213
params.execute ??
197214
(async () => {
@@ -283,6 +300,9 @@ export function buildBundleMcpToolsFromCatalog(params: {
283300
description: tool.description || tool.fallbackDescription,
284301
parameters: normalizeToolParameterSchema(tool.inputSchema),
285302
executionMode,
303+
...(params.createExecute && !sessionDeniedOnly
304+
? { resultContentSource: "network" as const }
305+
: {}),
286306
execute:
287307
(!sessionDeniedOnly ? params.createExecute?.(tool) : undefined) ??
288308
(async () => {
@@ -436,7 +456,7 @@ export async function materializeBundleMcpToolsForRun(params: {
436456
if (!Object.hasOwn(catalog.servers, tool.serverName)) {
437457
const connect = runtime.requesterConnect?.createExecute(tool.serverName);
438458
if (connect) {
439-
return await connect(toolCallId, input);
459+
return setMcpCodeModeGuestResultFromAgentResult(await connect(toolCallId, input));
440460
}
441461
}
442462
runtime.markUsed();

0 commit comments

Comments
 (0)