Preserve full MCP results in rollout traces (#57280)

## Why

MCP completion events can truncate large results and omit content removed for model consumption. Rollout traces need the original response, including content and metadata, as well as results for calls denied before reaching the backend.

## What changed

- Record MCP runtime results before callbacks, content filtering, and UI truncation, and record skipped calls as failures.
- Stop deriving MCP runtime completion records from protocol events to avoid duplicate records.
- Treat MCP runtime payloads as opaque results when reducing agent interactions.
- Buffer JSON trace writes and explicitly flush them.

## Testing

Extend app-server tests to verify that traces retain oversized MCP text, audio, structured content, and metadata while UI results remain truncated, and that denied calls produce exactly one failed runtime result with the denial reason.

GitOrigin-RevId: 57880770545eb5869420d7dc6fa4a15e481cae9d
This commit is contained in:
cassirer-openai
2026-10-26 21:56:23 +00:00
committed by copyberry
parent 6d8f311b00
commit f2df3e3b56
7 changed files with 154 additions and 23 deletions
+5 -15
View File
@@ -2,9 +2,9 @@
//!
//! The session layer already emits protocol events for turn lifecycle, terminal
//! sessions, patch application, MCP calls, and collaboration tools. Rollout
//! tracing reuses those observations instead of adding another set of hooks in
//! `codex-core`: this module translates the protocol surface into the smaller
//! trace vocabulary and keeps the mapping isolated inside `codex-rollout-trace`.
//! tracing reuses those observations where they preserve the original payload.
//! MCP results are recorded before protocol-event truncation instead. This module
//! translates protocol events into the smaller trace vocabulary.
//!
//! The long explicit `EventMsg` matches are intentional. Most protocol events
//! are not trace runtime boundaries, but spelling them out makes new protocol
@@ -17,7 +17,6 @@ use codex_protocol::protocol::ExecCommandEndEvent;
use codex_protocol::protocol::ExecCommandSource;
use codex_protocol::protocol::ExecCommandStatus;
use codex_protocol::protocol::McpToolCallBeginEvent;
use codex_protocol::protocol::McpToolCallEndEvent;
use codex_protocol::protocol::PatchApplyBeginEvent;
use codex_protocol::protocol::PatchApplyEndEvent;
use codex_protocol::protocol::PatchApplyStatus;
@@ -116,7 +115,6 @@ pub(crate) enum ToolRuntimePayload<'a> {
PatchApplyBegin(&'a PatchApplyBeginEvent),
PatchApplyEnd(&'a PatchApplyEndEvent),
McpToolCallBegin(&'a McpToolCallBeginEvent),
McpToolCallEnd(&'a McpToolCallEndEvent),
CollabAgentSpawnBegin(&'a codex_protocol::protocol::CollabAgentSpawnBeginEvent),
CollabAgentSpawnEnd(&'a codex_protocol::protocol::CollabAgentSpawnEndEvent),
CollabAgentInteractionBegin(&'a codex_protocol::protocol::CollabAgentInteractionBeginEvent),
@@ -143,7 +141,6 @@ impl Serialize for ToolRuntimePayload<'_> {
ToolRuntimePayload::PatchApplyBegin(event) => event.serialize(serializer),
ToolRuntimePayload::PatchApplyEnd(event) => event.serialize(serializer),
ToolRuntimePayload::McpToolCallBegin(event) => event.serialize(serializer),
ToolRuntimePayload::McpToolCallEnd(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentSpawnBegin(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentSpawnEnd(event) => event.serialize(serializer),
ToolRuntimePayload::CollabAgentInteractionBegin(event) => event.serialize(serializer),
@@ -316,15 +313,8 @@ pub(crate) fn tool_runtime_trace_event(event: &EventMsg) -> Option<ToolRuntimeTr
},
payload: ToolRuntimePayload::McpToolCallBegin(event),
}),
EventMsg::McpToolCallEnd(event) => Some(ToolRuntimeTraceEvent::Ended {
tool_call_id: &event.call_id,
status: if event.result.is_ok() {
ExecutionStatus::Completed
} else {
ExecutionStatus::Failed
},
payload: ToolRuntimePayload::McpToolCallEnd(event),
}),
// The full backend result is recorded before this UI event can truncate it.
EventMsg::McpToolCallEnd(_) => None,
EventMsg::CollabAgentSpawnBegin(event) => Some(ToolRuntimeTraceEvent::Started {
tool_call_id: &event.call_id,
kind: ToolCallKind::SpawnAgent,
@@ -133,6 +133,10 @@ impl TraceReducer {
runtime_payload: &RawPayloadRef,
) -> Result<()> {
let kind = self.rollout.tool_calls[tool_call_id].kind.clone();
// MCP results are opaque evidence; they cannot describe agent interactions.
if matches!(kind, ToolCallKind::Mcp { .. }) {
return Ok(());
}
let runtime_payload_json = self.read_payload_json(runtime_payload)?;
if runtime_payload_json.get("agent_thread_id").is_some() {
let payload: SubAgentActivityEvent = serde_json::from_value(runtime_payload_json)?;
+36
View File
@@ -5,6 +5,7 @@
//! thread-local event methods here avoids repeatedly plumbing `thread_id`
//! through session code.
use codex_protocol::mcp::CallToolResult;
use codex_protocol::protocol::AgentStatus;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::SessionSource;
@@ -21,6 +22,7 @@ use crate::CodeCellTraceContext;
use crate::CodexTurnId;
use crate::CompactionId;
use crate::CompactionTraceContext;
use crate::ExecutionStatus;
use crate::InferenceTraceContext;
use crate::McpCallTraceContext;
use crate::RawPayloadKind;
@@ -247,6 +249,40 @@ impl ThreadTraceContext {
context.append_with_context_best_effort(codex_turn_id.into(), payload);
}
/// Records the full MCP backend result before callbacks, sanitization, or UI truncation.
/// The dispatch trace separately records the result returned to the caller.
pub fn record_mcp_tool_result(
&self,
codex_turn_id: &str,
tool_call_id: &str,
result: &Result<CallToolResult, String>,
) {
let ThreadTraceContextState::Enabled(context) = &self.state else {
return;
};
#[derive(Serialize)]
struct Payload<'a> {
result: &'a Result<CallToolResult, String>,
}
let Some(runtime_payload) = context
.write_json_payload_best_effort(RawPayloadKind::ToolRuntimeEvent, &Payload { result })
else {
return;
};
context.append_with_context_best_effort(
codex_turn_id.to_owned(),
RawTraceEventPayload::ToolCallRuntimeEnded {
tool_call_id: tool_call_id.to_owned(),
status: if result.is_ok() {
ExecutionStatus::Completed
} else {
ExecutionStatus::Failed
},
runtime_payload,
},
);
}
/// Records the exec actually selected by stdin, since its process handle can be reused.
pub fn record_stdin_target(
&self,
+6 -2
View File
@@ -143,8 +143,12 @@ impl TraceWriter {
fn write_json_file(path: &Path, value: &impl Serialize) -> Result<()> {
let file = File::create(path).with_context(|| format!("create {}", path.display()))?;
serde_json::to_writer_pretty(file, value)
.with_context(|| format!("write JSON {}", path.display()))
let mut writer = BufWriter::new(file);
serde_json::to_writer_pretty(&mut writer, value)
.with_context(|| format!("write JSON {}", path.display()))?;
writer
.flush()
.with_context(|| format!("flush JSON {}", path.display()))
}
pub(crate) fn unix_time_ms() -> i64 {