Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(agents): show an MCP tool call's request and response in session transcripts (#6585)
Wolf Mermelstein15b82e9fa689
diff --git a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsxindex 1ba9dc21ab..1d481185cc 100644--- a/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ElicitationPart.tsx@@ -176,6 +176,7 @@ function ResolvedElicitation(props: { part: ElicitationPartData }) {common={{id: props.part.toolCall ?? String(props.part.requestId),label: reviewed().request.tool,+ server: undefined,status:reviewed().toolOutcome.kind === 'failed' ? 'failed' : 'completed',muted: reviewed().toolOutcome.kind === 'failed',diff --git a/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx b/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsxnew file mode 100644index 0000000000..242a9e3479--- /dev/null+++ b/apps/web/src/features/block-agent/component/parts/ExchangeToolCall.tsx@@ -0,0 +1,46 @@+/**+ * The card for a call the fold has no special rendering for: a tool on an+ * MCP server it does not know, a harness tool this block does not model,+ * ACP's `switch_mode`. What there is to show is the exchange itself - the+ * arguments the agent sent and the result it got - so the body is those,+ * labelled, as JSON.+ *+ * An MCP tool shows its server beside its name (`ReadContent · macro`), the+ * way the chat block's MCP row does; a failed call keeps the fold's error+ * text as its subtitle, the chat block's failed-tool treatment.+ */++import type { ToolDetail } from '@service-agent-fold/generated/types';+import type { JSX } from 'solid-js';+import { FoldedExchange, ToolCard } from '../../ui';+import type { ToolCallCommon } from './shared';++type ExchangeDetail = Extract<ToolDetail, { kind: 'other' }>;++export function ExchangeToolCall(props: {+ detail: ExchangeDetail;+ common: ToolCallCommon;+}): JSX.Element {+ const hasContent = () =>+ props.detail.input != null ||+ props.detail.result != null ||+ Boolean(props.detail.output) ||+ Boolean(props.detail.error);+ return (+ <ToolCard+ title={props.common.label}+ subtitle={props.detail.error ?? props.common.server}+ status={props.common.status}+ muted={props.common.muted}+ trailing={props.common.trailing}+ hasContent={hasContent()}+ >+ <FoldedExchange+ request={props.detail.input}+ response={props.detail.result}+ responseText={props.detail.output}+ error={props.detail.error}+ />+ </ToolCard>+ );+}diff --git a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsxindex 0f03a44983..ff4b225080 100644--- a/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx@@ -19,7 +19,7 @@ import {deserializeToolResponse,} from '@service-cognition/generated/tools/tool';import { createMemo, ErrorBoundary, type JSX, Show } from 'solid-js';-import { FoldedOutput, ToolCard } from '../../ui';+import { FoldedExchange, ToolCard } from '../../ui';import type { ToolCallCommon, ToolCallContext } from './shared';type MacroDetail = Extract<ToolDetail, { kind: 'macro' }>;@@ -76,28 +76,18 @@ export function MacroToolCall(props: {);}-/** The labelled row with the tool's own JSON, for a tool the chat has no component for. */+/**+ * The labelled row with the tool's own JSON - request, response, error - for+ * a tool the chat has no component for.+ */function GenericMacroToolCall(props: {detail: MacroDetail;common: ToolCallCommon;}): JSX.Element {- const body = () => {- const sections: string[] = [];- if (props.detail.input != null) {- sections.push(JSON.stringify(props.detail.input, null, 2));- }- if (props.detail.error != null) {- sections.push(props.detail.error);- } else if (props.detail.output != null) {- sections.push(JSON.stringify(props.detail.output, null, 2));- }- return sections.join('\n\n');- };-return (<ToolCardtitle={props.common.label}- subtitle={props.detail.error ?? undefined}+ subtitle={props.detail.error ?? props.common.server}status={props.common.status}muted={props.common.muted}trailing={props.common.trailing}@@ -107,7 +97,11 @@ function GenericMacroToolCall(props: {Boolean(props.detail.error)}>- <Show when={body()}>{(text) => <FoldedOutput text={text()} />}</Show>+ <FoldedExchange+ request={props.detail.input}+ response={props.detail.output}+ error={props.detail.error}+ /></ToolCard>);}diff --git a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsxindex 116b6a2e87..5472da513b 100644--- a/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx+++ b/apps/web/src/features/block-agent/component/parts/OutputToolCall.tsx@@ -1,7 +1,6 @@/**- * The fallback card for fetch, think, and unmodeled tool kinds: label in the- * row, whatever text the call reported in the body — the chat block's- * GenericTool analog.+ * The card for fetch and think: label in the row, whatever text the call+ * reported in the body — the chat block's GenericTool analog.*/import type { ToolDetail } from '@service-agent-fold/generated/types';@@ -10,7 +9,7 @@ import { FoldedOutput, ToolCard } from '../../ui';import type { ToolCallCommon } from './shared';export function OutputToolCall(props: {- detail: Extract<ToolDetail, { kind: 'fetch' | 'think' | 'other' }>;+ detail: Extract<ToolDetail, { kind: 'fetch' | 'think' }>;common: ToolCallCommon;}) {return (diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsxindex a1e25a2b72..85e6bc53ca 100644--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.test.tsx@@ -96,6 +96,24 @@ vi.mock('../../ui', async () => ({FoldedOutput: (props: { text: string }) => (<pre data-testid="output">{props.text}</pre>),+ FoldedExchange: (props: {+ request?: unknown;+ response?: unknown;+ responseText?: string | null;+ error?: string | null;+ }) => (+ <div data-testid="exchange">+ <pre data-testid="request">+ {props.request == null ? '' : JSON.stringify(props.request, null, 2)}+ </pre>+ <pre data-testid="response">+ {props.response == null+ ? (props.responseText ?? '')+ : JSON.stringify(props.response, null, 2)}+ </pre>+ <pre data-testid="error">{props.error ?? ''}</pre>+ </div>+ ),FoldedPathList: (props: { paths: string[] }) => (<div data-testid="path-list">{props.paths.join(',')}</div>),@@ -155,7 +173,7 @@ describe('ToolCallPart routing', () => {);});- it('shows an MCP tool by its own name, without the server namespace', () => {+ it('shows an MCP tool by its own name, with the server beside it', () => {const rendered = render(() => (<ToolCallPartpart={{@@ -164,12 +182,66 @@ describe('ToolCallPart routing', () => {acpKind: 'other',output: null,input: null,+ result: null,+ error: null,}),name: { kind: 'mcp', server: 'deepwiki', tool: 'ask' },}}/>));expect(rendered.getByTestId('title').textContent).toBe('ask');+ expect(rendered.getByTestId('subtitle').textContent).toBe('deepwiki');+ });++ it('shows an MCP call as its request and response', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={{+ ...toolUse({+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: { documentId: '4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46' },+ result: { content: { text: 'Q3 plan' }, comments: [] },+ error: null,+ }),+ name: { kind: 'mcp', server: 'macro', tool: 'ReadContent' },+ }}+ />+ ));+ expect(rendered.getByTestId('title').textContent).toBe('ReadContent');+ expect(rendered.getByTestId('request').textContent).toContain(+ '"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"'+ );+ expect(rendered.getByTestId('response').textContent).toContain(+ '"text": "Q3 plan"'+ );+ expect(rendered.getByTestId('error').textContent).toBe('');+ });++ it('shows a failed MCP call faded, with the error as subtitle and in the body', () => {+ const rendered = render(() => (+ <ToolCallPart+ part={{+ ...toolUse(+ {+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: {},+ result: null,+ error: 'user declined',+ },+ { status: 'failed' }+ ),+ name: { kind: 'mcp', server: 'ops', tool: 'deploy' },+ }}+ />+ ));+ expect(rendered.getByTestId('tool-card').dataset.muted).toBe('true');+ expect(rendered.getByTestId('subtitle').textContent).toBe('user declined');+ expect(rendered.getByTestId('error').textContent).toBe('user declined');+ expect(rendered.getByTestId('trailing').textContent).toBe('Failed');});it('renders an edit with computed +/− counts and the diff body', () => {@@ -200,7 +272,7 @@ describe('ToolCallPart routing', () => {expect(rendered.getByTestId('path-list').textContent).toBe('a.rs,b.rs');});- it('routes unmodeled kinds to the output fallback', () => {+ it('routes unmodeled kinds to the exchange card, with reported text as the response', () => {const rendered = render(() => (<ToolCallPartpart={toolUse({@@ -208,10 +280,21 @@ describe('ToolCallPart routing', () => {acpKind: 'custom_tool',output: 'raw result',input: null,+ result: null,+ error: null,})}/>));- expect(rendered.getByTestId('body').textContent).toContain('raw result');+ expect(rendered.getByTestId('request').textContent).toBe('');+ expect(rendered.getByTestId('response').textContent).toBe('raw result');+ });++ it('routes fetch and think to the plain output card', () => {+ const rendered = render(() => (+ <ToolCallPart part={toolUse({ kind: 'fetch', output: 'page body' })} />+ ));+ expect(rendered.getByTestId('output').textContent).toBe('page body');+ expect(rendered.queryByTestId('exchange')).toBeNull();});});@@ -281,7 +364,10 @@ describe('ToolCallPart Macro tools', () => {));expect(rendered.queryByTestId('macro-tool')).toBeNull();expect(rendered.getByTestId('title').textContent).toBe('BrandNewTool');- expect(rendered.getByTestId('body').textContent).toContain(+ expect(rendered.getByTestId('request').textContent).toContain(+ '"anything": 1'+ );+ expect(rendered.getByTestId('response').textContent).toContain('"result": "ok"');});diff --git a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsxindex 545cbdf235..5688f55780 100644--- a/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx+++ b/apps/web/src/features/block-agent/component/parts/ToolCallPart.tsx@@ -13,6 +13,7 @@ import type { JSX } from 'solid-js';import { match } from 'ts-pattern';import { settledToolStatus } from '../../ui';import { EditToolCall } from './EditToolCall';+import { ExchangeToolCall } from './ExchangeToolCall';import { MacroToolCall } from './MacroToolCall';import { OutputToolCall } from './OutputToolCall';import { PathsToolCall } from './PathsToolCall';@@ -23,6 +24,7 @@ import {type ToolCallContext,type ToolUsePart,toolLabel,+ toolServer,} from './shared';import { TerminalToolCall } from './TerminalToolCall';import { UserToolCall } from './UserToolCall';@@ -43,6 +45,7 @@ export function ToolCallPart(props: {const common = (): ToolCallCommon => ({id: props.part.id,label: toolLabel(props.part.name),+ server: toolServer(props.part.name),status: status(),muted: failed(),trailing: failed() ? <span class="text-ink">Failed</span> : undefined,@@ -61,9 +64,12 @@ export function ToolCallPart(props: {.with({ kind: 'search' }, (detail) => (<SearchToolCall detail={detail} common={common()} />))- .with({ kind: 'fetch' }, { kind: 'think' }, { kind: 'other' }, (detail) => (+ .with({ kind: 'fetch' }, { kind: 'think' }, (detail) => (<OutputToolCall detail={detail} common={common()} />))+ .with({ kind: 'other' }, (detail) => (+ <ExchangeToolCall detail={detail} common={common()} />+ )).with({ kind: 'macro' }, (detail) => (<MacroToolCalldetail={detail}diff --git a/apps/web/src/features/block-agent/component/parts/shared.ts b/apps/web/src/features/block-agent/component/parts/shared.tsindex 53ff547d60..d5314d8a81 100644--- a/apps/web/src/features/block-agent/component/parts/shared.ts+++ b/apps/web/src/features/block-agent/component/parts/shared.ts@@ -37,6 +37,8 @@ export type ToolCallCommon = {/** The ACP tool call id. */id: string;label: string;+ /** The MCP server the tool was reached over, for a tool that was. */+ server: string | undefined;status: ToolStatus;/** The chat block's failed treatment: faded row, quiet trailing label. */muted: boolean;@@ -51,6 +53,11 @@ export function toolLabel(name: ToolName): string {return name.kind === 'mcp' ? name.tool : name.name;}+/** The MCP server a tool was reached over, when it was one. */+export function toolServer(name: ToolName): string | undefined {+ return name.kind === 'mcp' ? name.server : undefined;+}+/** Subtitle for a call that touched paths: the path, or how many. */export function pathsSubtitle(paths: string[]): string | undefined {if (paths.length === 0) return undefined;diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsxindex 06b5c4f525..c1f8c6d265 100644--- a/apps/web/src/features/block-agent/debug/Gallery.tsx+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx@@ -303,6 +303,75 @@ const FIXTURE_MESSAGE: FoldedMessage = {error: null,},},+ // An MCP call the fold has no model for - a Cursor session reaching+ // Macro's server, whose exchange is the request and response JSON.+ {+ kind: 'tool_use',+ id: 'demo-mcp-macro',+ name: { kind: 'mcp', server: 'macro', tool: 'ReadChannelThread' },+ status: 'completed',+ detail: {+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: {+ channelId: '0195d2dd-5de9-71f2-9d59-5d9734f1adb7',+ threadId: '01a0b102-3e01-7166-92ca-e5a4b11dace6',+ limit: 20,+ },+ result: {+ channelName: 'feature-requests',+ messages: [+ {+ id: '01a0b16e-95d9-79a8-ace0-2dc075b7d49f',+ sender: 'macro|[email protected]',+ text: 'references for agents so i know where they were dispatched from',+ sentAt: '2026-09-17T22:41:03Z',+ },+ {+ id: '01a0b17a-db3f-75d1-86d9-0d8e86b5106b',+ sender: 'macro|[email protected]',+ text: 'would be nice to be able to scroll context/copy the entire thing',+ sentAt: '2026-09-17T22:47:19Z',+ },+ ],+ hasMore: false,+ },+ error: null,+ },+ },+ {+ kind: 'tool_use',+ id: 'demo-mcp-deepwiki',+ name: { kind: 'mcp', server: 'deepwiki', tool: 'ask_question' },+ status: 'completed',+ detail: {+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: {+ repoName: 'sst/opencode',+ question: 'How are tool calls rendered in the session UI?',+ },+ result:+ 'Tool calls render through `basic-tool-v2.tsx`: one collapsible row per call, with the tool-specific body mounted on expansion.',+ error: null,+ },+ },+ {+ kind: 'tool_use',+ id: 'demo-mcp-refused',+ name: { kind: 'mcp', server: 'ops', tool: 'deploy' },+ status: 'failed',+ detail: {+ kind: 'other',+ acpKind: 'other',+ output: null,+ input: { environment: 'production', service: 'agent-fold' },+ result: null,+ error: 'user declined',+ },+ },{kind: 'tool_use',id: 'demo-email',diff --git a/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsx b/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsxnew file mode 100644index 0000000000..13edf2cfc3--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedExchange.test.tsx@@ -0,0 +1,127 @@+/** @vitest-environment jsdom */++import { cleanup, render, waitFor } from '@solidjs/testing-library';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { exchangeText, FoldedExchange } from './FoldedExchange';++vi.mock('@phosphor/copy.svg', () => ({ default: () => <svg /> }));+vi.mock('@phosphor/check.svg', () => ({ default: () => <svg /> }));++afterEach(cleanup);++const section = (view: ReturnType<typeof render>, label: string) =>+ view.container.querySelector<HTMLElement>(+ `[data-exchange-section="${label}"]`+ );++describe('FoldedExchange', () => {+ it('shows the request and a JSON response as labelled, pretty-printed sections', () => {+ const view = render(() => (+ <FoldedExchange+ request={{ documentId: 'doc-1', limit: 5 }}+ response={{ content: { text: 'Q3 plan' }, ok: true, count: null }}+ />+ ));+ const request = section(view, 'request');+ expect(request?.textContent).toContain('Request');+ expect(request?.querySelector('pre')?.textContent).toBe(+ JSON.stringify({ documentId: 'doc-1', limit: 5 }, null, 2)+ );+ const response = section(view, 'response');+ expect(response?.querySelector('pre')?.textContent).toBe(+ JSON.stringify(+ { content: { text: 'Q3 plan' }, ok: true, count: null },+ null,+ 2+ )+ );+ expect(section(view, 'error')).toBeNull();+ });++ it('lights JSON by token kind', () => {+ const view = render(() => (+ <FoldedExchange request={{ name: 'x', n: 1, on: true, none: null }} />+ ));+ const pre = section(view, 'request')?.querySelector('pre');+ const classes = (selector: string) =>+ [...(pre?.querySelectorAll(selector) ?? [])].map((el) => el.textContent);+ expect(classes('.text-cyan')).toEqual(['"name"', '"n"', '"on"', '"none"']);+ expect(classes('.text-green')).toEqual(['"x"']);+ expect(classes('.text-orange')).toEqual(['1', 'true', 'null']);+ });++ it('shows a string response as its text, unquoted and unlit', () => {+ const view = render(() => (+ <FoldedExchange response="Launching skill: hexagonal-architecture" />+ ));+ const pre = section(view, 'response')?.querySelector('pre');+ expect(pre?.textContent).toBe('Launching skill: hexagonal-architecture');+ expect(pre?.querySelector('span')).toBeNull();+ });++ it('falls back to reported text when there is no structured response', () => {+ const view = render(() => (+ <FoldedExchange responseText="1 match in src/a.rs" />+ ));+ expect(section(view, 'response')?.querySelector('pre')?.textContent).toBe(+ '1 match in src/a.rs'+ );+ expect(section(view, 'request')).toBeNull();+ });++ it('shows nothing for slots the call did not report', () => {+ const view = render(() => (+ <FoldedExchange request={null} response={null} responseText={null} />+ ));+ expect(view.container.querySelectorAll('section')).toHaveLength(0);+ });++ it('shows an error in its own section, read as a failure', () => {+ const view = render(() => (+ <FoldedExchange request={{}} error="permission denied" />+ ));+ const error = section(view, 'error');+ expect(error?.querySelector('pre')?.textContent).toBe('permission denied');+ expect(+ error?.querySelector('pre')?.classList.contains('text-failure')+ ).toBe(true);+ // A tool that takes nothing still made a request.+ expect(section(view, 'request')?.querySelector('pre')?.textContent).toBe(+ '{}'+ );+ });++ it('copies a section whole', async () => {+ const writeText = vi.fn(() => Promise.resolve());+ Object.defineProperty(navigator, 'clipboard', {+ value: { writeText },+ configurable: true,+ });+ const view = render(() => (+ <FoldedExchange response={{ answer: 42, nested: { deep: [1, 2] } }} />+ ));+ view.getByRole('button', { name: 'Copy response' }).click();+ expect(writeText).toHaveBeenCalledWith(+ JSON.stringify({ answer: 42, nested: { deep: [1, 2] } }, null, 2)+ );+ // The button says so for a moment, then offers to copy again.+ await waitFor(() =>+ expect(view.getByRole('button', { name: 'Copied' })).toBeTruthy()+ );+ await waitFor(+ () =>+ expect(+ view.getByRole('button', { name: 'Copy response' })+ ).toBeTruthy(),+ { timeout: 3000 }+ );+ });+});++describe('exchangeText', () => {+ it('pretty-prints JSON and leaves strings alone', () => {+ expect(exchangeText({ a: 1 })).toBe('{\n "a": 1\n}');+ expect(exchangeText('plain')).toBe('plain');+ expect(exchangeText([1, 'two'])).toBe('[\n 1,\n "two"\n]');+ });+});diff --git a/apps/web/src/features/block-agent/ui/FoldedExchange.tsx b/apps/web/src/features/block-agent/ui/FoldedExchange.tsxnew file mode 100644index 0000000000..04a7231de5--- /dev/null+++ b/apps/web/src/features/block-agent/ui/FoldedExchange.tsx@@ -0,0 +1,198 @@+/**+ * The exchange a tool call was: the request the agent made and the response+ * it got, each labelled, as JSON lit the way the code gallery lights its+ * snippets, with a copy button per section. The body for a call the fold has+ * no special rendering for - a tool on an MCP server, a harness tool this+ * block does not model - where the chat block would show raw JSON.+ */++import { jsonLanguage } from '@codemirror/lang-json';+import { highlightCode, tagHighlighter, tags } from '@lezer/highlight';+import Check from '@phosphor/check.svg';+import Copy from '@phosphor/copy.svg';+import { Button } from '@ui';+import {+ createMemo,+ createSignal,+ For,+ type JSX,+ onCleanup,+ Show,+} from 'solid-js';++export interface FoldedExchangeProps {+ /** The tool's arguments; `null` or `undefined` when the call reported none. */+ request?: unknown;+ /** The tool's result, when it reported one as JSON. */+ response?: unknown;+ /** The text the tool reported, for a call whose result is not JSON. */+ responseText?: string | null;+ /** Why the call failed, when it did. */+ error?: string | null;+}++/**+ * Above this many characters a payload is shown plain: lighting it would+ * mean a span per token of something nobody reads token by token.+ */+const HIGHLIGHT_LIMIT = 100_000;++type Token = { text: string; class: string };++const highlighter = tagHighlighter([+ { tag: tags.propertyName, class: 'text-cyan' },+ { tag: tags.string, class: 'text-green' },+ { tag: [tags.number, tags.bool, tags.null], class: 'text-orange' },+ {+ tag: [tags.punctuation, tags.bracket, tags.separator],+ class: 'text-ink-extra-muted',+ },+]);++/** The text split into lines of lit tokens, or plain lines past the limit. */+function tokenizeJson(code: string): Token[][] {+ if (code.length > HIGHLIGHT_LIMIT) {+ return code.split('\n').map((line) => [{ text: line, class: '' }]);+ }+ const lines: Token[][] = [[]];+ highlightCode(+ code,+ jsonLanguage.parser.parse(code),+ highlighter,+ (text, classes) => lines[lines.length - 1]!.push({ text, class: classes }),+ () => lines.push([])+ );+ return lines;+}++/**+ * A payload as the text to show and copy: pretty-printed JSON, or - for a+ * result that is one string, which is how a tool reporting prose arrives -+ * the string itself.+ */+export function exchangeText(value: unknown): string {+ return typeof value === 'string' ? value : JSON.stringify(value, null, 2);+}++/** Whether a payload slot carries anything to show. */+function present(value: unknown): boolean {+ return value !== undefined && value !== null;+}++export function FoldedExchange(props: FoldedExchangeProps): JSX.Element {+ const responseText = () =>+ present(props.response)+ ? exchangeText(props.response)+ : (props.responseText ?? undefined);+ return (+ <div class="flex flex-col gap-2">+ <Show when={present(props.request)}>+ <Section+ label="Request"+ text={exchangeText(props.request)}+ json={typeof props.request !== 'string'}+ />+ </Show>+ <Show when={responseText()}>+ {(text) => (+ <Section+ label="Response"+ text={text()}+ json={present(props.response) && typeof props.response !== 'string'}+ />+ )}+ </Show>+ <Show when={props.error}>+ {(error) => <Section label="Error" text={error()} failed />}+ </Show>+ </div>+ );+}++function Section(props: {+ label: string;+ text: string;+ /** Light the text as JSON; plain otherwise. */+ json?: boolean;+ /** Read as a failure. */+ failed?: boolean;+}): JSX.Element {+ const lines = createMemo(() => (props.json ? tokenizeJson(props.text) : []));+ return (+ <section+ class="flex min-w-0 flex-col gap-1"+ aria-label={props.label}+ data-exchange-section={props.label.toLowerCase()}+ >+ <div class="flex items-center justify-between gap-2">+ <span class="text-[10px] font-medium tracking-wide text-ink-extra-muted uppercase">+ {props.label}+ </span>+ <CopyButton+ text={props.text}+ label={`Copy ${props.label.toLowerCase()}`}+ />+ </div>+ <pre+ class="max-h-96 overflow-auto rounded bg-surface p-2 font-mono text-xs whitespace-pre-wrap wrap-break-word"+ classList={{+ 'text-failure': props.failed,+ 'text-ink-muted': !props.failed,+ }}+ >+ <Show when={props.json} fallback={props.text}>+ <For each={lines()}>+ {(tokens, index) => (+ <>+ <Show when={index() > 0}>{'\n'}</Show>+ <For each={tokens}>+ {(token) => (+ <span class={token.class || undefined}>{token.text}</span>+ )}+ </For>+ </>+ )}+ </For>+ </Show>+ </pre>+ </section>+ );+}++function CopyButton(props: { text: string; label: string }): JSX.Element {+ const [copied, setCopied] = createSignal(false);+ let timer: ReturnType<typeof setTimeout> | undefined;+ onCleanup(() => clearTimeout(timer));++ const copy = async () => {+ try {+ await navigator.clipboard.writeText(props.text);+ } catch (error) {+ console.error('Failed to copy to clipboard', error);+ return;+ }+ setCopied(true);+ clearTimeout(timer);+ timer = setTimeout(() => setCopied(false), 2000);+ };++ return (+ <Button+ type="button"+ variant="ghost"+ size="icon-xs"+ noTouchResize+ class="shrink-0 text-ink-extra-muted hover:text-ink-muted"+ label={copied() ? 'Copied' : props.label}+ onMouseDown={(event) => event.preventDefault()}+ onClick={(event) => {+ event.stopPropagation();+ void copy();+ }}+ >+ <Show when={copied()} fallback={<Copy />}>+ <Check class="text-success" />+ </Show>+ </Button>+ );+}diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.tsindex 3ee51bb16d..00cbf7aca9 100644--- a/apps/web/src/features/block-agent/ui/index.ts+++ b/apps/web/src/features/block-agent/ui/index.ts@@ -26,6 +26,11 @@ export {type ElicitationFormProps,} from './ElicitationForm';export { FoldedAnsiText } from './FoldedAnsiText';+export {+ exchangeText,+ FoldedExchange,+ type FoldedExchangeProps,+} from './FoldedExchange';export { FoldedOutput } from './FoldedOutput';export { FoldedPathList } from './FoldedPathList';export { FoldedTerminal } from './FoldedTerminal';diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.tsindex a7bd7ad1b1..2a31afa299 100644--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts@@ -916,19 +916,33 @@ export type ToolDetail =output: string | null;}/**- * Anything else: ACP's `switch_mode`, and any kind - including `other`- * itself, [`ToolKind`](agent_client_protocol::ToolKind)'s default for a- * call that names no kind at all - this fold has no special rendering- * for.+ * Anything else: ACP's `switch_mode`, a tool from an MCP server the fold+ * knows nothing about, and any kind - including `other` itself,+ * [`ToolKind`](agent_client_protocol::ToolKind)'s default for a call+ * that names no kind at all - this fold has no special rendering for.+ * What a reader wants is the exchange itself: the request the agent+ * made and the response it got, as JSON.*/| {kind: 'other';/** ACP's tool kind, as its wire string. */acpKind: string;- /** Text the call reported, when any. */+ /** Text the call reported in its content blocks, when any. */output: string | null;- /** The tool's input, when reported. */+ /**+ * The tool's own arguments, when reported - out of any wrapper the+ * harness put around them.+ */input: unknown;+ /**+ * The tool's own result, when the harness reported one in+ * `rawOutput` - out of the harness's wrapper and MCP's envelope, so+ * an MCP tool's `structuredContent` (or its text, parsed when it is+ * JSON) arrives as the JSON the tool returned.+ */+ result: unknown;+ /** The error text, when the harness's wrapper reported failure. */+ error: string | null;}/*** A Macro tool the fold knows by name - reached over Macro's MCPdiff --git a/crates/agent_fold/src/bin/fold_jsonl.rs b/crates/agent_fold/src/bin/fold_jsonl.rsindex f642404d00..69a74d270d 100644--- a/crates/agent_fold/src/bin/fold_jsonl.rs+++ b/crates/agent_fold/src/bin/fold_jsonl.rs@@ -473,13 +473,20 @@ fn render_tool(label: &str, status: ToolStatus, detail: &ToolDetail) -> String {kind,output,input,+ result,+ error,} => {let _ = writeln!(out, "{}", indent(&format!("kind: {kind}")));- if let Some(output) = output {+ if let Some(input) = input {+ let _ = writeln!(out, "{}", indent(&format!("input: {}", pretty(input))));+ }+ if let Some(result) = result {+ let _ = writeln!(out, "{}", indent(&format!("result: {}", pretty(result))));+ } else if let Some(output) = output {let _ = writeln!(out, "{}", indent(output.trim_end()));}- if let Some(input) = input {- let _ = writeln!(out, "{}", indent(&pretty(input)));+ if let Some(error) = error {+ let _ = writeln!(out, "{}", indent(&format!("error: {error}")));}}ToolDetail::Macro {diff --git a/crates/agent_fold/src/domain/fold/tool_call.rs b/crates/agent_fold/src/domain/fold/tool_call.rsindex 6fb50d27ea..5bf30aa23f 100644--- a/crates/agent_fold/src/domain/fold/tool_call.rs+++ b/crates/agent_fold/src/domain/fold/tool_call.rs@@ -183,11 +183,31 @@ pub(super) fn tool_detail(reader: &dyn HarnessReader, frame: &ToolFrame<'_>) ->ToolKind::Think => ToolDetail::Think {output: frame.content_text(),},- other => ToolDetail::Other {- kind: tool_kind_name(other).to_owned(),- output: frame.content_text(),- input: frame.raw_input.cloned(),- },+ other => {+ let (result, error) = tool_output(reader, frame);+ ToolDetail::Other {+ kind: tool_kind_name(other).to_owned(),+ output: frame.content_text(),+ input: reader.tool_input(frame),+ result,+ error,+ }+ }+ }+}++/// A frame's `rawOutput` as the tool's own result and the wrapper's error,+/// through the harness's reading. `(None, None)` when the frame carries no+/// output; a result the wrapper reports as empty is `None` too, so a reader+/// never shows a `null` response for a call that reported nothing.+fn tool_output(+ reader: &dyn HarnessReader,+ frame: &ToolFrame<'_>,+) -> (Option<serde_json::Value>, Option<String>) {+ match frame.raw_output.map(|raw| reader.unwrap_tool_output(raw)) {+ None => (None, None),+ Some((serde_json::Value::Null, error)) => (None, error),+ Some((value, error)) => (Some(value), error),}}@@ -199,7 +219,7 @@ pub(super) fn macro_detail(reader: &dyn HarnessReader, frame: &ToolFrame<'_>) ->Some((value, error)) => (Some(value), error),};ToolDetail::Macro {- input: frame.raw_input.cloned().unwrap_or(serde_json::Value::Null),+ input: reader.tool_input(frame).unwrap_or(serde_json::Value::Null),output,error,}@@ -216,7 +236,7 @@ pub(super) fn user_tool_detail(frame: &ToolFrame<'_>,) -> ToolDetail {ToolDetail::UserTool {- input: frame.raw_input.cloned().unwrap_or(serde_json::Value::Null),+ input: reader.tool_input(frame).unwrap_or(serde_json::Value::Null),outcome: frame.raw_output.map_or(UserToolOutcome::Pending, |raw| {harness::user_tool_outcome(reader, tool, raw)}),@@ -240,8 +260,8 @@ pub(super) fn patch_macro_detail(output,error,} => {- if let Some(found) = frame.raw_input {- *input = found.clone();+ if let Some(found) = reader.tool_input(frame) {+ *input = found;}if let Some(raw) = frame.raw_output {let (value, failure) = reader.unwrap_tool_output(raw);@@ -250,8 +270,8 @@ pub(super) fn patch_macro_detail(}}ToolDetail::UserTool { input, outcome } => {- if let Some(found) = frame.raw_input {- *input = found.clone();+ if let Some(found) = reader.tool_input(frame) {+ *input = found;}if let Some(raw) = frame.raw_output {// The detail says this is a user tool, so the name's short@@ -325,13 +345,26 @@ pub(super) fn patch_detail(*output = Some(found);}}- ToolDetail::Other { input, output, .. } => {- if let Some(found) = frame.raw_input {- *input = Some(found.clone());+ ToolDetail::Other {+ input,+ output,+ result,+ error,+ ..+ } => {+ if let Some(found) = reader.tool_input(frame) {+ *input = Some(found);}if let Some(found) = frame.content_text() {*output = Some(found);}+ // A harness sends the result whole each time, so both replace:+ // an update that carries the outcome carries all of it.+ if frame.raw_output.is_some() {+ let (found, failure) = tool_output(reader, frame);+ *result = found;+ *error = failure;+ }}// Patched by `patch_macro_detail` / `patch_subagent_detail`, which// have the name and the harness's result shapes to hand.diff --git a/crates/agent_fold/src/domain/harness.rs b/crates/agent_fold/src/domain/harness.rsindex da9d90d6d5..5d45642bbb 100644--- a/crates/agent_fold/src/domain/harness.rs+++ b/crates/agent_fold/src/domain/harness.rs@@ -243,6 +243,16 @@ pub trait HarnessReader: Sync {macro_tools::mcp_tool(name)}+ /// A tool's own arguments, out of whatever this harness wrapped them in+ /// when it wrote `rawInput`. The neutral reading is `rawInput` as it is:+ /// most harnesses write the arguments bare, and only a harness that+ /// routes every external tool through one dispatcher of its own (Cursor's+ /// `mcp`) has a wrapper to take off. `None` when the frame carries no+ /// input.+ fn tool_input(&self, frame: &ToolFrame<'_>) -> Option<Value> {+ frame.raw_input.cloned()+ }+/// An external tool's own result, out of whatever this harness wrapped it/// in when it wrote `rawOutput`, plus the error text when the wrapper/// reported failure. The neutral reading is MCP's envelope.diff --git a/crates/agent_fold/src/domain/harness/cursor.rs b/crates/agent_fold/src/domain/harness/cursor.rsindex 41e6b253e6..8cbd090322 100644--- a/crates/agent_fold/src/domain/harness/cursor.rs+++ b/crates/agent_fold/src/domain/harness/cursor.rs@@ -37,6 +37,26 @@//! steps into the subagent's children and takes the closing prose as its//! answer, so the transcript reads like the child had streamed.//!+//! Every external tool goes through one dispatcher tool, `mcp`, so that is+//! the only name the wire ever gives an MCP call. Which tool was really+//! called is in the arguments, beside the tool's own:+//!+//! ```json+//! { "name": "macro-ReadContent", "toolName": "ReadContent",+//! "serverIdentifier": "macro", "providerIdentifier": "macro",+//! "toolCallId": "call_…", "args": { "documentId": "…" } }+//! ```+//!+//! and the result is MCP's, in Cursor's spelling, under the translator's+//! `result` key: `{ "result": { "success": { "content": [{ "text": { "text":+//! "…" } }], "structuredContent": … } } }`, or one of the failure variants+//! (`error`, `rejected`, `permissionDenied`, `toolNotFound`,+//! `serverNotFound`). The reader names the call `server`/`tool`, hands the+//! fold the tool's own arguments without the dispatcher's, and unwraps the+//! result to what the tool returned, so a reader sees the exchange and not+//! the plumbing. The arguments arrive on the first update rather than the+//! announcement, so the name is patched in when they do.+//!//! Every shape is a serde type below and read by deserializing, never by//! walking `Value`s. A field the types do not name is ignored; a frame they//! cannot read is "no information", same as every reader. Proto oneofs are@@ -48,9 +68,9 @@ use std::collections::BTreeMap;use lazy_regex::regex_is_match;use serde::Deserialize;use serde::de::IgnoredAny;-use serde_json::Value;+use serde_json::{Map, Value};-use super::{HarnessReader, SubagentInput, ToolFrame, generic, raw};+use super::{HarnessReader, SubagentInput, ToolFrame, generic, mcp, raw};use crate::domain::model::{AnsiText, FileDiff, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStatus, ToolUseId,};@@ -58,11 +78,44 @@ use crate::domain::model::{/// Reader for Cursor's conventions.pub struct Cursor;+/// The dispatcher tool every MCP call is made through.+const MCP_TOOL: &str = "mcp";+impl HarnessReader for Cursor {fn announces(&self, name: &str) -> bool {regex_is_match!(r"(?i)cursor", name)}+ /// An `mcp` call's real name, `server`/`tool`, once its arguments have+ /// arrived. Any other title is the name, as the generic reading has it.+ fn reported_tool_name(&self, frame: &ToolFrame<'_>) -> Option<ToolName> {+ if frame.title.is_some_and(|title| title != MCP_TOOL) {+ return None;+ }+ McpArguments::read(frame.raw_input).map(McpArguments::into_name)+ }++ /// The tool's own arguments: for an `mcp` call, out of the dispatcher's+ /// envelope; for anything else, `rawInput` as it is.+ fn tool_input(&self, frame: &ToolFrame<'_>) -> Option<Value> {+ let raw_input = frame.raw_input?;+ Some(match McpArguments::read(Some(raw_input)) {+ Some(_) => McpArguments::tool_input(raw_input),+ None => raw_input.clone(),+ })+ }++ /// The tool's own result, out of Cursor's `{ result: { success | error |+ /// … } }` envelope - and, for an MCP call, out of MCP's content blocks+ /// in Cursor's spelling. A `rawOutput` that is not Cursor's envelope is+ /// read the neutral way.+ fn unwrap_tool_output(&self, raw: &Value) -> (Value, Option<String>) {+ match RawOutput::read(raw) {+ Some(output) => output.result.into_tool_output(),+ None => mcp::unwrap_call_result(raw),+ }+ }+fn subagent_input(&self, frame: &ToolFrame<'_>) -> SubagentInput {let mut input = generic::subagent_input(frame);if input.agent_type.is_none() {@@ -191,15 +244,29 @@ impl TaskOutput {}}-/// Cursor's result envelope, shared by the `task` call and every call the-/// child made: `success` with the payload, or `error` (`failure` for the-/// shell tool), and sometimes a flag beside them (`isBackground`) - hence a-/// struct of optionals rather than a one-key enum.+/// Cursor's result envelope, shared by the `task` call, every call the+/// child made, and every top-level call's `rawOutput`: `success` with the+/// payload, or `error` (`failure` for the shell tool), or for an MCP call+/// one of the ways the dispatcher can refuse (`rejected`,+/// `permissionDenied`, `toolNotFound`, `serverNotFound`), and sometimes a+/// flag beside them (`isBackground`) - hence a struct of optionals rather+/// than a one-key enum.#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]struct Envelope<Payload> {success: Option<Payload>,failure: Option<Payload>,error: Option<Value>,+ /// The MCP dispatcher's refusals, all read alike: the call never reached+ /// the tool, and the payload says why.+ #[serde(+ default,+ alias = "rejected",+ alias = "permissionDenied",+ alias = "toolNotFound",+ alias = "serverNotFound"+ )]+ refused: Option<Value>,}/// By hand rather than derived: the derive would demand `Payload: Default`,@@ -210,19 +277,25 @@ impl<Payload> Default for Envelope<Payload> {success: None,failure: None,error: None,+ refused: None,}}}impl<Payload> Envelope<Payload> {fn is_reported(&self) -> bool {- self.success.is_some() || self.failure.is_some() || self.error.is_some()+ self.success.is_some() || self.failure.is_some() || self.failed()+ }++ /// Whether the envelope reports the call as not having succeeded.+ fn failed(&self) -> bool {+ self.error.is_some() || self.refused.is_some()}fn status(&self) -> ToolStatus {if self.success.is_some() {ToolStatus::Completed- } else if self.failure.is_some() || self.error.is_some() {+ } else if self.failure.is_some() || self.failed() {ToolStatus::Failed} else {// Nothing recorded: not evidence either way.@@ -235,11 +308,219 @@ impl<Payload> Envelope<Payload> {self.success.as_ref().or(self.failure.as_ref())}+ /// Why the call failed, as text: the error or refusal Cursor reported.fn error_text(&self) -> Option<String> {- Some(match self.error.as_ref()? {- Value::String(text) => text.clone(),- other => other.to_string(),- })+ self.error+ .as_ref()+ .or(self.refused.as_ref())+ .map(failure_text)+ }+}++impl Envelope<Value> {+ /// The tool's own result and the error text, for a call whose payload+ /// this reader has no type for: an MCP result out of its content blocks,+ /// anything else as Cursor wrote it. A failure payload (the shell tool's+ /// `{ stderr, exitCode }`) is both the result and, as text, the error.+ fn into_tool_output(self) -> (Value, Option<String>) {+ let mut error = self.error_text();+ if self.success.is_none()+ && let Some(failure) = &self.failure+ {+ error = error.or_else(|| Some(failure_text(failure)));+ }+ let Some(payload) = self.success.or(self.failure) else {+ return (Value::Null, error);+ };+ match McpSuccess::read(&payload) {+ Some(result) => {+ let (value, mcp_error) = result.into_tool_output();+ (value, error.or(mcp_error))+ }+ None => (payload, error),+ }+ }+}++/// A failure payload as text: the string it is, the message a structured+/// one carries under its usual key, else the whole thing as JSON.+fn failure_text(value: &Value) -> String {+ const MESSAGE_KEYS: &[&str] = &["error", "message", "reason", "stderr"];+ match value {+ Value::String(text) => text.clone(),+ Value::Object(fields) => MESSAGE_KEYS+ .iter()+ .find_map(|key| fields.get(*key).and_then(Value::as_str))+ .map_or_else(|| value.to_string(), str::to_owned),+ other => other.to_string(),+ }+}++// --- The `mcp` dispatcher ---++/// The `mcp` tool's arguments: which server and tool, beside the tool's own+/// arguments. Recognized by shape - `toolName` with a server identifier -+/// rather than by title alone, because the title (`mcp`) is also what a+/// child's `mcpToolCall` step is keyed by, where there is no title to read.+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct McpArguments {+ tool_name: String,+ #[serde(default)]+ server_identifier: Option<String>,+ #[serde(default)]+ provider_identifier: Option<String>,+}++impl McpArguments {+ /// The dispatcher's own keys: everything of Cursor's around the tool's+ /// arguments, per its `McpArgs` message.+ const DISPATCHER_KEYS: &'static [&'static str] = &[+ "name",+ "toolName",+ "toolCallId",+ "providerIdentifier",+ "serverIdentifier",+ "smartModeApproval",+ "smartModeApprovalOnly",+ "skipApproval",+ ];++ /// The envelope `raw_input` is, if it is one: a named tool on a named+ /// server. `None` for any other tool's arguments.+ fn read(raw_input: Option<&Value>) -> Option<Self> {+ let arguments: Self = raw(raw_input)?;+ (!arguments.tool_name.is_empty() && arguments.server().is_some()).then_some(arguments)+ }++ /// The server, by whichever identifier Cursor filled in. The two are the+ /// same string in every recording; `serverIdentifier` is the newer field.+ fn server(&self) -> Option<&str> {+ [&self.server_identifier, &self.provider_identifier]+ .into_iter()+ .flatten()+ .map(String::as_str)+ .find(|server| !server.is_empty())+ }++ fn into_name(self) -> ToolName {+ ToolName::Mcp {+ server: self.server().unwrap_or_default().to_owned(),+ tool: self.tool_name,+ }+ }++ /// The tool's own arguments, out of the dispatcher's envelope: whatever+ /// is not the dispatcher's, and - when that is Cursor's `args` map alone+ /// - the map itself. A call to a tool that takes nothing has `{}`.+ fn tool_input(raw_input: &Value) -> Value {+ let Value::Object(fields) = raw_input else {+ return raw_input.clone();+ };+ let mut own: Map<String, Value> = fields+ .iter()+ .filter(|(key, _)| !Self::DISPATCHER_KEYS.contains(&key.as_str()))+ .map(|(key, value)| (key.clone(), value.clone()))+ .collect();+ if own.len() == 1+ && let Some(args @ Value::Object(_)) = own.remove("args")+ {+ return args;+ }+ Value::Object(own)+ }+}++/// A top-level call's `rawOutput`: Cursor's result under the translator's+/// `result` key.+#[derive(Deserialize)]+struct RawOutput {+ result: Envelope<Value>,+}++impl RawOutput {+ /// `None` for a `rawOutput` that is not Cursor's envelope - one with no+ /// outcome under `result` at all.+ fn read(raw_output: &Value) -> Option<Self> {+ let output: Self = raw(Some(raw_output))?;+ output.result.is_reported().then_some(output)+ }+}++/// MCP's `CallToolResult` in Cursor's spelling: content items keyed by+/// their kind (`{ "text": { "text": … } }`, `{ "image": … }`) rather than+/// tagged, and - for the dispatcher's own tools - sometimes one string+/// where the items would be.+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct McpSuccess {+ content: Option<McpContent>,+ structured_content: Option<Value>,+ #[serde(default)]+ is_error: bool,+}++#[derive(Deserialize)]+#[serde(untagged)]+enum McpContent {+ Items(Vec<McpContentItem>),+ Text(String),+}++#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+enum McpContentItem {+ Text(StepText),+ /// Anything that is not text - an image, a kind this reader does not+ /// know - carries nothing the fold shows.+ #[serde(untagged)]+ Other(IgnoredAny),+}++impl McpSuccess {+ /// The payload as an MCP result, if it is one. A success payload of+ /// Cursor's own tools (`{ path }`, `{ stdout }`) has neither `content`+ /// nor `structuredContent` and is not.+ fn read(payload: &Value) -> Option<Self> {+ let result: Self = raw(Some(payload))?;+ (result.content.is_some() || result.structured_content.is_some()).then_some(result)+ }++ /// The text items' text, in order.+ fn texts(&self) -> Vec<&str> {+ match &self.content {+ None => Vec::new(),+ Some(McpContent::Text(text)) => vec![text.as_str()],+ Some(McpContent::Items(items)) => items+ .iter()+ .filter_map(|item| match item {+ McpContentItem::Text(StepText { text }) => Some(text.as_str()),+ McpContentItem::Other(_) => None,+ })+ .collect(),+ }+ }++ /// The tool's own result, read the way [`mcp::unwrap_call_result`] reads+ /// the standard envelope: `structuredContent`; else the first text that+ /// parses as JSON; else the texts joined; else `null`. The error is the+ /// texts, when the result marks itself one.+ fn into_tool_output(self) -> (Value, Option<String>) {+ let texts = self.texts();+ let error = self.is_error.then(|| texts.join("\n"));+ if let Some(structured) = self.structured_content {+ return (structured, error);+ }+ if let Some(parsed) = texts+ .iter()+ .find_map(|text| serde_json::from_str::<Value>(text).ok())+ {+ return (parsed, error);+ }+ if texts.is_empty() {+ return (Value::Null, error);+ }+ (Value::String(texts.join("\n")), error)}}@@ -379,7 +660,7 @@ impl KnownToolCall {let (name, status, detail) = self.descriptor.into_detail();MessagePart::ToolUse {id: ToolUseId(collapse_whitespace(&self.tool_call_id)),- name: ToolName::native(name),+ name,status,detail,}@@ -409,13 +690,23 @@ enum Descriptor {#[serde(rename = "taskToolCall")]Task(ToolBody<Value, IgnoredAny>),#[serde(rename = "mcpToolCall")]- Mcp(ToolBody<Value, IgnoredAny>),+ Mcp(ToolBody<Value, Value>),}impl Descriptor {- /// The tool's name in Cursor's own vocabulary (the descriptor key's- /// stem), how far it got, and what it did.- fn into_detail(self) -> (&'static str, ToolStatus, ToolDetail) {+ /// The tool's name - in Cursor's own vocabulary (the descriptor key's+ /// stem), or for an MCP call the server and tool it dispatched to - how+ /// far it got, and what it did.+ fn into_detail(self) -> (ToolName, ToolStatus, ToolDetail) {+ if let Self::Mcp(body) = self {+ return body.into_mcp_call();+ }+ let (name, status, detail) = self.into_native_detail();+ (ToolName::native(name), status, detail)+ }++ /// Every descriptor but [`Self::Mcp`], which `into_detail` has taken.+ fn into_native_detail(self) -> (&'static str, ToolStatus, ToolDetail) {match self {Self::Shell(body) => {let status = body.result.status();@@ -477,7 +768,9 @@ impl Descriptor {ToolDetail::Think { output: None },),Self::Task(body) => ("task", body.result.status(), body.into_other()),- Self::Mcp(body) => ("mcp", body.result.status(), body.into_other()),+ // Taken by `into_detail`; named here so the match stays+ // exhaustive when a descriptor is added.+ Self::Mcp(body) => (MCP_TOOL, body.result.status(), body.into_other()),}}}@@ -506,10 +799,40 @@ impl<Outcome> ToolBody<Value, Outcome> {kind: "other".to_owned(),output: None,input: self.args,+ result: None,+ error: None,}}}+impl ToolBody<Value, Value> {+ /// A child's MCP call, read as a top-level one is: named for the server+ /// and tool, its own arguments out of the dispatcher's envelope, its+ /// result out of MCP's.+ fn into_mcp_call(self) -> (ToolName, ToolStatus, ToolDetail) {+ let status = self.result.status();+ let name = McpArguments::read(self.args.as_ref())+ .map_or_else(|| ToolName::native(MCP_TOOL), McpArguments::into_name);+ let input = self.args.as_ref().map(McpArguments::tool_input);+ let (result, error) = if self.result.is_reported() {+ match self.result.into_tool_output() {+ (Value::Null, error) => (None, error),+ (value, error) => (Some(value), error),+ }+ } else {+ (None, None)+ };+ let detail = ToolDetail::Other {+ kind: "other".to_owned(),+ output: None,+ input,+ result,+ error,+ };+ (name, status, detail)+ }+}+impl ToolBody<PathArguments, PathOutcome> {/// The path the call touched - from its result once finished, from its/// arguments before.@@ -616,6 +939,8 @@ impl UnknownToolCall {kind: "other".to_owned(),output: None,input: None,+ result: None,+ error: None,},}}diff --git a/crates/agent_fold/src/domain/model/search.rs b/crates/agent_fold/src/domain/model/search.rsindex fd3d23c3a1..0a0e6e3054 100644--- a/crates/agent_fold/src/domain/model/search.rs+++ b/crates/agent_fold/src/domain/model/search.rs@@ -153,12 +153,25 @@ impl SearchText {self.push(output);}}- ToolDetail::Other { input, output, .. } => {+ ToolDetail::Other {+ input,+ output,+ result,+ error,+ ..+ } => {if let Some(input) = input {self.json(input);}- if let Some(output) = output {- self.push(output);+ if let Some(error) = error {+ self.push(error);+ }+ // The text blocks and the unwrapped result usually carry the+ // same words; either alone is enough to find the call by.+ match (result, output) {+ (Some(result), _) => self.json(result),+ (None, Some(output)) => self.push(output),+ (None, None) => {}}}ToolDetail::Macro {diff --git a/crates/agent_fold/src/domain/model/tool.rs b/crates/agent_fold/src/domain/model/tool.rsindex 3f6b3e15d0..bc6fdf2255 100644--- a/crates/agent_fold/src/domain/model/tool.rs+++ b/crates/agent_fold/src/domain/model/tool.rs@@ -215,19 +215,30 @@ pub enum ToolDetail {/// Text the call reported, when any.output: Option<String>,},- /// Anything else: ACP's `switch_mode`, and any kind - including `other`- /// itself, [`ToolKind`](agent_client_protocol::ToolKind)'s default for a- /// call that names no kind at all - this fold has no special rendering- /// for.+ /// Anything else: ACP's `switch_mode`, a tool from an MCP server the fold+ /// knows nothing about, and any kind - including `other` itself,+ /// [`ToolKind`](agent_client_protocol::ToolKind)'s default for a call+ /// that names no kind at all - this fold has no special rendering for.+ /// What a reader wants is the exchange itself: the request the agent+ /// made and the response it got, as JSON.Other {/// ACP's tool kind, as its wire string.#[serde(rename = "acpKind")]kind: String,- /// Text the call reported, when any.+ /// Text the call reported in its content blocks, when any.output: Option<String>,- /// The tool's input, when reported.+ /// The tool's own arguments, when reported - out of any wrapper the+ /// harness put around them.#[specta(type = specta_typescript::Unknown)]input: Option<serde_json::Value>,+ /// The tool's own result, when the harness reported one in+ /// `rawOutput` - out of the harness's wrapper and MCP's envelope, so+ /// an MCP tool's `structuredContent` (or its text, parsed when it is+ /// JSON) arrives as the JSON the tool returned.+ #[specta(type = specta_typescript::Unknown)]+ result: Option<serde_json::Value>,+ /// The error text, when the harness's wrapper reported failure.+ error: Option<String>,},/// A Macro tool the fold knows by name - reached over Macro's MCP/// server, or called in-process by Macro's own agent. Input and outputdiff --git a/crates/agent_fold/src/domain/test/fold.rs b/crates/agent_fold/src/domain/test/fold.rsindex 233ff960db..55d358a8f4 100644--- a/crates/agent_fold/src/domain/test/fold.rs+++ b/crates/agent_fold/src/domain/test/fold.rs@@ -3,10 +3,11 @@ use crate::domain::fold::fold;use crate::domain::log::{AgentSessionLog, Message};use crate::domain::model::{Author, Control, ControlOutcome, FoldedMessage, MessagePart, PermissionOutcome, StopReason,- ToolDetail, ToolStatus, TurnId,+ ToolDetail, ToolName, ToolStatus, ToolUseId, TurnId,};use agent_client_protocol::RawJsonRpcMessage;use agent_runtime_protocol::domain::schema::v0::ToServerMessage;+use serde_json::json;/// Fold a log while capturing anything it logs at `WARN`.fn fold_capturing_warnings(@@ -381,6 +382,94 @@ fn folds_every_official_tool_kind() {insta::assert_debug_snapshot!(agent.parts);}+/// An unmodeled call keeps the exchange itself: its arguments, and the+/// result the harness put in `rawOutput` with MCP's envelope removed, beside+/// whatever text its content blocks carried.+#[test]+fn an_unmodeled_call_keeps_its_request_and_response() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"hi"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"_meta":{"claudeCode":{"toolName":"mcp__deepwiki__ask_question"}},"sessionUpdate":"tool_call","toolCallId":"q","title":"mcp__deepwiki__ask_question","kind":"other","status":"in_progress","rawInput":{"repoName":"sst/opencode","question":"how are tools rendered?"}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"q","status":"completed","rawOutput":{"content":[{"type":"text","text":"{\"answer\":\"in basic-tool-v2.tsx\"}"}],"isError":false},"content":[{"type":"content","content":{"type":"text","text":"{\"answer\":\"in basic-tool-v2.tsx\"}"}}]}}}}"#,+ ));+ let (messages, warnings) = fold_capturing_warnings(log);+ assert_eq!(warnings, vec![]);+ let [part] = &messages[1].parts[..] else {+ panic!("one part: {:#?}", messages[1].parts);+ };+ assert_eq!(+ *part,+ MessagePart::ToolUse {+ id: ToolUseId("q".to_owned()),+ name: ToolName::Mcp {+ server: "deepwiki".to_owned(),+ tool: "ask_question".to_owned(),+ },+ status: ToolStatus::Completed,+ detail: ToolDetail::Other {+ kind: "other".to_owned(),+ output: Some(r#"{"answer":"in basic-tool-v2.tsx"}"#.to_owned()),+ input: Some(+ json!({"repoName": "sst/opencode", "question": "how are tools rendered?"})+ ),+ result: Some(json!({"answer": "in basic-tool-v2.tsx"})),+ error: None,+ },+ }+ );+}++/// Cursor announces an MCP call as its `mcp` dispatcher with nothing else,+/// sends the arguments - which say which tool - on an update, and the result+/// on the last. The part is named once the arguments arrive, shows the+/// tool's own arguments rather than the dispatcher's, and ends with what the+/// tool returned.+#[test]+fn a_cursor_mcp_call_is_named_and_unwrapped_as_its_frames_arrive() {+ let log = parse_log(concat!(+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"i","method":"initialize","params":{"protocolVersion":1,"clientCapabilities":{}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","id":"i","result":{"protocolVersion":1,"agentCapabilities":{},"agentInfo":{"name":"cursor-acp","version":"0"}}}}"#,+ "\n",+ r#"{"direction":"to_runtime","content":{"type":"acp","jsonrpc":"2.0","id":"p","method":"session/prompt","params":{"sessionId":"s","prompt":[{"type":"text","text":"hi"}]}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call","toolCallId":"m","title":"mcp","kind":"other","status":"in_progress"}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"m","title":"mcp","kind":"other","status":"in_progress","rawInput":{"name":"macro-ReadContent","toolCallId":"m","providerIdentifier":"macro","toolName":"ReadContent","serverIdentifier":"macro","args":{"documentId":"4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}}}}}}"#,+ "\n",+ r#"{"direction":"to_server","content":{"type":"acp","jsonrpc":"2.0","method":"session/update","params":{"sessionId":"s","update":{"sessionUpdate":"tool_call_update","toolCallId":"m","title":"mcp","kind":"other","status":"completed","rawInput":{"name":"macro-ReadContent","toolCallId":"m","providerIdentifier":"macro","toolName":"ReadContent","serverIdentifier":"macro","args":{"documentId":"4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}},"rawOutput":{"result":{"success":{"content":[{"text":{"text":"{\"content\":{\"text\":\"Q3 plan\"},\"comments\":[]}"}}],"structuredContent":{"content":{"text":"Q3 plan"},"comments":[]}}}}}}}}"#,+ ));+ let (messages, warnings) = fold_capturing_warnings(log);+ assert_eq!(warnings, vec![]);+ let agent = messages+ .iter()+ .find(|message| message.author == Author::Agent)+ .expect("the agent answered");+ let [part] = &agent.parts[..] else {+ panic!("one part: {:#?}", agent.parts);+ };+ assert_eq!(+ *part,+ MessagePart::ToolUse {+ id: ToolUseId("m".to_owned()),+ name: ToolName::Mcp {+ server: "macro".to_owned(),+ tool: "ReadContent".to_owned(),+ },+ status: ToolStatus::Completed,+ detail: ToolDetail::Other {+ kind: "other".to_owned(),+ output: None,+ input: Some(json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"})),+ result: Some(json!({"content": {"text": "Q3 plan"}, "comments": []})),+ error: None,+ },+ }+ );+}+/// An edit call that never reports a diff content block — Claude Code's/// `Write` — synthesizes a whole-file diff from `rawInput`'s/// `{filePath, content}`, on the opening frame or a later patch.diff --git a/crates/agent_fold/src/domain/test/harness_readers.rs b/crates/agent_fold/src/domain/test/harness_readers.rsindex a66f188611..00b2916865 100644--- a/crates/agent_fold/src/domain/test/harness_readers.rs+++ b/crates/agent_fold/src/domain/test/harness_readers.rs@@ -8,7 +8,7 @@ use crate::domain::model::{};use crate::domain::test::util::Frame;use agent_client_protocol::schema::v1::ToolKind;-use serde_json::json;+use serde_json::{Value, json};fn native(name: &str) -> ToolName {ToolName::native(name)@@ -370,6 +370,8 @@ fn cursor_task_result_unfolds_the_childs_transcript() {kind: "other".to_owned(),output: None,input: None,+ result: None,+ error: None,},},]@@ -386,6 +388,263 @@ fn cursor_task_result_unfolds_the_childs_transcript() {assert_eq!(reader.subagent_transcript(&Frame::new().view()), vec![]);}+/// Every MCP call goes through Cursor's `mcp` dispatcher, whose arguments+/// say which server and tool; the reader names the call for those and hands+/// on the tool's own arguments without the dispatcher's.+#[test]+fn cursor_names_mcp_calls_from_the_dispatchers_arguments() {+ let reader = Harness::Cursor.reader();+ let dispatched = Frame::new().title("mcp").raw_input(json!({+ "name": "macro-ReadContent",+ "toolCallId": "call-1 fc_1",+ "providerIdentifier": "macro",+ "toolName": "ReadContent",+ "serverIdentifier": "macro",+ "args": {"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}+ }));+ assert_eq!(+ reader.reported_tool_name(&dispatched.view()),+ Some(ToolName::Mcp {+ server: "macro".to_owned(),+ tool: "ReadContent".to_owned()+ })+ );+ assert_eq!(+ reader.tool_input(&dispatched.view()),+ Some(json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}))+ );++ // The announcement carries no arguments: nothing to name it by yet.+ let announced = Frame::new().title("mcp");+ assert_eq!(reader.reported_tool_name(&announced.view()), None);+ assert_eq!(reader.tool_input(&announced.view()), None);++ // A tool that takes nothing, as recorded: the dispatcher's keys alone,+ // and only `providerIdentifier` in an older recording.+ let bare = Frame::new().title("mcp").raw_input(json!({+ "name": "cursor-cloud-get-message-queue",+ "toolCallId": "call-2 fc_2",+ "providerIdentifier": "cursor-cloud",+ "toolName": "get-message-queue"+ }));+ assert_eq!(+ reader.reported_tool_name(&bare.view()),+ Some(ToolName::Mcp {+ server: "cursor-cloud".to_owned(),+ tool: "get-message-queue".to_owned()+ })+ );+ assert_eq!(reader.tool_input(&bare.view()), Some(json!({})));++ // Any other tool's arguments are its own already, and its title is its+ // name - `get_mcp_tools` names a tool too, but is not the dispatcher.+ let listing = Frame::new().title("get_mcp_tools").raw_input(+ json!({"server": "cursor-cloud", "toolName": "get-message-queue", "toolCallId": "c"}),+ );+ assert_eq!(reader.reported_tool_name(&listing.view()), None);+ assert_eq!(+ reader.tool_input(&listing.view()),+ Some(json!({"server": "cursor-cloud", "toolName": "get-message-queue", "toolCallId": "c"}))+ );+ let shell = Frame::new()+ .title("run_terminal_cmd")+ .raw_input(json!({"command": "ls"}));+ assert_eq!(reader.reported_tool_name(&shell.view()), None);+ assert_eq!(+ reader.tool_input(&shell.view()),+ Some(json!({"command": "ls"}))+ );+}++/// A call's `rawOutput` is Cursor's result under `result`; for an MCP call+/// that is MCP's `CallToolResult` in Cursor's spelling, and the reader+/// unwraps it to what the tool returned.+#[test]+fn cursor_unwraps_mcp_results_from_its_envelope() {+ let reader = Harness::Cursor.reader();++ // Structured content wins, as in the standard envelope.+ let structured = json!({"result": {"success": {+ "content": [{"text": {"text": "Cursor Cloud message queue (0 queued).\n{\"hasQueuedMessages\": false}"}}],+ "structuredContent": {"hasQueuedMessages": false, "queuedMessageCount": 0}+ }}});+ assert_eq!(+ reader.unwrap_tool_output(&structured),+ (+ json!({"hasQueuedMessages": false, "queuedMessageCount": 0}),+ None+ )+ );++ // Else the text, parsed when it is JSON, as text when it is not.+ let json_text = json!({"result": {"success": {+ "content": [{"text": {"text": "{\"content\":{\"text\":\"Q3 plan\"},\"comments\":[]}"}}]+ }}});+ assert_eq!(+ reader.unwrap_tool_output(&json_text),+ (+ json!({"content": {"text": "Q3 plan"}, "comments": []}),+ None+ )+ );+ let prose = json!({"result": {"success": {+ "content": [{"text": {"text": "first"}}, {"image": {"data": "…"}}, {"text": {"text": "second"}}]+ }}});+ assert_eq!(+ reader.unwrap_tool_output(&prose),+ (json!("first\nsecond"), None)+ );++ // Content as one string - how `get_mcp_tools` reports its catalog.+ let catalog =+ json!({"result": {"success": {"content": "{\"mode\": \"catalog\", \"servers\": []}"}}});+ assert_eq!(+ reader.unwrap_tool_output(&catalog),+ (json!({"mode": "catalog", "servers": []}), None)+ );++ // A result that marks itself an error is one, and still a result.+ let marked = json!({"result": {"success": {+ "content": [{"text": {"text": "no such document"}}], "isError": true+ }}});+ assert_eq!(+ reader.unwrap_tool_output(&marked),+ (+ json!("no such document"),+ Some("no such document".to_owned())+ )+ );++ // The dispatcher's own failures, each as its text.+ let error =+ json!({"result": {"error": {"error": "MCP tool \"x\" not found on server \"y\"."}}});+ assert_eq!(+ reader.unwrap_tool_output(&error),+ (+ Value::Null,+ Some("MCP tool \"x\" not found on server \"y\".".to_owned())+ )+ );+ let rejected =+ json!({"result": {"rejected": {"reason": "user declined", "isReadonly": false}}});+ assert_eq!(+ reader.unwrap_tool_output(&rejected),+ (Value::Null, Some("user declined".to_owned()))+ );+ let denied = json!({"result": {"permissionDenied": {"error": "not allowed"}}});+ assert_eq!(+ reader.unwrap_tool_output(&denied),+ (Value::Null, Some("not allowed".to_owned()))+ );+ let missing = json!({"result": {"toolNotFound": {"name": "x", "availableTools": ["y"]}}});+ assert_eq!(+ reader.unwrap_tool_output(&missing),+ (+ Value::Null,+ Some("{\"name\":\"x\",\"availableTools\":[\"y\"]}".to_owned())+ )+ );++ // A native tool's payload is not MCP's and comes through as Cursor wrote+ // it; a shell failure is both the result and, as text, the error.+ let path = json!({"result": {"success": {"path": "/workspace/README.md"}}});+ assert_eq!(+ reader.unwrap_tool_output(&path),+ (json!({"path": "/workspace/README.md"}), None)+ );+ let failure =+ json!({"result": {"failure": {"stderr": "No module named 'sympy'\n", "exitCode": 1}}});+ assert_eq!(+ reader.unwrap_tool_output(&failure),+ (+ json!({"stderr": "No module named 'sympy'\n", "exitCode": 1}),+ Some("No module named 'sympy'\n".to_owned())+ )+ );++ // Not Cursor's envelope at all: the neutral reading.+ let standard =+ json!({"content": [{"type": "text", "text": "{\"ok\":true}"}], "isError": false});+ assert_eq!(+ reader.unwrap_tool_output(&standard),+ (json!({"ok": true}), None)+ );+ assert_eq!(+ reader.unwrap_tool_output(&json!({"result": {}})),+ (json!({"result": {}}), None)+ );+}++/// A child's `mcpToolCall` step is read the same way as a top-level call.+#[test]+fn cursor_child_mcp_calls_are_named_and_unwrapped() {+ let reader = Harness::Cursor.reader();+ let frame = Frame::new().raw_output(json!({"result": {"success": {+ "agentId": "bc-child",+ "conversationSteps": [+ {"toolCall": {+ "toolCallId": "call_m",+ "mcpToolCall": {+ "args": {+ "name": "macro-ReadContent",+ "toolCallId": "call_m",+ "providerIdentifier": "macro",+ "toolName": "ReadContent",+ "serverIdentifier": "macro",+ "args": {"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}+ },+ "result": {"success": {+ "content": [{"text": {"text": "{\"content\":{\"text\":\"Q3 plan\"}}"}}]+ }}+ }+ }},+ {"toolCall": {+ "toolCallId": "call_n",+ "mcpToolCall": {+ "args": {"toolName": "deploy", "serverIdentifier": "ops", "toolCallId": "call_n"},+ "result": {"rejected": {"reason": "user declined"}}+ }+ }},+ {"assistantMessage": {"text": "Done."}}+ ]+ }}}));+ assert_eq!(+ reader.subagent_transcript(&frame.view()),+ vec![+ MessagePart::ToolUse {+ id: ToolUseId("call_m".to_owned()),+ name: ToolName::Mcp {+ server: "macro".to_owned(),+ tool: "ReadContent".to_owned()+ },+ status: ToolStatus::Completed,+ detail: ToolDetail::Other {+ kind: "other".to_owned(),+ output: None,+ input: Some(json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"})),+ result: Some(json!({"content": {"text": "Q3 plan"}})),+ error: None,+ },+ },+ MessagePart::ToolUse {+ id: ToolUseId("call_n".to_owned()),+ name: ToolName::Mcp {+ server: "ops".to_owned(),+ tool: "deploy".to_owned()+ },+ status: ToolStatus::Failed,+ detail: ToolDetail::Other {+ kind: "other".to_owned(),+ output: None,+ input: Some(json!({})),+ result: None,+ error: Some("user declined".to_owned()),+ },+ },+ ]+ );+}+// --- Hermes (hermes-agent) ---#[test]diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snapindex 6b3507dac5..b12450ca64 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__fold__folds_every_official_tool_kind.snap@@ -1,6 +1,5 @@---source: crates/agent_fold/src/domain/test/fold.rs-assertion_line: 381expression: agent.parts---NonEmpty {@@ -97,6 +96,8 @@ NonEmpty {"foo": String("bar"),},),+ result: None,+ error: None,},},],diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snapindex 3ace8fd73c..a026ca0dde 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@plan_todo.jsonl.snap@@ -78,6 +78,31 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl"max_results": Number(5),},),+ result: Some(+ Array [+ Object {+ "type": String("tool_reference"),+ "tool_name": String("TaskList"),+ },+ Object {+ "type": String("tool_reference"),+ "tool_name": String("CronList"),+ },+ Object {+ "type": String("tool_reference"),+ "tool_name": String("ListMcpResourcesTool"),+ },+ Object {+ "type": String("tool_reference"),+ "tool_name": String("mcp__macro__ListEntities"),+ },+ Object {+ "type": String("tool_reference"),+ "tool_name": String("mcp__macro__ListCompanies"),+ },+ ],+ ),+ error: None,},},ToolUse {@@ -99,6 +124,19 @@ input_file: crates/agent_fold/fixtures/real/plan_todo.jsonl"max_results": Number(3),},),+ result: Some(+ Array [+ Object {+ "type": String("tool_reference"),+ "tool_name": String("TaskCreate"),+ },+ Object {+ "type": String("tool_reference"),+ "tool_name": String("TaskUpdate"),+ },+ ],+ ),+ error: None,},},Plan {diff --git a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snapindex 2189be3504..d0f51db892 100644--- a/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap+++ b/crates/agent_fold/src/domain/test/snapshots/agent_fold__domain__test__real_recordings__real_fixtures_fold_to_their_pinned_snapshot@resumed_no_prompt.jsonl.snap@@ -469,6 +469,10 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl],},),+ result: Some(+ String("The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed.\n\nNote: The user's next message may contain a correction or preference. Pay close attention — if they explain what went wrong or how they'd prefer you to work, consider saving that to memory for future sessions."),+ ),+ error: None,},},],@@ -1950,6 +1954,10 @@ input_file: crates/agent_fold/fixtures/real/resumed_no_prompt.jsonl"skill": String("cloud-storage-hexagonal-architecture"),},),+ result: Some(+ String("Launching skill: cloud-storage-hexagonal-architecture"),+ ),+ error: None,},},ToolUse {diff --git a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snapindex 4c613d33aa..68d016f7be 100644--- a/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap+++ b/crates/codex_cloud_agents/tests/snapshots/fold__verified_pr_tool.snap@@ -43,7 +43,13 @@ expression: messages"output": "[View pull request](https://github.com/org/repo/pull/42)","input": {"url": "https://github.com/org/repo/pull/42"- }+ },+ "result": {+ "url": "https://github.com/org/repo/pull/42",+ "assistantTurnId": "turn-1",+ "source": "codex_cloud_metadata"+ },+ "error": null}}],diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.mdindex 95f9662f13..cfa8d78363 100644--- a/docs/AGENT_GUIDE/channels.md+++ b/docs/AGENT_GUIDE/channels.md@@ -24,6 +24,18 @@ session-specific modal. Folder moves, duplication, and property/tag editing arenot offered because those APIs do not support sessions. Runtime controls remainsession-specific.+A session transcript shows each tool call as a collapsible row (consecutive calls+fold into a `Called N tools` group; click it to see the rows). A tool reached over+an MCP server - Macro's own (`ReadContent · macro`) from a Cursor, Claude, or+Codex session, or a third-party server (`ask_question · deepwiki`) - is titled by+the tool's name with the server as its subtitle, never by the harness's dispatcher+(`mcp`). Clicking the row expands the exchange: a `Request` section with the+tool's own arguments and a `Response` section with what it returned, both as+syntax-lit, pretty-printed JSON (prose results show as text), each with a copy+button that copies the whole section; a call that failed is faded, shows the+error as its subtitle, and adds an `Error` section. Rows for a call still running+show whatever has arrived so far.+## Message composerComposer and conversation body text use `text-base` (15px at the default root