feat(app-server, core): allow text + image content items for dynamic tool outputs (#10567)

Took over the work that @aaronl-openai started here:
https://github.com/openai/codex/pull/10397

Now that app-server clients are able to set up custom tools (called
`dynamic_tools` in app-server), we should expose a way for clients to
pass in not just text, but also image outputs. This is something the
Responses API already supports for function call outputs, where you can
pass in either a string or an array of content outputs (text, image,
file):
https://platform.openai.com/docs/api-reference/responses/create#responses_create-input-input_item_list-item-function_tool_call_output-output-array-input_image

So let's just plumb it through in Codex (with the caveat that we only
support text and image for now). This is implemented end-to-end across
app-server v2 protocol types and core tool handling.

## Breaking API change
NOTE: This introduces a breaking change with dynamic tools, but I think
it's ok since this concept was only recently introduced
(https://github.com/openai/codex/pull/9539) and it's better to get the
API contract correct. I don't think there are any real consumers of this
yet (not even the Codex App).

Old shape:
`{ "output": "dynamic-ok", "success": true }`

New shape:
```
{
    "contentItems": [
      { "type": "inputText", "text": "dynamic-ok" },
      { "type": "inputImage", "imageUrl": "data:image/png;base64,AAA" }
    ]
  "success": true
}
```
This commit is contained in:
Owen Lin
2026-02-04 16:12:47 -08:00
committed by GitHub
parent f9c38f531c
commit 5ea107a088
49 changed files with 1103 additions and 468 deletions
+74 -29
View File
@@ -5,7 +5,7 @@ use crate::tools::TELEMETRY_PREVIEW_MAX_LINES;
use crate::tools::TELEMETRY_PREVIEW_TRUNCATION_NOTICE;
use crate::turn_diff_tracker::TurnDiffTracker;
use codex_protocol::mcp::CallToolResult;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ShellToolCallParams;
@@ -58,10 +58,9 @@ impl ToolPayload {
#[derive(Clone)]
pub enum ToolOutput {
Function {
// Plain text representation of the tool output.
content: String,
// Some tool calls such as MCP calls may return structured content that can get parsed into an array of polymorphic content items.
content_items: Option<Vec<FunctionCallOutputContentItem>>,
// Canonical output body for function-style tools. This may be plain text
// or structured content items.
body: FunctionCallOutputBody,
success: Option<bool>,
},
Mcp {
@@ -72,7 +71,9 @@ pub enum ToolOutput {
impl ToolOutput {
pub fn log_preview(&self) -> String {
match self {
ToolOutput::Function { content, .. } => telemetry_preview(content),
ToolOutput::Function { body, .. } => {
telemetry_preview(&body.to_text().unwrap_or_default())
}
ToolOutput::Mcp { result } => format!("{result:?}"),
}
}
@@ -86,27 +87,28 @@ impl ToolOutput {
pub fn into_response(self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
match self {
ToolOutput::Function {
content,
content_items,
success,
} => {
ToolOutput::Function { body, success } => {
// `custom_tool_call` is the Responses API item type for freeform
// tools (`ToolSpec::Freeform`, e.g. freeform `apply_patch`).
// Those payloads must round-trip as `custom_tool_call_output`
// with plain string output.
if matches!(payload, ToolPayload::Custom { .. }) {
ResponseInputItem::CustomToolCallOutput {
// Freeform/custom tools (`custom_tool_call`) use the custom
// output wire shape and remain string-only.
return ResponseInputItem::CustomToolCallOutput {
call_id: call_id.to_string(),
output: content,
}
} else {
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload {
content,
content_items,
success,
},
}
output: body.to_text().unwrap_or_default(),
};
}
// Function-style outputs (JSON function tools, including dynamic
// tools and MCP adaptation) preserve the exact body shape.
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output: FunctionCallOutputPayload { body, success },
}
}
// Direct MCP response path for MCP tool result envelopes.
ToolOutput::Mcp { result } => ResponseInputItem::McpToolCallOutput {
call_id: call_id.to_string(),
result,
@@ -158,6 +160,7 @@ fn telemetry_preview(content: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use codex_protocol::models::FunctionCallOutputContentItem;
use pretty_assertions::assert_eq;
#[test]
@@ -166,8 +169,7 @@ mod tests {
input: "patch".to_string(),
};
let response = ToolOutput::Function {
content: "patched".to_string(),
content_items: None,
body: FunctionCallOutputBody::Text("patched".to_string()),
success: Some(true),
}
.into_response("call-42", &payload);
@@ -187,8 +189,7 @@ mod tests {
arguments: "{}".to_string(),
};
let response = ToolOutput::Function {
content: "ok".to_string(),
content_items: None,
body: FunctionCallOutputBody::Text("ok".to_string()),
success: Some(true),
}
.into_response("fn-1", &payload);
@@ -196,14 +197,58 @@ mod tests {
match response {
ResponseInputItem::FunctionCallOutput { call_id, output } => {
assert_eq!(call_id, "fn-1");
assert_eq!(output.content, "ok");
assert!(output.content_items.is_none());
assert_eq!(output.text_content(), Some("ok"));
assert!(output.content_items().is_none());
assert_eq!(output.success, Some(true));
}
other => panic!("expected FunctionCallOutput, got {other:?}"),
}
}
#[test]
fn custom_tool_calls_can_derive_text_from_content_items() {
let payload = ToolPayload::Custom {
input: "patch".to_string(),
};
let response = ToolOutput::Function {
body: FunctionCallOutputBody::ContentItems(vec![
FunctionCallOutputContentItem::InputText {
text: "line 1".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image_url: "data:image/png;base64,AAA".to_string(),
},
FunctionCallOutputContentItem::InputText {
text: "line 2".to_string(),
},
]),
success: Some(true),
}
.into_response("call-99", &payload);
match response {
ResponseInputItem::CustomToolCallOutput { call_id, output } => {
assert_eq!(call_id, "call-99");
assert_eq!(output, "line 1\nline 2");
}
other => panic!("expected CustomToolCallOutput, got {other:?}"),
}
}
#[test]
fn log_preview_uses_content_items_when_plain_text_is_missing() {
let output = ToolOutput::Function {
body: FunctionCallOutputBody::ContentItems(vec![
FunctionCallOutputContentItem::InputText {
text: "preview".to_string(),
},
]),
success: Some(true),
};
assert_eq!(output.log_preview(), "preview");
}
#[test]
fn telemetry_preview_returns_original_within_limits() {
let content = "short output";
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::collections::BTreeMap;
use std::path::Path;
@@ -109,8 +110,7 @@ impl ToolHandler for ApplyPatchHandler {
InternalApplyPatchInvocation::Output(item) => {
let content = item?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
@@ -155,8 +155,7 @@ impl ToolHandler for ApplyPatchHandler {
);
let content = emitter.finish(event_ctx, out).await?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
@@ -205,8 +204,7 @@ pub(crate) async fn intercept_apply_patch(
InternalApplyPatchInvocation::Output(item) => {
let content = item?;
Ok(Some(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
}))
}
@@ -242,8 +240,7 @@ pub(crate) async fn intercept_apply_patch(
ToolEventCtx::new(session, turn, call_id, tracker.as_ref().copied());
let content = emitter.finish(event_ctx, out).await?;
Ok(Some(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
}))
}
+17 -12
View File
@@ -15,6 +15,7 @@ use crate::tools::registry::ToolKind;
use async_trait::async_trait;
use codex_protocol::ThreadId;
use codex_protocol::models::BaseInstructions;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::protocol::CollabAgentInteractionBeginEvent;
use codex_protocol::protocol::CollabAgentInteractionEndEvent;
use codex_protocol::protocol::CollabAgentSpawnBeginEvent;
@@ -184,9 +185,8 @@ mod spawn {
})?;
Ok(ToolOutput::Function {
content,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
content_items: None,
})
}
}
@@ -273,9 +273,8 @@ mod send_input {
})?;
Ok(ToolOutput::Function {
content,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
content_items: None,
})
}
}
@@ -441,9 +440,8 @@ mod wait {
})?;
Ok(ToolOutput::Function {
content,
body: FunctionCallOutputBody::Text(content),
success: None,
content_items: None,
})
}
@@ -552,9 +550,8 @@ pub mod close_agent {
})?;
Ok(ToolOutput::Function {
content,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
content_items: None,
})
}
}
@@ -970,7 +967,9 @@ mod tests {
.await
.expect("wait should succeed");
let ToolOutput::Function {
content, success, ..
body: FunctionCallOutputBody::Text(content),
success,
..
} = output
else {
panic!("expected function output");
@@ -1012,7 +1011,9 @@ mod tests {
.await
.expect("wait should succeed");
let ToolOutput::Function {
content, success, ..
body: FunctionCallOutputBody::Text(content),
success,
..
} = output
else {
panic!("expected function output");
@@ -1103,7 +1104,9 @@ mod tests {
.await
.expect("wait should succeed");
let ToolOutput::Function {
content, success, ..
body: FunctionCallOutputBody::Text(content),
success,
..
} = output
else {
panic!("expected function output");
@@ -1141,7 +1144,9 @@ mod tests {
.await
.expect("close_agent should succeed");
let ToolOutput::Function {
content, success, ..
body: FunctionCallOutputBody::Text(content),
success,
..
} = output
else {
panic!("expected function output");
+14 -3
View File
@@ -10,6 +10,8 @@ use crate::tools::registry::ToolKind;
use async_trait::async_trait;
use codex_protocol::dynamic_tools::DynamicToolCallRequest;
use codex_protocol::dynamic_tools::DynamicToolResponse;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::protocol::EventMsg;
use serde_json::Value;
use tokio::sync::oneshot;
@@ -55,10 +57,19 @@ impl ToolHandler for DynamicToolHandler {
)
})?;
let DynamicToolResponse {
content_items,
success,
} = response;
let body = content_items
.into_iter()
.map(FunctionCallOutputContentItem::from)
.collect::<Vec<_>>();
let body = FunctionCallOutputBody::ContentItems(body);
Ok(ToolOutput::Function {
content: response.output,
content_items: None,
success: Some(response.success),
body,
success: Some(success),
})
}
}
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::path::Path;
use std::time::Duration;
@@ -86,14 +87,12 @@ impl ToolHandler for GrepFilesHandler {
if search_results.is_empty() {
Ok(ToolOutput::Function {
content: "No matches found.".to_string(),
content_items: None,
body: FunctionCallOutputBody::Text("No matches found.".to_string()),
success: Some(false),
})
} else {
Ok(ToolOutput::Function {
content: search_results.join("\n"),
content_items: None,
body: FunctionCallOutputBody::Text(search_results.join("\n")),
success: Some(true),
})
}
+2 -2
View File
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::collections::VecDeque;
use std::ffi::OsStr;
use std::fs::FileType;
@@ -102,8 +103,7 @@ impl ToolHandler for ListDirHandler {
output.push(format!("Absolute path: {}", path.display()));
output.extend(entries);
Ok(ToolOutput::Function {
content: output.join("\n"),
content_items: None,
body: FunctionCallOutputBody::Text(output.join("\n")),
success: Some(true),
})
}
+6 -14
View File
@@ -8,6 +8,7 @@ use crate::tools::context::ToolOutput;
use crate::tools::context::ToolPayload;
use crate::tools::registry::ToolHandler;
use crate::tools::registry::ToolKind;
use codex_protocol::models::ResponseInputItem;
pub struct McpHandler;
@@ -53,20 +54,11 @@ impl ToolHandler for McpHandler {
.await;
match response {
codex_protocol::models::ResponseInputItem::McpToolCallOutput { result, .. } => {
Ok(ToolOutput::Mcp { result })
}
codex_protocol::models::ResponseInputItem::FunctionCallOutput { output, .. } => {
let codex_protocol::models::FunctionCallOutputPayload {
content,
content_items,
success,
} = output;
Ok(ToolOutput::Function {
content,
content_items,
success,
})
ResponseInputItem::McpToolCallOutput { result, .. } => Ok(ToolOutput::Mcp { result }),
ResponseInputItem::FunctionCallOutput { output, .. } => {
let success = output.success;
let body = output.body;
Ok(ToolOutput::Function { body, success })
}
_ => Err(FunctionCallError::RespondToModel(
"mcp handler received unexpected response variant".to_string(),
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
@@ -296,12 +297,10 @@ async fn handle_list_resources(
match payload_result {
Ok(payload) => match serialize_function_output(payload) {
Ok(output) => {
let ToolOutput::Function {
content, success, ..
} = &output
else {
let ToolOutput::Function { body, success } = &output else {
unreachable!("MCP resource handler should return function output");
};
let content = body.to_text().unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
@@ -309,7 +308,7 @@ async fn handle_list_resources(
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(content, *success)),
Ok(call_tool_result_from_content(&content, *success)),
)
.await;
Ok(output)
@@ -405,12 +404,10 @@ async fn handle_list_resource_templates(
match payload_result {
Ok(payload) => match serialize_function_output(payload) {
Ok(output) => {
let ToolOutput::Function {
content, success, ..
} = &output
else {
let ToolOutput::Function { body, success } = &output else {
unreachable!("MCP resource handler should return function output");
};
let content = body.to_text().unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
@@ -418,7 +415,7 @@ async fn handle_list_resource_templates(
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(content, *success)),
Ok(call_tool_result_from_content(&content, *success)),
)
.await;
Ok(output)
@@ -494,12 +491,10 @@ async fn handle_read_resource(
match payload_result {
Ok(payload) => match serialize_function_output(payload) {
Ok(output) => {
let ToolOutput::Function {
content, success, ..
} = &output
else {
let ToolOutput::Function { body, success } = &output else {
unreachable!("MCP resource handler should return function output");
};
let content = body.to_text().unwrap_or_default();
let duration = start.elapsed();
emit_tool_call_end(
&session,
@@ -507,7 +502,7 @@ async fn handle_read_resource(
&call_id,
invocation,
duration,
Ok(call_tool_result_from_content(content, *success)),
Ok(call_tool_result_from_content(&content, *success)),
)
.await;
Ok(output)
@@ -622,8 +617,7 @@ where
})?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
+2 -2
View File
@@ -11,6 +11,7 @@ use crate::tools::registry::ToolKind;
use crate::tools::spec::JsonSchema;
use async_trait::async_trait;
use codex_protocol::config_types::ModeKind;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::plan_tool::UpdatePlanArgs;
use codex_protocol::protocol::EventMsg;
use std::collections::BTreeMap;
@@ -88,8 +89,7 @@ impl ToolHandler for PlanHandler {
handle_update_plan(session.as_ref(), turn.as_ref(), arguments, call_id).await?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::collections::VecDeque;
use std::path::PathBuf;
@@ -146,8 +147,7 @@ impl ToolHandler for ReadFileHandler {
}
};
Ok(ToolOutput::Function {
content: collected.join("\n"),
content_items: None,
body: FunctionCallOutputBody::Text(collected.join("\n")),
success: Some(true),
})
}
@@ -1,4 +1,5 @@
use async_trait::async_trait;
use codex_protocol::models::FunctionCallOutputBody;
use crate::function_tool::FunctionCallError;
use crate::tools::context::ToolInvocation;
@@ -120,8 +121,7 @@ impl ToolHandler for RequestUserInputHandler {
})?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
+2 -2
View File
@@ -1,5 +1,6 @@
use async_trait::async_trait;
use codex_protocol::ThreadId;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::ShellCommandToolCallParams;
use codex_protocol::models::ShellToolCallParams;
use std::sync::Arc;
@@ -329,8 +330,7 @@ impl ShellHandler {
let event_ctx = ToolEventCtx::new(session.as_ref(), turn.as_ref(), &call_id, None);
let content = emitter.finish(event_ctx, out).await?;
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
@@ -1,3 +1,4 @@
use codex_protocol::models::FunctionCallOutputBody;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
@@ -91,8 +92,7 @@ impl ToolHandler for TestSyncHandler {
}
Ok(ToolOutput::Function {
content: "ok".to_string(),
content_items: None,
body: FunctionCallOutputBody::Text("ok".to_string()),
success: Some(true),
})
}
@@ -18,6 +18,7 @@ use crate::unified_exec::UnifiedExecProcessManager;
use crate::unified_exec::UnifiedExecResponse;
use crate::unified_exec::WriteStdinRequest;
use async_trait::async_trait;
use codex_protocol::models::FunctionCallOutputBody;
use serde::Deserialize;
use std::path::PathBuf;
use std::sync::Arc;
@@ -238,8 +239,7 @@ impl ToolHandler for UnifiedExecHandler {
let content = format_response(&response);
Ok(ToolOutput::Function {
content,
content_items: None,
body: FunctionCallOutputBody::Text(content),
success: Some(true),
})
}
@@ -1,4 +1,5 @@
use async_trait::async_trait;
use codex_protocol::models::FunctionCallOutputBody;
use serde::Deserialize;
use tokio::fs;
@@ -92,8 +93,7 @@ impl ToolHandler for ViewImageHandler {
.await;
Ok(ToolOutput::Function {
content: "attached local image path".to_string(),
content_items: None,
body: FunctionCallOutputBody::Text("attached local image path".to_string()),
success: Some(true),
})
}
+2 -1
View File
@@ -17,6 +17,7 @@ use crate::tools::context::SharedTurnDiffTracker;
use crate::tools::context::ToolPayload;
use crate::tools::router::ToolCall;
use crate::tools::router::ToolRouter;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ResponseInputItem;
@@ -119,7 +120,7 @@ impl ToolCallRuntime {
_ => ResponseInputItem::FunctionCallOutput {
call_id: call.call_id.clone(),
output: FunctionCallOutputPayload {
content: Self::abort_message(call, secs),
body: FunctionCallOutputBody::Text(Self::abort_message(call, secs)),
..Default::default()
},
},
+2 -2
View File
@@ -11,6 +11,7 @@ use crate::tools::registry::ToolRegistry;
use crate::tools::spec::ToolsConfig;
use crate::tools::spec::build_specs;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::LocalShellAction;
use codex_protocol::models::ResponseInputItem;
use codex_protocol::models::ResponseItem;
@@ -181,9 +182,8 @@ impl ToolRouter {
ResponseInputItem::FunctionCallOutput {
call_id,
output: codex_protocol::models::FunctionCallOutputPayload {
content: message,
body: FunctionCallOutputBody::Text(message),
success: Some(false),
..Default::default()
},
}
}