Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
//! Applies sparse catalog overrides while preserving bundled tool transport requirements.
//! Invalid parameters retain the bundled schema; other tool fields remain harness-owned.
use crate::ResponsesApiTool;
use crate::parse_catalog_tool_parameters;
use codex_protocol::openai_models::ToolMessage;
/// Apply catalog descriptions and parameters without changing the tool's identity or transport.
pub fn with_catalog_tool_message(
mut tool: ResponsesApiTool,
messages: Option<&ToolMessage>,
) -> ResponsesApiTool {
let Some(messages) = messages else {
return tool;
};
if let Some(description) = &messages.description {
tool.description.clone_from(description);
}
if let Some(parameters) = &messages.parameters {
let parameters = parse_catalog_tool_parameters(parameters).and_then(|mut parameters| {
if let Some(properties) = &tool.parameters.properties {
for (name, bundled_property) in properties.iter() {
if bundled_property.encrypted == Some(true) {
let property = parameters
.properties
.as_mut()
.and_then(|properties| properties.get_mut(name))
.ok_or("schema omits an encrypted parameter")?;
property.encrypted = Some(true);
}
}
}
Ok(parameters)
});
match parameters {
Ok(parameters) => tool.parameters = parameters,
Err(reason) => tracing::warn!(
tool = %tool.name,
reason,
"Invalid catalog tool parameters; using bundled parameters"
),
}
}
tool
}
#[cfg(test)]
#[path = "catalog_tool_message_tests.rs"]
mod tests;

View File

@@ -0,0 +1,85 @@
use super::*;
use crate::JsonSchema;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn catalog_overrides_preserve_tool_fields_and_encryption_with_independent_fallbacks() {
let bundled = ResponsesApiTool {
name: "example".to_string(),
description: "Bundled guidance.".to_string(),
strict: true,
defer_loading: Some(true),
parameters: serde_json::from_value(json!({
"type": "object",
"properties": {
"text": {"type": "string", "encrypted": true},
"title": {"type": "string", "encrypted": true},
"path": {"type": "string"}
}
}))
.unwrap(),
output_schema: Some(json!({"type": "string"}).into()),
};
assert_eq!(
with_catalog_tool_message(bundled.clone(), /*messages*/ None),
bundled,
);
let mut catalog = json!({
"type": "object",
"properties": {
"text": {"type": "string", "description": "Catalog guidance.", "encrypted": false},
"title": {"type": "string"},
"path": {"type": "string"}
}
});
let parameters = catalog.to_string();
catalog["properties"]["text"]["encrypted"] = json!(true);
catalog["properties"]["title"]["encrypted"] = json!(true);
let expected_parameters: JsonSchema = serde_json::from_value(catalog).unwrap();
for (description, schema, expected_schema) in [
(None, None, None),
(Some(""), None, None),
(None, Some(parameters.as_str()), Some(&expected_parameters)),
(
Some(" Catalog {{literal}} guidance.\n"),
Some(parameters.as_str()),
Some(&expected_parameters),
),
(Some("Catalog guidance."), Some("invalid JSON"), None),
(None, Some(r#"{"type":"string"}"#), None),
(
None,
Some(r#"{"type":"object","properties":{"text":{"type":"unsupported"}}}"#),
None,
),
(
Some(""),
Some(r#"{"type":"object","properties":{"title":{"type":"string"}}}"#),
None,
),
(
Some("Catalog guidance."),
Some(r#"{"type":"object","properties":{"text":{"type":"string"}}}"#),
None,
),
] {
let messages = ToolMessage {
description: description.map(str::to_owned),
parameters: schema.map(str::to_owned),
};
let mut expected = bundled.clone();
if let Some(description) = description {
expected.description = description.to_owned();
}
if let Some(parameters) = expected_schema {
expected.parameters = parameters.clone();
}
assert_eq!(
with_catalog_tool_message(bundled.clone(), Some(&messages)),
expected,
);
}
}

View File

@@ -0,0 +1,277 @@
use crate::ResponsesApiNamespaceTool;
use crate::ToolName;
use crate::ToolOutputSchema;
use crate::ToolSpec;
use codex_code_mode::CodeModeToolKind;
use codex_code_mode::ToolDefinition as CodeModeToolDefinition;
/// Augment tool descriptions with code-mode-specific exec samples.
pub fn augment_tool_spec_for_code_mode(
spec: ToolSpec,
code_mode_input_schema_max_bytes: Option<usize>,
) -> ToolSpec {
match spec {
ToolSpec::Function(mut tool) => {
let Some(description) = augmented_description_for_spec(
&ToolSpec::Function(tool.clone()),
code_mode_input_schema_max_bytes,
) else {
return ToolSpec::Function(tool);
};
tool.description = description;
ToolSpec::Function(tool)
}
ToolSpec::Freeform(mut tool) => {
let Some(description) = augmented_description_for_spec(
&ToolSpec::Freeform(tool.clone()),
code_mode_input_schema_max_bytes,
) else {
return ToolSpec::Freeform(tool);
};
tool.description = description;
ToolSpec::Freeform(tool)
}
ToolSpec::Namespace(mut namespace) => {
for tool in &mut namespace.tools {
match tool {
ResponsesApiNamespaceTool::Function(tool) => {
let tool_name =
ToolName::namespaced(namespace.name.clone(), tool.name.clone());
let definition = CodeModeToolDefinition {
name: code_mode_name_for_tool_name(&tool_name),
tool_name,
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
)),
output_schema: tool
.output_schema
.as_ref()
.map(ToolOutputSchema::to_value),
};
tool.description =
codex_code_mode::augment_tool_definition(definition).description;
}
ResponsesApiNamespaceTool::Custom(tool) => {
let tool_name =
ToolName::namespaced(namespace.name.clone(), tool.name.clone());
let definition = CodeModeToolDefinition {
name: code_mode_name_for_tool_name(&tool_name),
tool_name,
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
};
tool.description =
codex_code_mode::augment_tool_definition(definition).description;
}
}
}
ToolSpec::Namespace(namespace)
}
other => other,
}
}
/// Convert a supported nested tool spec into the code-mode runtime shape,
/// including the code-mode-specific description sample.
pub fn tool_spec_to_code_mode_tool_definition(spec: &ToolSpec) -> Option<CodeModeToolDefinition> {
let definition =
code_mode_tool_definition_for_spec(spec, /*code_mode_input_schema_max_bytes*/ None)?;
codex_code_mode::is_code_mode_nested_tool(&definition.name)
.then(|| codex_code_mode::augment_tool_definition(definition))
}
pub fn collect_code_mode_tool_definitions<'a>(
specs: impl IntoIterator<Item = &'a ToolSpec>,
code_mode_input_schema_max_bytes: Option<usize>,
) -> Vec<CodeModeToolDefinition> {
let mut tool_definitions = specs
.into_iter()
.flat_map(|spec| {
let mut definitions =
code_mode_tool_definitions_for_spec(spec, code_mode_input_schema_max_bytes);
if let ToolSpec::Namespace(namespace) = spec {
let namespace_description = namespace.description.trim();
if !namespace_description.is_empty() {
for definition in &mut definitions {
definition.description =
format!("{}\n\n{namespace_description}", definition.description);
}
}
}
definitions
})
.filter(|definition| codex_code_mode::is_code_mode_nested_tool(&definition.name))
.map(codex_code_mode::augment_tool_definition)
.collect::<Vec<_>>();
tool_definitions.sort_by(|left, right| left.name.cmp(&right.name));
tool_definitions.dedup_by(|left, right| left.name == right.name);
tool_definitions
}
pub fn collect_code_mode_exec_prompt_tool_definitions<'a>(
specs: impl IntoIterator<Item = &'a ToolSpec>,
code_mode_input_schema_max_bytes: Option<usize>,
) -> Vec<CodeModeToolDefinition> {
let mut tool_definitions = specs
.into_iter()
.flat_map(|spec| {
code_mode_tool_definitions_for_spec(spec, code_mode_input_schema_max_bytes)
})
.filter(|definition| codex_code_mode::is_code_mode_nested_tool(&definition.name))
.collect::<Vec<_>>();
tool_definitions.sort_by(|left, right| left.name.cmp(&right.name));
tool_definitions.dedup_by(|left, right| left.name == right.name);
tool_definitions
}
fn augmented_description_for_spec(
spec: &ToolSpec,
code_mode_input_schema_max_bytes: Option<usize>,
) -> Option<String> {
code_mode_tool_definition_for_spec(spec, code_mode_input_schema_max_bytes)
.map(codex_code_mode::augment_tool_definition)
.map(|definition| definition.description)
}
fn code_mode_tool_definition_for_spec(
spec: &ToolSpec,
code_mode_input_schema_max_bytes: Option<usize>,
) -> Option<CodeModeToolDefinition> {
code_mode_tool_definitions_for_spec(spec, code_mode_input_schema_max_bytes)
.into_iter()
.next()
}
fn effective_input_schema_max_bytes(
mcp_input_schema_max_bytes: Option<usize>,
code_mode_max_bytes: Option<usize>,
) -> usize {
codex_code_mode::DEFAULT_INPUT_SCHEMA_MAX_BYTES
.max(code_mode_max_bytes.unwrap_or_default())
.max(mcp_input_schema_max_bytes.unwrap_or_default())
}
fn code_mode_tool_definitions_for_spec(
spec: &ToolSpec,
code_mode_input_schema_max_bytes: Option<usize>,
) -> Vec<CodeModeToolDefinition> {
match spec {
ToolSpec::Function(tool) => {
let name = tool.name.clone();
vec![CodeModeToolDefinition {
tool_name: ToolName::plain(name.clone()),
name,
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
)),
output_schema: tool.output_schema.as_ref().map(ToolOutputSchema::to_value),
}]
}
ToolSpec::Freeform(tool) => {
let name = tool.name.clone();
vec![CodeModeToolDefinition {
tool_name: ToolName::plain(name.clone()),
name,
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}]
}
ToolSpec::Namespace(namespace) => namespace
.tools
.iter()
.map(|tool| match tool {
ResponsesApiNamespaceTool::Function(tool) => {
let tool_name = ToolName::namespaced(namespace.name.clone(), tool.name.clone());
CodeModeToolDefinition {
name: code_mode_name_for_tool_name(&tool_name),
tool_name,
description: tool.description.clone(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(&tool.parameters).ok(),
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
tool.parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
)),
output_schema: tool.output_schema.as_ref().map(ToolOutputSchema::to_value),
}
}
ResponsesApiNamespaceTool::Custom(tool) => {
let tool_name = ToolName::namespaced(namespace.name.clone(), tool.name.clone());
CodeModeToolDefinition {
name: code_mode_name_for_tool_name(&tool_name),
tool_name,
description: tool.description.clone(),
kind: CodeModeToolKind::Freeform,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
}
}
})
.collect(),
ToolSpec::ToolSearch { parameters, .. } => {
let name = spec.name().to_string();
vec![CodeModeToolDefinition {
tool_name: ToolName::plain(name.clone()),
name,
description: codex_code_mode::TOOL_SEARCH_GUIDANCE.to_string(),
kind: CodeModeToolKind::Function,
input_schema: serde_json::to_value(parameters).ok(),
input_schema_max_bytes: Some(effective_input_schema_max_bytes(
parameters.mcp_input_schema_max_bytes,
code_mode_input_schema_max_bytes,
)),
output_schema: Some(serde_json::json!({
"type": "object",
"properties": {
"tools": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": { "type": "string" },
"description": { "type": "string" }
},
"required": ["name", "description"]
}
}
},
"required": ["tools"]
})),
}]
}
ToolSpec::WebSearch { .. } => Vec::new(),
}
}
pub fn code_mode_name_for_tool_name(tool_name: &ToolName) -> String {
if tool_name.is_default_namespace() {
return tool_name.name.clone();
}
match tool_name.namespace.as_deref() {
Some(namespace) if namespace.ends_with('_') || tool_name.name.starts_with('_') => {
format!("{namespace}{}", tool_name.name)
}
Some(namespace) => format!("{namespace}__{}", tool_name.name),
None => tool_name.name.clone(),
}
}
#[cfg(test)]
#[path = "code_mode_tests.rs"]
mod tests;

View File

@@ -0,0 +1,287 @@
use super::augment_tool_spec_for_code_mode as augment_tool_spec_with_budget;
use super::code_mode_name_for_tool_name;
use super::tool_spec_to_code_mode_tool_definition;
use crate::AdditionalProperties;
use crate::FreeformTool;
use crate::FreeformToolFormat;
use crate::JsonSchema;
use crate::ResponsesApiNamespace;
use crate::ResponsesApiNamespaceTool;
use crate::ResponsesApiTool;
use crate::ToolName;
use crate::ToolSpec;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
fn augment_tool_spec_for_code_mode(spec: ToolSpec) -> ToolSpec {
augment_tool_spec_with_budget(spec, /*code_mode_input_schema_max_bytes*/ None)
}
#[test]
fn code_mode_input_schema_uses_the_larger_budget() {
let default_code_mode = codex_code_mode::DEFAULT_INPUT_SCHEMA_MAX_BYTES;
for (mcp, code_mode, expected) in [
(None, None, default_code_mode),
(Some(5_000), Some(1_000), default_code_mode),
(None, Some(1_000), default_code_mode),
(Some(30_000), Some(20_000), 30_000),
(Some(20_000), Some(30_000), 30_000),
] {
assert_eq!(
super::effective_input_schema_max_bytes(mcp, code_mode),
expected
);
}
}
#[test]
fn code_mode_materializes_mcp_output_schemas() {
let output = json!({"type": "object", "properties": {"ok": {"type": "boolean"}}});
let mut tool = rmcp::model::Tool::new(
"lookup_order",
"Look up an order",
std::sync::Arc::new(rmcp::model::object(json!({"type": "object"}))),
);
tool.output_schema = Some(std::sync::Arc::new(rmcp::model::object(output.clone())));
let parsed = crate::mcp_tool_to_responses_api_tool(
&ToolName::plain("lookup_order"),
&tool,
/*schema_max_bytes*/ None,
)
.unwrap();
let eager = ResponsesApiTool {
output_schema: Some(crate::mcp_call_tool_result_output_schema(output).into()),
..parsed.clone()
};
assert_eq!(
super::collect_code_mode_tool_definitions(
[&ToolSpec::Function(parsed)],
/*code_mode_input_schema_max_bytes*/ None,
),
super::collect_code_mode_tool_definitions(
[&ToolSpec::Function(eager)],
/*code_mode_input_schema_max_bytes*/ None,
),
);
}
#[test]
fn code_mode_tool_names_do_not_prefix_the_default_namespace() {
for tool_name in [
ToolName::plain("apply_patch"),
ToolName::namespaced("functions", "apply_patch"),
] {
assert_eq!(code_mode_name_for_tool_name(&tool_name), "apply_patch");
}
assert_eq!(
code_mode_name_for_tool_name(&ToolName::namespaced("editor", "apply_patch")),
"editor__apply_patch"
);
}
#[test]
fn augment_tool_spec_for_code_mode_augments_function_tools() {
assert_eq!(
augment_tool_spec_for_code_mode(ToolSpec::Function(ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: Some(true),
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(AdditionalProperties::Boolean(false))
),
output_schema: Some(
json!({
"type": "object",
"properties": {
"ok": {"type": "boolean"}
},
"required": ["ok"],
})
.into()
),
})),
ToolSpec::Function(ResponsesApiTool {
name: "lookup_order".to_string(),
description: r#"Look up an order
exec tool declaration:
```ts
declare const tools: { lookup_order(args: { order_id: string; }): Promise<{ ok: boolean; }>; };
```"#
.to_string(),
strict: false,
defer_loading: Some(true),
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(AdditionalProperties::Boolean(false))
),
output_schema: Some(
json!({
"type": "object",
"properties": {
"ok": {"type": "boolean"}
},
"required": ["ok"],
})
.into()
),
})
);
}
#[test]
fn augment_tool_spec_for_code_mode_preserves_exec_tool_description() {
assert_eq!(
augment_tool_spec_for_code_mode(ToolSpec::Freeform(FreeformTool {
name: codex_code_mode::PUBLIC_TOOL_NAME.to_string(),
description: "Run code".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"exec\"".to_string(),
},
})),
ToolSpec::Freeform(FreeformTool {
name: codex_code_mode::PUBLIC_TOOL_NAME.to_string(),
description: "Run code".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"exec\"".to_string(),
},
})
);
}
#[test]
fn tool_spec_to_code_mode_tool_definition_returns_augmented_nested_tools() {
let spec = ToolSpec::Freeform(FreeformTool {
name: "apply_patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
});
assert_eq!(
tool_spec_to_code_mode_tool_definition(&spec),
Some(codex_code_mode::ToolDefinition {
name: "apply_patch".to_string(),
tool_name: ToolName::plain("apply_patch"),
description: r#"Apply a patch
exec tool declaration:
```ts
declare const tools: { apply_patch(input: string): Promise<unknown>; };
```"#
.to_string(),
kind: codex_code_mode::CodeModeToolKind::Freeform,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
})
);
}
#[test]
fn tool_spec_to_code_mode_tool_definition_supports_namespaced_custom_tools() {
let spec = ToolSpec::Namespace(ResponsesApiNamespace {
name: "editor".to_string(),
description: "Editing tools".to_string(),
tools: vec![ResponsesApiNamespaceTool::Custom(FreeformTool {
name: "apply_patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
})],
});
assert_eq!(
tool_spec_to_code_mode_tool_definition(&spec),
Some(codex_code_mode::ToolDefinition {
name: "editor__apply_patch".to_string(),
tool_name: ToolName::namespaced("editor", "apply_patch"),
description: r#"Apply a patch
exec tool declaration:
```ts
declare const tools: { editor__apply_patch(input: string): Promise<unknown>; };
```"#
.to_string(),
kind: codex_code_mode::CodeModeToolKind::Freeform,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
})
);
}
#[test]
fn tool_search_spec_converts_to_a_callable_code_mode_definition() {
let definition = tool_spec_to_code_mode_tool_definition(&ToolSpec::ToolSearch {
execution: "client".to_string(),
description: "Native tool discovery".to_string(),
parameters: JsonSchema::object(
BTreeMap::from([(
"query".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["query".to_string()]),
Some(AdditionalProperties::Boolean(false)),
),
})
.expect("tool search should be callable from Code Mode");
assert_eq!(
(
&definition.name,
&definition.tool_name,
&definition.input_schema,
definition.input_schema_max_bytes,
),
(
&"tool_search".to_string(),
&ToolName::plain("tool_search"),
&Some(json!({
"type": "object",
"properties": {
"query": { "type": "string" },
},
"required": ["query"],
"additionalProperties": false,
})),
Some(codex_code_mode::DEFAULT_INPUT_SCHEMA_MAX_BYTES),
),
);
assert!(
definition
.description
.contains("tool_search(args: { query: string; })")
);
assert!(
definition
.description
.contains("tools[result.name](arguments)")
);
assert!(!definition.description.contains("Native tool discovery"));
}

View File

@@ -0,0 +1,19 @@
use crate::ToolDefinition;
use crate::parse_tool_input_schema;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
pub fn parse_dynamic_tool(
tool: &DynamicToolFunctionSpec,
) -> Result<ToolDefinition, serde_json::Error> {
Ok(ToolDefinition {
name: tool.name.clone(),
description: tool.description.clone(),
input_schema: parse_tool_input_schema(&tool.input_schema)?,
output_schema: None,
defer_loading: tool.defer_loading,
})
}
#[cfg(test)]
#[path = "dynamic_tool_tests.rs"]
mod tests;

View File

@@ -0,0 +1,65 @@
use super::parse_dynamic_tool;
use crate::JsonSchema;
use crate::ToolDefinition;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn parse_dynamic_tool_sanitizes_input_schema() {
let tool = DynamicToolFunctionSpec {
name: "lookup_ticket".to_string(),
description: "Fetch a ticket".to_string(),
input_schema: serde_json::json!({
"properties": {
"id": {
"description": "Ticket identifier"
}
}
}),
defer_loading: false,
};
assert_eq!(
parse_dynamic_tool(&tool).expect("parse dynamic tool"),
ToolDefinition {
name: "lookup_ticket".to_string(),
description: "Fetch a ticket".to_string(),
input_schema: JsonSchema::object(
BTreeMap::from([("id".to_string(), JsonSchema::default(),)]),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: None,
defer_loading: false,
}
);
}
#[test]
fn parse_dynamic_tool_preserves_defer_loading() {
let tool = DynamicToolFunctionSpec {
name: "lookup_ticket".to_string(),
description: "Fetch a ticket".to_string(),
input_schema: serde_json::json!({
"type": "object",
"properties": {}
}),
defer_loading: true,
};
assert_eq!(
parse_dynamic_tool(&tool).expect("parse dynamic tool"),
ToolDefinition {
name: "lookup_ticket".to_string(),
description: "Fetch a ticket".to_string(),
input_schema: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: None,
defer_loading: true,
}
);
}

View File

@@ -0,0 +1,10 @@
use thiserror::Error;
/// Error returned while executing a model-visible tool invocation.
#[derive(Debug, Error, PartialEq)]
pub enum FunctionCallError {
#[error("{0}")]
RespondToModel(String),
#[error("Fatal error: {0}")]
Fatal(String),
}

View File

@@ -0,0 +1,83 @@
//! Prepares function descriptions before direct, Code Mode, or search rendering.
//! Only the `functions` namespace is affected; runtime-owned specs stay unchanged.
use crate::ResponsesApiNamespaceTool;
use crate::ToolName;
use crate::ToolSpec;
use std::collections::BTreeMap;
/// Trimmed, size-bounded description prefixes for the available `functions.*` tools.
#[derive(Default)]
pub struct FunctionsNamespaceFunctionPrefixes(BTreeMap<String, String>);
impl FunctionsNamespaceFunctionPrefixes {
pub fn new(
prefixes: Option<&BTreeMap<String, String>>,
available_tools: impl IntoIterator<Item = ToolName>,
) -> Result<Self, &'static str> {
let Some(prefixes) = prefixes.filter(|prefixes| !prefixes.is_empty()) else {
return Ok(Self::default());
};
let mut remaining = 256usize;
let mut normalized = BTreeMap::new();
for tool in available_tools {
if !tool.is_default_namespace() || normalized.contains_key(&tool.name) {
continue;
}
let Some(prefix) = prefixes.get(&tool.name) else {
continue;
};
let prefix = prefix.trim();
if prefix.is_empty() {
continue;
}
remaining = remaining
.checked_sub(prefix.len())
.and_then(|remaining| remaining.checked_sub(2))
.ok_or(
"Available functions' description prefixes exceed the 256-byte combined limit",
)?;
normalized.insert(tool.name, prefix.to_owned());
}
Ok(Self(normalized))
}
/// Returns an owned replacement only for a configured function. Unaffected tools
/// keep their original specs and derived caches, including large MCP schemas.
pub fn prepare(&self, name: &ToolName, spec: impl FnOnce() -> ToolSpec) -> Option<ToolSpec> {
if !name.is_default_namespace() || !self.0.contains_key(&name.name) {
return None;
}
let mut spec = spec();
match &mut spec {
ToolSpec::Function(tool) => self.prepend(&tool.name, &mut tool.description),
ToolSpec::Freeform(tool) => self.prepend(&tool.name, &mut tool.description),
ToolSpec::Namespace(namespace) if namespace.name == "functions" => {
for tool in &mut namespace.tools {
match tool {
ResponsesApiNamespaceTool::Function(tool) => {
self.prepend(&tool.name, &mut tool.description);
}
ResponsesApiNamespaceTool::Custom(tool) => {
self.prepend(&tool.name, &mut tool.description);
}
}
}
}
ToolSpec::Namespace(_) | ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => {
return None;
}
}
Some(spec)
}
fn prepend(&self, name: &str, description: &mut String) {
if let Some(prefix) = self.0.get(name) {
*description = if description.is_empty() {
prefix.clone()
} else {
format!("{prefix}\n\n{description}")
};
}
}
}

View File

@@ -0,0 +1,42 @@
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ImageDetail;
use codex_protocol::openai_models::ModelInfo;
pub fn can_request_original_image_detail(model_info: &ModelInfo) -> bool {
model_info.supports_image_detail_original
}
pub fn normalize_output_image_detail(
model_info: &ModelInfo,
detail: Option<ImageDetail>,
) -> Option<ImageDetail> {
match detail {
Some(ImageDetail::Original) if can_request_original_image_detail(model_info) => {
Some(ImageDetail::Original)
}
Some(ImageDetail::Original) | None => None,
Some(ImageDetail::Auto | ImageDetail::Low | ImageDetail::High) => detail,
}
}
pub fn sanitize_original_image_detail(
can_request_original_image_detail: bool,
items: &mut [FunctionCallOutputContentItem],
) {
if can_request_original_image_detail {
return;
}
for item in items {
if let FunctionCallOutputContentItem::InputImage { detail, .. } = item
&& matches!(detail, Some(ImageDetail::Original))
{
*detail = Some(DEFAULT_IMAGE_DETAIL);
}
}
}
#[cfg(test)]
#[path = "image_detail_tests.rs"]
mod tests;

View File

@@ -0,0 +1,127 @@
use super::*;
use codex_protocol::models::DEFAULT_IMAGE_DETAIL;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::ImageDetail;
use codex_protocol::models::ImageReference;
use codex_protocol::openai_models::ModelInfo;
use pretty_assertions::assert_eq;
use serde_json::json;
fn model_info() -> ModelInfo {
serde_json::from_value(json!({
"slug": "test-model",
"display_name": "Test Model",
"description": null,
"supported_reasoning_levels": [],
"shell_type": "shell_command",
"visibility": "list",
"supported_in_api": true,
"priority": 1,
"availability_nux": null,
"upgrade": null,
"model_messages": null,
"default_reasoning_summary": "auto",
"support_verbosity": false,
"default_verbosity": null,
"apply_patch_tool_type": null,
"truncation_policy": {
"mode": "bytes",
"limit": 10000
},
"supports_image_detail_original": true,
"context_window": null,
"auto_compact_token_limit": null,
"effective_context_window_percent": 95,
"experimental_supported_tools": [],
"input_modalities": ["text", "image"],
"supports_search_tool": false
}))
.expect("deserialize test model")
}
#[test]
fn explicit_original_is_allowed_when_model_supports_it() {
let model_info = model_info();
assert!(can_request_original_image_detail(&model_info));
assert_eq!(
normalize_output_image_detail(&model_info, Some(ImageDetail::Original)),
Some(ImageDetail::Original)
);
assert_eq!(
normalize_output_image_detail(&model_info, /*detail*/ None),
None
);
}
#[test]
fn explicit_original_is_dropped_without_model_support() {
let mut model_info = model_info();
model_info.supports_image_detail_original = false;
assert_eq!(
normalize_output_image_detail(&model_info, Some(ImageDetail::Original)),
None
);
}
#[test]
fn explicit_non_original_detail_is_preserved() {
let model_info = model_info();
assert_eq!(
normalize_output_image_detail(&model_info, Some(ImageDetail::Auto)),
Some(ImageDetail::Auto)
);
assert_eq!(
normalize_output_image_detail(&model_info, Some(ImageDetail::Low)),
Some(ImageDetail::Low)
);
assert_eq!(
normalize_output_image_detail(&model_info, Some(ImageDetail::High)),
Some(ImageDetail::High)
);
}
#[test]
fn sanitize_original_falls_back_to_high_without_support() {
let mut items = vec![
FunctionCallOutputContentItem::InputText {
text: "header".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,AAA".to_string(),
},
detail: Some(ImageDetail::Original),
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,BBB".to_string(),
},
detail: Some(ImageDetail::Low),
},
];
sanitize_original_image_detail(/*can_request_original_image_detail*/ false, &mut items);
assert_eq!(
items,
vec![
FunctionCallOutputContentItem::InputText {
text: "header".to_string(),
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,AAA".to_string()
},
detail: Some(DEFAULT_IMAGE_DETAIL),
},
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,BBB".to_string()
},
detail: Some(ImageDetail::Low),
},
]
);
}

View File

@@ -0,0 +1,174 @@
//! Adds namespace guidance to indirect tool descriptions after selection.
//! Conflicting prefixes for the same final namespace are rejected before rendering.
//! Direct specifications, search indexes, and cached definitions remain unchanged.
use crate::LoadableToolSpec;
use crate::ToolName;
use codex_code_mode::ToolDefinition;
use codex_code_mode::ToolNamespaceDescription;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use codex_protocol::openai_models::IndirectDescriptionPrefixes;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::btree_map::Entry;
/// Conflicting catalog selectors for the same namespace, without including their prompt text.
#[derive(Debug, thiserror::Error)]
#[error(
"Conflicting indirect description prefixes for namespace `{namespace}`: `{first_source}` and `{second_source}`"
)]
pub struct IndirectNamespacePrefixConflict {
namespace: String,
first_source: String,
second_source: String,
}
/// Borrowed model text applied only to fresh indirect presentation data.
pub struct IndirectNamespacePrefixes<'a> {
prefixes: BTreeMap<String, &'a str>,
}
impl<'a> IndirectNamespacePrefixes<'a> {
/// Expands configured server names using registered tools' final namespaces.
/// Overlapping selectors must agree after trimming, including explicit empty values.
pub fn new<'s>(
prefixes: Option<&'a IndirectDescriptionPrefixes>,
namespaces: impl IntoIterator<Item = (&'s str, &'s str)>,
) -> Result<Self, IndirectNamespacePrefixConflict> {
let mut resolved = BTreeMap::new();
if let Some(namespaces) = prefixes.and_then(|prefixes| prefixes.namespaces.as_ref()) {
for (namespace, prefix) in namespaces {
resolved.insert(
namespace.clone(),
(prefix.trim(), format!("namespaces.{namespace}")),
);
}
}
if let Some(servers) = prefixes
.and_then(|prefixes| prefixes.mcp_servers.as_ref())
.filter(|servers| !servers.is_empty())
{
for (server, namespace) in namespaces {
if let Some(prefix) = servers.get(server) {
let prefix = prefix.trim();
match resolved.entry(namespace.to_owned()) {
Entry::Vacant(entry) => {
entry.insert((prefix, format!("mcp_servers.{server}")));
}
Entry::Occupied(entry) if entry.get().0 != prefix => {
return Err(IndirectNamespacePrefixConflict {
namespace: namespace.to_owned(),
first_source: entry.get().1.clone(),
second_source: format!("mcp_servers.{server}"),
});
}
Entry::Occupied(_) => {}
}
}
}
}
Ok(Self {
prefixes: resolved
.into_iter()
.filter(|(_, (prefix, _))| !prefix.is_empty())
.map(|(namespace, (prefix, _))| (namespace, prefix))
.collect(),
})
}
/// ALL_TOOLS is flat, so each entry carries its namespace's guidance.
/// Its eventual model-visible output is subject to normal tool-output truncation.
pub fn apply_code_mode(&self, tools: &mut [ToolDefinition]) {
if self.prefixes.is_empty() {
return;
}
for tool in tools {
self.apply_code_mode_description(&tool.tool_name, &mut tool.description);
}
}
/// Adds guidance to one owned description without copying the tool's schemas.
pub fn apply_code_mode_description(&self, tool_name: &ToolName, description: &mut String) {
if let Some(prefix) = self.prefix(namespace_name(tool_name)) {
prepend(prefix, description);
}
}
/// Adds one prefix per namespace actually embedded in the exec description.
pub fn apply_exec_prompt(
&self,
tools: &mut [ToolDefinition],
namespaces: &mut BTreeMap<String, ToolNamespaceDescription>,
) {
if self.prefixes.is_empty() {
return;
}
let mut has_default_prefix = false;
let rendered_namespaces = tools
.iter()
.map(|tool| namespace_name(&tool.tool_name))
.collect::<BTreeSet<_>>();
for name in rendered_namespaces {
if let Some(prefix) = self.prefix(name) {
let namespace = namespaces.entry(name.to_string()).or_insert_with(|| {
ToolNamespaceDescription {
name: name.to_string(),
description: String::new(),
}
});
prepend(prefix, &mut namespace.description);
has_default_prefix |= name == DEFAULT_FUNCTION_NAMESPACE;
}
}
if has_default_prefix {
// Only temporary prompt definitions join this group; runtime names stay unchanged.
for tool in tools {
if tool
.tool_name
.namespace
.as_deref()
.is_none_or(str::is_empty)
{
tool.tool_name.namespace = Some(DEFAULT_FUNCTION_NAMESPACE.to_string());
}
}
}
}
/// Applies prefixes after search ranking and namespace coalescing.
pub fn apply_search(&self, tools: &mut [LoadableToolSpec]) {
if self.prefixes.is_empty() {
return;
}
for spec in tools {
if let LoadableToolSpec::Namespace(namespace) = spec
&& let Some(prefix) = self.prefix(&namespace.name)
{
prepend(prefix, &mut namespace.description);
}
}
}
fn prefix(&self, namespace: &str) -> Option<&'a str> {
self.prefixes.get(namespace).copied()
}
}
fn prepend(prefix: &str, description: &mut String) {
*description = if description.is_empty() {
prefix.to_string()
} else {
format!("{prefix}\n\n{description}")
};
}
fn namespace_name(name: &ToolName) -> &str {
name.namespace
.as_deref()
.filter(|namespace| !namespace.is_empty())
.unwrap_or(DEFAULT_FUNCTION_NAMESPACE)
}
#[cfg(test)]
#[path = "indirect_namespace_prefixes_tests.rs"]
mod tests;

View File

@@ -0,0 +1,211 @@
//! Checks prefix normalization and rendering without exercising tool execution.
use super::*;
use codex_code_mode::CodeModeToolKind;
use codex_protocol::openai_models::IndirectDescriptionPrefixes;
use codex_protocol::openai_models::ToolMessages;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn plain_tools_join_an_existing_functions_group_only_with_a_prefix() {
let original_tools = [
ToolName::plain("plain"),
ToolName::namespaced("functions", "namespaced"),
]
.map(|tool_name| ToolDefinition {
name: tool_name.name.clone(),
tool_name,
description: "Tool guidance.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
});
let original_namespaces = BTreeMap::from([(
"functions".to_string(),
ToolNamespaceDescription {
name: "functions".to_string(),
description: "Original namespace guidance.".to_string(),
},
)]);
let render = |tools: &[ToolDefinition],
namespaces: &BTreeMap<String, ToolNamespaceDescription>| {
codex_code_mode::build_exec_tool_description_and_definitions(
tools,
&[],
namespaces,
codex_code_mode::DEFAULT_EXEC_YIELD_TIME_MS,
/*code_mode_only*/ true,
codex_code_mode::ImageDetailVisibility::Visible,
codex_code_mode::DeferredToolDiscovery::Catalog,
/*incremental_exec_enabled*/ false,
/*messages*/ None,
)
.0
};
let original = render(&original_tools, &original_namespaces);
for messages in [
json!({}),
json!({"indirect_description_prefixes": null}),
json!({"indirect_description_prefixes": {}}),
json!({"indirect_description_prefixes": {"namespaces": null, "mcp_servers": null}}),
json!({"indirect_description_prefixes": {"namespaces": {}, "mcp_servers": {}}}),
json!({"indirect_description_prefixes": {"namespaces": {"functions": " \n"}}}),
json!({"indirect_description_prefixes": {
"namespaces": {"unavailable": "Unused guidance."},
}}),
] {
let configured: ToolMessages = serde_json::from_value(messages).unwrap();
let mut tools = original_tools.clone();
let mut namespaces = original_namespaces.clone();
IndirectNamespacePrefixes::new(configured.indirect_description_prefixes.as_ref(), [])
.unwrap()
.apply_exec_prompt(&mut tools, &mut namespaces);
assert_eq!(render(&tools, &namespaces), original);
}
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"functions".to_string(),
"Catalog guidance.".to_string(),
)])),
..Default::default()
};
let mut tools = original_tools;
let mut namespaces = original_namespaces;
IndirectNamespacePrefixes::new(Some(&configured), [])
.unwrap()
.apply_exec_prompt(&mut tools, &mut namespaces);
let rendered = render(&tools, &namespaces);
assert_eq!(rendered.matches("## functions").count(), 1);
assert!(rendered.contains("## functions\nCatalog guidance.\n\nOriginal namespace guidance."));
assert!(rendered.find("## functions").unwrap() < rendered.find("### `plain`").unwrap());
}
#[test]
fn flat_tool_descriptions_use_trimmed_namespace_prefixes() {
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"functions".to_string(),
" \nFunction guidance.\t ".to_string(),
)])),
..Default::default()
};
let original = ToolDefinition {
name: "inspect".to_string(),
tool_name: ToolName::plain("inspect"),
description: "Inspect.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
};
let mut tools = [original.clone()];
IndirectNamespacePrefixes::new(Some(&configured), [])
.unwrap()
.apply_code_mode(&mut tools);
assert_eq!(
tools,
[ToolDefinition {
description: "Function guidance.\n\nInspect.".to_string(),
..original
}]
);
}
#[test]
fn matching_prefixes_cover_each_namespace_once() {
let servers = BTreeMap::from([
("codex_apps".to_string(), " App guidance. ".to_string()),
("apps_alias".to_string(), "App guidance.\n".to_string()),
]);
let exact = BTreeMap::from([(
"mcp__codex_apps__gmail".to_string(),
"App guidance.".to_string(),
)]);
let configured = IndirectDescriptionPrefixes {
namespaces: Some(exact),
mcp_servers: Some(servers),
};
let original = ["gmail", "calendar", "drive", "slack"].map(|app| ToolDefinition {
name: format!("mcp__codex_apps__{app}__search"),
tool_name: ToolName::namespaced(format!("mcp__codex_apps__{app}"), "search"),
description: "Search.".to_string(),
kind: CodeModeToolKind::Function,
input_schema: None,
input_schema_max_bytes: None,
output_schema: None,
});
let mut tools = original.clone();
let namespaces = original
.iter()
.map(|tool| ("codex_apps", tool.tool_name.namespace.as_deref().unwrap()))
.chain([
("codex_apps", "mcp__codex_apps__gmail"),
("apps_alias", "mcp__codex_apps__gmail"),
]);
IndirectNamespacePrefixes::new(Some(&configured), namespaces)
.unwrap()
.apply_code_mode(&mut tools);
let expected = original
.into_iter()
.map(|tool| ToolDefinition {
description: "App guidance.\n\nSearch.".to_string(),
..tool
})
.collect::<Vec<_>>();
assert_eq!(tools.as_slice(), expected);
}
#[test]
fn conflicting_namespace_and_server_prefixes_report_keys_without_values() {
for (namespace_prefix, server_prefix) in [
("Namespace guidance.", "Server guidance."),
("", "Server guidance."),
("Namespace guidance.", " \n"),
] {
let configured = IndirectDescriptionPrefixes {
namespaces: Some(BTreeMap::from([(
"mcp__reports_one".to_string(),
namespace_prefix.to_string(),
)])),
mcp_servers: Some(BTreeMap::from([(
"reports.one".to_string(),
server_prefix.to_string(),
)])),
};
let error = IndirectNamespacePrefixes::new(
Some(&configured),
[("reports.one", "mcp__reports_one")],
)
.err()
.expect("conflicting prefixes")
.to_string();
assert_eq!(
error,
"Conflicting indirect description prefixes for namespace `mcp__reports_one`: `namespaces.mcp__reports_one` and `mcp_servers.reports.one`",
);
}
}
#[test]
fn conflicting_mcp_servers_report_the_shared_namespace() {
let configured = IndirectDescriptionPrefixes {
mcp_servers: Some(BTreeMap::from([
("reports.one".to_string(), "First guidance.".to_string()),
("reports.two".to_string(), "Second guidance.".to_string()),
])),
..Default::default()
};
let error = IndirectNamespacePrefixes::new(
Some(&configured),
[("reports.one", "shared"), ("reports.two", "shared")],
)
.err()
.expect("conflicting prefixes")
.to_string();
assert_eq!(
error,
"Conflicting indirect description prefixes for namespace `shared`: `mcp_servers.reports.one` and `mcp_servers.reports.two`",
);
}

View File

@@ -0,0 +1,429 @@
//! Parse catalog overrides and normalize external tool schemas with their size policy.
mod compaction;
mod traversal;
mod types;
pub use types::AdditionalProperties;
pub use types::JsonSchema;
pub use types::JsonSchemaPrimitiveType;
pub use types::JsonSchemaType;
use compaction::DEFAULT_COMPACT_TOOL_SCHEMA_BYTES;
use compaction::compact_large_tool_schema;
use traversal::DefinitionTraversal;
use traversal::for_each_schema_child;
use serde_json::Value as JsonValue;
use serde_json::json;
use std::collections::BTreeSet;
const DEFINITION_TABLE_KEYS: [&str; 2] = ["$defs", "definitions"];
const SCHEMA_CHILD_KEYS: [&str; 4] = ["items", "anyOf", "oneOf", "allOf"];
const COMPOSITION_SCHEMA_KEYS: [&str; 3] = ["anyOf", "oneOf", "allOf"];
/// Parse catalog parameters without normalization or compaction.
/// Consumers own fallback and transport-specific requirements.
pub fn parse_catalog_tool_parameters(parameters: &str) -> Result<JsonSchema, &'static str> {
let parameters: JsonValue =
serde_json::from_str(parameters).map_err(|_| "schema is not valid JSON")?;
if !parameters.is_object() || parameters["type"] != "object" {
return Err("schema must declare an object type");
}
serde_json::from_value(parameters).map_err(|_| "schema uses unsupported JSON Schema structures")
}
/// Parse the tool `input_schema` or return an error for invalid schema.
pub fn parse_tool_input_schema(input_schema: &JsonValue) -> Result<JsonSchema, serde_json::Error> {
parse_tool_input_schema_with_max_bytes(input_schema, DEFAULT_COMPACT_TOOL_SCHEMA_BYTES)
}
/// Compact a tool input schema using the supplied threshold.
pub(crate) fn parse_tool_input_schema_with_max_bytes(
input_schema: &JsonValue,
max_bytes: usize,
) -> Result<JsonSchema, serde_json::Error> {
let mut input_schema = prepare_tool_input_schema(input_schema);
compact_large_tool_schema(&mut input_schema, max_bytes);
deserialize_tool_input_schema(input_schema)
}
/// Parse a trusted tool `input_schema` without running large-schema compaction.
pub fn parse_tool_input_schema_without_compaction(
input_schema: &JsonValue,
) -> Result<JsonSchema, serde_json::Error> {
deserialize_tool_input_schema(prepare_tool_input_schema(input_schema))
}
fn prepare_tool_input_schema(input_schema: &JsonValue) -> JsonValue {
let mut input_schema = input_schema.clone();
sanitize_json_schema(&mut input_schema);
prune_unreachable_definitions(&mut input_schema);
input_schema
}
fn deserialize_tool_input_schema(input_schema: JsonValue) -> Result<JsonSchema, serde_json::Error> {
let schema: JsonSchema = serde_json::from_value(input_schema)?;
if matches!(
schema.schema_type,
Some(JsonSchemaType::Single(JsonSchemaPrimitiveType::Null))
) {
return Err(singleton_null_schema_error());
}
Ok(schema)
}
fn has_composition_keyword(map: &serde_json::Map<String, JsonValue>) -> bool {
COMPOSITION_SCHEMA_KEYS
.into_iter()
.any(|key| map.contains_key(key))
}
/// Sanitize a JSON Schema (as serde_json::Value) so it can fit our limited
/// schema representation. This function:
/// - Ensures every typed schema object has a `"type"` when required.
/// - Preserves explicit `anyOf`, `oneOf`, and `allOf`.
/// - Preserves `$ref` and reachable local `$defs` / `definitions`.
/// - Collapses `const` into single-value `enum`.
/// - Fills required child fields for object/array schema types, including
/// nullable unions, with permissive defaults when absent.
/// - Coerces object schemas with no recognized schema hints into `{}`.
fn sanitize_json_schema(value: &mut JsonValue) {
match value {
JsonValue::Bool(_) => {
// JSON Schema boolean form: true/false. Coerce to an accept-all string.
*value = json!({ "type": "string" });
}
JsonValue::Array(values) => {
for value in values {
sanitize_json_schema(value);
}
}
JsonValue::Object(map) => {
if let Some(properties) = map.get_mut("properties")
&& let Some(properties_map) = properties.as_object_mut()
{
for value in properties_map.values_mut() {
sanitize_json_schema(value);
}
}
if let Some(items) = map.get_mut("items") {
sanitize_json_schema(items);
}
if let Some(additional_properties) = map.get_mut("additionalProperties")
&& !matches!(additional_properties, JsonValue::Bool(_))
{
sanitize_json_schema(additional_properties);
}
if let Some(value) = map.get_mut("prefixItems") {
sanitize_json_schema(value);
}
for key in COMPOSITION_SCHEMA_KEYS {
if let Some(value) = map.get_mut(key) {
sanitize_json_schema(value);
}
}
for table in DEFINITION_TABLE_KEYS {
sanitize_schema_table(map, table);
}
if let Some(const_value) = map.remove("const") {
map.insert("enum".to_string(), JsonValue::Array(vec![const_value]));
}
let mut schema_types = normalized_schema_types(map);
if schema_types.is_empty() && (map.contains_key("$ref") || has_composition_keyword(map))
{
return;
}
if schema_types.is_empty() {
if map.contains_key("properties")
|| map.contains_key("required")
|| map.contains_key("additionalProperties")
{
schema_types.push(JsonSchemaPrimitiveType::Object);
} else if map.contains_key("items") || map.contains_key("prefixItems") {
schema_types.push(JsonSchemaPrimitiveType::Array);
} else if map.contains_key("enum") || map.contains_key("format") {
schema_types.push(JsonSchemaPrimitiveType::String);
} else if map.contains_key("minimum")
|| map.contains_key("maximum")
|| map.contains_key("exclusiveMinimum")
|| map.contains_key("exclusiveMaximum")
|| map.contains_key("multipleOf")
{
schema_types.push(JsonSchemaPrimitiveType::Number);
} else {
map.clear();
return;
}
}
write_schema_types(map, &schema_types);
ensure_default_children_for_schema_types(map, &schema_types);
}
_ => {}
}
}
/// Sanitize a schema definition table before deserializing into `JsonSchema`.
///
/// Definition tables must be objects. Codex keeps valid definition tables and
/// recursively applies the same compatibility lowering used for inline schemas,
/// but drops malformed tables so `strict: false` tool registration degrades
/// gracefully instead of failing on an unreachable or invalid definition table.
fn sanitize_schema_table(map: &mut serde_json::Map<String, JsonValue>, key: &str) {
let should_remove = match map.get_mut(key) {
Some(JsonValue::Object(definitions)) => {
for definition in definitions.values_mut() {
sanitize_json_schema(definition);
}
false
}
Some(_) => true,
None => false,
};
if should_remove {
map.remove(key);
}
}
fn ensure_default_children_for_schema_types(
map: &mut serde_json::Map<String, JsonValue>,
schema_types: &[JsonSchemaPrimitiveType],
) {
if schema_types.contains(&JsonSchemaPrimitiveType::Object) && !map.contains_key("properties") {
map.insert(
"properties".to_string(),
JsonValue::Object(serde_json::Map::new()),
);
}
if schema_types.contains(&JsonSchemaPrimitiveType::Array) && !map.contains_key("items") {
map.insert("items".to_string(), json!({ "type": "string" }));
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct DefinitionPointer {
table: &'static str,
name: String,
}
/// Prune unused root definition entries to avoid sending tokens for definitions
/// the tool schema never references.
fn prune_unreachable_definitions(value: &mut JsonValue) {
let reachable = collect_reachable_definitions(value);
let JsonValue::Object(map) = value else {
return;
};
for table in DEFINITION_TABLE_KEYS {
prune_schema_table(map, table, &reachable);
}
}
fn prune_schema_table(
map: &mut serde_json::Map<String, JsonValue>,
table: &'static str,
reachable: &BTreeSet<DefinitionPointer>,
) {
let Some(JsonValue::Object(definitions)) = map.get_mut(table) else {
return;
};
definitions.retain(|name, _| {
reachable.contains(&DefinitionPointer {
table,
name: name.clone(),
})
});
if definitions.is_empty() {
map.remove(table);
}
}
fn collect_reachable_definitions(value: &JsonValue) -> BTreeSet<DefinitionPointer> {
let mut reachable = BTreeSet::new();
let mut pending = Vec::new();
collect_refs_outside_definitions(value, &mut pending);
while let Some(pointer) = pending.pop() {
if !reachable.insert(pointer.clone()) {
continue;
}
if let Some(definition) = definition_for_pointer(value, &pointer) {
collect_refs(definition, &mut pending);
}
}
reachable
}
fn collect_refs_outside_definitions(value: &JsonValue, refs: &mut Vec<DefinitionPointer>) {
match value {
JsonValue::Array(values) => {
for value in values {
collect_refs_outside_definitions(value, refs);
}
}
JsonValue::Object(map) => {
collect_ref_from_map(map, refs);
for_each_schema_child(map, DefinitionTraversal::Skip, &mut |value| {
collect_refs_outside_definitions(value, refs);
});
}
_ => {}
}
}
fn collect_refs(value: &JsonValue, refs: &mut Vec<DefinitionPointer>) {
match value {
JsonValue::Array(values) => {
for value in values {
collect_refs(value, refs);
}
}
JsonValue::Object(map) => {
collect_ref_from_map(map, refs);
for value in map.values() {
collect_refs(value, refs);
}
}
_ => {}
}
}
fn collect_ref_from_map(
map: &serde_json::Map<String, JsonValue>,
refs: &mut Vec<DefinitionPointer>,
) {
if let Some(JsonValue::String(schema_ref)) = map.get("$ref")
&& let Some(pointer) = parse_local_definition_ref(schema_ref)
{
refs.push(pointer);
}
}
fn definition_for_pointer<'a>(
value: &'a JsonValue,
pointer: &DefinitionPointer,
) -> Option<&'a JsonValue> {
let JsonValue::Object(map) = value else {
return None;
};
map.get(pointer.table)
.and_then(JsonValue::as_object)
.and_then(|definitions| definitions.get(&pointer.name))
}
fn parse_local_definition_ref(schema_ref: &str) -> Option<DefinitionPointer> {
let fragment = schema_ref.strip_prefix('#')?;
let pointer = urlencoding::decode(fragment).ok()?;
let pointer = jsonptr::Pointer::parse(pointer.as_ref()).ok()?;
let (table_token, pointer) = pointer.split_front()?;
let table = table_token.decoded();
let table = DEFINITION_TABLE_KEYS
.into_iter()
.find(|candidate| table.as_ref() == *candidate)?;
// Responses API non-strict mode accepts nested local refs such as
// `#/$defs/User/properties/name`, so keep the parent definition reachable.
let (name, _) = pointer.split_front()?;
Some(DefinitionPointer {
table,
name: name.decoded().into_owned(),
})
}
fn normalized_schema_types(
map: &serde_json::Map<String, JsonValue>,
) -> Vec<JsonSchemaPrimitiveType> {
let Some(schema_type) = map.get("type") else {
return Vec::new();
};
match schema_type {
JsonValue::String(schema_type) => schema_type_from_str(schema_type).into_iter().collect(),
JsonValue::Array(schema_types) => schema_types
.iter()
.filter_map(JsonValue::as_str)
.filter_map(schema_type_from_str)
.collect(),
_ => Vec::new(),
}
}
fn write_schema_types(
map: &mut serde_json::Map<String, JsonValue>,
schema_types: &[JsonSchemaPrimitiveType],
) {
match schema_types {
[] => {
map.remove("type");
}
[schema_type] => {
map.insert(
"type".to_string(),
JsonValue::String(schema_type_name(*schema_type).to_string()),
);
}
_ => {
map.insert(
"type".to_string(),
JsonValue::Array(
schema_types
.iter()
.map(|schema_type| {
JsonValue::String(schema_type_name(*schema_type).to_string())
})
.collect(),
),
);
}
}
}
fn schema_type_from_str(schema_type: &str) -> Option<JsonSchemaPrimitiveType> {
match schema_type {
"string" => Some(JsonSchemaPrimitiveType::String),
"number" => Some(JsonSchemaPrimitiveType::Number),
"boolean" => Some(JsonSchemaPrimitiveType::Boolean),
"integer" => Some(JsonSchemaPrimitiveType::Integer),
"object" => Some(JsonSchemaPrimitiveType::Object),
"array" => Some(JsonSchemaPrimitiveType::Array),
"null" => Some(JsonSchemaPrimitiveType::Null),
_ => None,
}
}
fn schema_type_name(schema_type: JsonSchemaPrimitiveType) -> &'static str {
match schema_type {
JsonSchemaPrimitiveType::String => "string",
JsonSchemaPrimitiveType::Number => "number",
JsonSchemaPrimitiveType::Boolean => "boolean",
JsonSchemaPrimitiveType::Integer => "integer",
JsonSchemaPrimitiveType::Object => "object",
JsonSchemaPrimitiveType::Array => "array",
JsonSchemaPrimitiveType::Null => "null",
}
}
fn singleton_null_schema_error() -> serde_json::Error {
serde_json::Error::io(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"tool input schema must not be a singleton null type",
))
}
#[cfg(test)]
#[path = "json_schema_tests.rs"]
mod tests;

View File

@@ -0,0 +1,164 @@
//! Apply the legacy best-effort size policy after schema sanitization and pruning.
//! Pass order and normalized-byte accounting are compatibility behavior.
use super::DEFINITION_TABLE_KEYS;
use super::JsonSchema;
use super::SCHEMA_CHILD_KEYS;
use super::has_composition_keyword;
use super::parse_local_definition_ref;
use super::traversal::DefinitionTraversal;
use super::traversal::for_each_schema_child_mut;
use serde_json::Value as JsonValue;
use serde_json::json;
// Measure compact normalized JSON in UTF-8 bytes.
pub(crate) const DEFAULT_COMPACT_TOOL_SCHEMA_BYTES: usize = 5_000;
const MAX_COMPACT_TOOL_SCHEMA_DEPTH: usize = 3;
/// Shrink unusually large tool schemas while preserving the top-level argument
/// surface. Compaction is best-effort rather than a hard cap: it runs only
/// after schema sanitization/pruning and applies increasingly lossy passes
/// while the schema remains over budget.
pub(super) fn compact_large_tool_schema(value: &mut JsonValue, max_bytes: usize) {
for pass in LARGE_SCHEMA_COMPACTION_PASSES {
if compact_schema_fits_budget(value, max_bytes) {
break;
}
pass(value);
}
}
type LargeSchemaCompactionPass = fn(&mut JsonValue);
const LARGE_SCHEMA_COMPACTION_PASSES: &[LargeSchemaCompactionPass] = &[
strip_schema_descriptions,
drop_schema_definitions,
collapse_deep_schema_objects_from_root,
prune_schema_compositions,
];
fn collapse_deep_schema_objects_from_root(value: &mut JsonValue) {
collapse_deep_schema_objects(value, /*depth*/ 0);
}
fn compact_schema_fits_budget(value: &JsonValue, max_bytes: usize) -> bool {
compact_normalized_schema_len(value) <= max_bytes
}
fn compact_normalized_schema_len(value: &JsonValue) -> usize {
serde_json::from_value::<JsonSchema>(value.clone())
.and_then(|schema| serde_json::to_vec(&schema))
.map(|json| json.len())
.unwrap_or(0)
}
fn strip_schema_descriptions(value: &mut JsonValue) {
match value {
JsonValue::Array(values) => {
for value in values {
strip_schema_descriptions(value);
}
}
JsonValue::Object(map) => {
map.remove("description");
for_each_schema_child_mut(map, DefinitionTraversal::Include, &mut |value| {
strip_schema_descriptions(value);
});
}
_ => {}
}
}
/// Replace local definition refs with empty schemas before dropping root
/// definition tables, so downstream behavior does not depend on how a schema
/// parser handles refs to missing definitions.
fn drop_schema_definitions(value: &mut JsonValue) {
rewrite_definition_refs_to_empty_schemas(value);
let JsonValue::Object(map) = value else {
return;
};
for key in DEFINITION_TABLE_KEYS {
map.remove(key);
}
}
fn rewrite_definition_refs_to_empty_schemas(value: &mut JsonValue) {
match value {
JsonValue::Array(values) => {
for value in values {
rewrite_definition_refs_to_empty_schemas(value);
}
}
JsonValue::Object(map) => {
if map
.get("$ref")
.and_then(JsonValue::as_str)
.and_then(parse_local_definition_ref)
.is_some()
{
*value = json!({});
return;
}
for_each_schema_child_mut(map, DefinitionTraversal::Skip, &mut |value| {
rewrite_definition_refs_to_empty_schemas(value);
});
}
_ => {}
}
}
fn collapse_deep_schema_objects(value: &mut JsonValue, depth: usize) {
match value {
JsonValue::Array(values) => {
for value in values {
collapse_deep_schema_objects(value, depth);
}
}
JsonValue::Object(map) => {
if depth >= MAX_COMPACT_TOOL_SCHEMA_DEPTH && is_complex_schema_object(map) {
*value = json!({});
return;
}
for_each_schema_child_mut(map, DefinitionTraversal::Skip, &mut |value| {
collapse_deep_schema_objects(value, depth + 1);
});
}
_ => {}
}
}
fn prune_schema_compositions(value: &mut JsonValue) {
match value {
JsonValue::Array(values) => {
for value in values {
prune_schema_compositions(value);
}
}
JsonValue::Object(map) => {
if has_composition_keyword(map) {
*value = json!({});
return;
}
for_each_schema_child_mut(map, DefinitionTraversal::Skip, &mut |value| {
prune_schema_compositions(value);
});
}
_ => {}
}
}
fn is_complex_schema_object(map: &serde_json::Map<String, JsonValue>) -> bool {
SCHEMA_CHILD_KEYS.iter().any(|key| map.contains_key(*key))
|| map.contains_key("properties")
|| map.contains_key("additionalProperties")
|| map.contains_key("$ref")
}
#[cfg(test)]
#[path = "compaction_tests.rs"]
mod tests;

View File

@@ -0,0 +1,127 @@
use pretty_assertions::assert_eq;
#[test]
fn collapse_deep_schema_objects_traverses_schema_children() {
let mut schema = serde_json::json!({
"type": "object",
"properties": {
"object_parent": {
"type": "object",
"properties": {
"complex": {
"type": "object",
"properties": {
"nested": {
"type": "object",
"properties": {
"leaf": { "type": "string" }
}
}
}
},
"scalar": {
"type": "string"
}
}
},
"array_parent": {
"type": "array",
"items": {
"type": "object",
"properties": {
"nested": {
"type": "object",
"properties": {
"leaf": { "type": "string" }
}
}
}
}
},
"map_parent": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"nested": {
"type": "object",
"properties": {
"leaf": { "type": "string" }
}
}
}
}
},
"union_parent": {
"anyOf": [
{
"type": "object",
"properties": {
"nested": {
"type": "object",
"properties": {
"leaf": { "type": "string" }
}
}
}
},
{ "type": "string" }
]
}
}
});
super::collapse_deep_schema_objects(&mut schema, /*depth*/ 0);
assert_eq!(
schema,
serde_json::json!({
"type": "object",
"properties": {
"object_parent": {
"type": "object",
"properties": {
"complex": {
"type": "object",
"properties": {
"nested": {}
}
},
"scalar": {
"type": "string"
}
}
},
"array_parent": {
"type": "array",
"items": {
"type": "object",
"properties": {
"nested": {}
}
}
},
"map_parent": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"nested": {}
}
}
},
"union_parent": {
"anyOf": [
{
"type": "object",
"properties": {
"nested": {}
}
},
{ "type": "string" }
]
}
}
})
);
}

View File

@@ -0,0 +1,87 @@
//! Visit schema-valued children while leaving enum values and other instance data untouched.
use super::DEFINITION_TABLE_KEYS;
use super::SCHEMA_CHILD_KEYS;
use serde_json::Value as JsonValue;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum DefinitionTraversal {
Include,
Skip,
}
pub(super) fn for_each_schema_child(
map: &serde_json::Map<String, JsonValue>,
definition_traversal: DefinitionTraversal,
visitor: &mut impl FnMut(&JsonValue),
) {
if let Some(properties) = map.get("properties")
&& let Some(properties_map) = properties.as_object()
{
for value in properties_map.values() {
visitor(value);
}
}
for key in SCHEMA_CHILD_KEYS {
if let Some(value) = map.get(key) {
visitor(value);
}
}
if let Some(additional_properties) = map.get("additionalProperties")
&& !matches!(additional_properties, JsonValue::Bool(_))
{
visitor(additional_properties);
}
if definition_traversal == DefinitionTraversal::Include {
for key in DEFINITION_TABLE_KEYS {
if let Some(definitions) = map.get(key)
&& let Some(definitions_map) = definitions.as_object()
{
for value in definitions_map.values() {
visitor(value);
}
}
}
}
}
pub(super) fn for_each_schema_child_mut(
map: &mut serde_json::Map<String, JsonValue>,
definition_traversal: DefinitionTraversal,
visitor: &mut impl FnMut(&mut JsonValue),
) {
if let Some(properties) = map.get_mut("properties")
&& let Some(properties_map) = properties.as_object_mut()
{
for value in properties_map.values_mut() {
visitor(value);
}
}
for key in SCHEMA_CHILD_KEYS {
if let Some(value) = map.get_mut(key) {
visitor(value);
}
}
if let Some(additional_properties) = map.get_mut("additionalProperties")
&& !matches!(additional_properties, JsonValue::Bool(_))
{
visitor(additional_properties);
}
if definition_traversal == DefinitionTraversal::Include {
for key in DEFINITION_TABLE_KEYS {
if let Some(definitions) = map.get_mut(key)
&& let Some(definitions_map) = definitions.as_object_mut()
{
for value in definitions_map.values_mut() {
visitor(value);
}
}
}
}
}

View File

@@ -0,0 +1,194 @@
//! Define serializable tool schema types and their constructors.
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
/// Primitive JSON Schema type names we support in tool definitions.
///
/// This mirrors the OpenAI Structured Outputs subset for JSON Schema `type`:
/// string, number, boolean, integer, object, array, and null.
/// Keywords such as `enum`, `const`, `anyOf`, `oneOf`, and `allOf` are modeled
/// separately.
/// See <https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas>.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum JsonSchemaPrimitiveType {
String,
Number,
Boolean,
Integer,
Object,
Array,
Null,
}
/// JSON Schema `type` supports either a single type name or a union of names.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(untagged)]
pub enum JsonSchemaType {
Single(JsonSchemaPrimitiveType),
Multiple(Box<[JsonSchemaPrimitiveType]>),
}
/// Generic JSON-Schema subset needed for our tool definitions.
///
/// Stored strings and sequences do not grow, so they do not retain spare capacity.
/// Optional maps are boxed because most schema nodes do not contain them.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct JsonSchema {
/// Explicit ordinary MCP server input schema limit; never sent as JSON Schema.
#[serde(skip)]
pub mcp_input_schema_max_bytes: Option<usize>,
#[serde(rename = "$ref", skip_serializing_if = "Option::is_none")]
pub schema_ref: Option<Box<str>>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub schema_type: Option<JsonSchemaType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<Box<str>>,
/// Responses-only marker for reviewed encrypted tool parameters.
#[serde(skip_serializing_if = "Option::is_none")]
pub encrypted: Option<bool>,
#[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
pub enum_values: Option<Box<[JsonValue]>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Box<JsonSchema>>,
#[serde(rename = "minItems", skip_serializing_if = "Option::is_none")]
pub min_items: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub properties: Option<Box<BTreeMap<String, JsonSchema>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub required: Option<Box<[String]>>,
#[serde(
rename = "additionalProperties",
skip_serializing_if = "Option::is_none"
)]
pub additional_properties: Option<AdditionalProperties>,
#[serde(rename = "anyOf", skip_serializing_if = "Option::is_none")]
pub any_of: Option<Box<[JsonSchema]>>,
#[serde(rename = "oneOf", skip_serializing_if = "Option::is_none")]
pub one_of: Option<Box<[JsonSchema]>>,
#[serde(rename = "allOf", skip_serializing_if = "Option::is_none")]
pub all_of: Option<Box<[JsonSchema]>>,
#[serde(rename = "$defs", skip_serializing_if = "Option::is_none")]
pub defs: Option<Box<BTreeMap<String, JsonSchema>>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub definitions: Option<Box<BTreeMap<String, JsonSchema>>>,
}
impl JsonSchema {
/// Construct a scalar/object/array schema with a single JSON Schema type.
fn typed(schema_type: JsonSchemaPrimitiveType, description: Option<String>) -> Self {
Self {
schema_type: Some(JsonSchemaType::Single(schema_type)),
description: description.map(String::into_boxed_str),
..Default::default()
}
}
pub fn any_of(variants: Vec<JsonSchema>, description: Option<String>) -> Self {
Self {
description: description.map(String::into_boxed_str),
any_of: Some(variants.into_boxed_slice()),
..Default::default()
}
}
pub fn one_of(variants: Vec<JsonSchema>, description: Option<String>) -> Self {
Self {
description: description.map(String::into_boxed_str),
one_of: Some(variants.into_boxed_slice()),
..Default::default()
}
}
pub fn all_of(variants: Vec<JsonSchema>, description: Option<String>) -> Self {
Self {
description: description.map(String::into_boxed_str),
all_of: Some(variants.into_boxed_slice()),
..Default::default()
}
}
pub fn boolean(description: Option<String>) -> Self {
Self::typed(JsonSchemaPrimitiveType::Boolean, description)
}
pub fn string(description: Option<String>) -> Self {
Self::typed(JsonSchemaPrimitiveType::String, description)
}
pub fn with_encrypted(mut self) -> Self {
self.encrypted = Some(true);
self
}
pub fn number(description: Option<String>) -> Self {
Self::typed(JsonSchemaPrimitiveType::Number, description)
}
pub fn integer(description: Option<String>) -> Self {
Self::typed(JsonSchemaPrimitiveType::Integer, description)
}
pub fn null(description: Option<String>) -> Self {
Self::typed(JsonSchemaPrimitiveType::Null, description)
}
pub fn string_enum(values: Vec<JsonValue>, description: Option<String>) -> Self {
Self {
schema_type: Some(JsonSchemaType::Single(JsonSchemaPrimitiveType::String)),
description: description.map(String::into_boxed_str),
enum_values: Some(values.into_boxed_slice()),
..Default::default()
}
}
pub fn array(items: JsonSchema, description: Option<String>) -> Self {
Self {
schema_type: Some(JsonSchemaType::Single(JsonSchemaPrimitiveType::Array)),
description: description.map(String::into_boxed_str),
items: Some(Box::new(items)),
..Default::default()
}
}
pub fn object(
properties: BTreeMap<String, JsonSchema>,
required: Option<Vec<String>>,
additional_properties: Option<AdditionalProperties>,
) -> Self {
Self {
schema_type: Some(JsonSchemaType::Single(JsonSchemaPrimitiveType::Object)),
properties: Some(Box::new(properties)),
required: required.map(Vec::into_boxed_slice),
additional_properties,
..Default::default()
}
}
}
/// Whether additional properties are allowed, and if so, any required schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum AdditionalProperties {
Boolean(bool),
Schema(Box<JsonSchema>),
}
impl From<bool> for AdditionalProperties {
fn from(value: bool) -> Self {
Self::Boolean(value)
}
}
impl From<JsonSchema> for AdditionalProperties {
fn from(value: JsonSchema) -> Self {
Self::Schema(Box::new(value))
}
}
#[cfg(test)]
#[path = "types_tests.rs"]
mod tests;

View File

@@ -0,0 +1,18 @@
//! Verify serialization of the supported tool schema representation.
use super::JsonSchema;
use pretty_assertions::assert_eq;
#[test]
fn json_schema_serializes_encrypted_marker() {
let schema = JsonSchema::string(Some("Secret value".to_string())).with_encrypted();
assert_eq!(
serde_json::to_value(schema).expect("serialize schema"),
serde_json::json!({
"type": "string",
"description": "Secret value",
"encrypted": true,
})
);
}

File diff suppressed because it is too large Load Diff

115
codex-rs/tools/src/lib.rs Normal file
View File

@@ -0,0 +1,115 @@
//! Shared tool definitions and Responses API tool primitives that can live
//! outside `codex-core`.
mod catalog_tool_message;
mod code_mode;
mod dynamic_tool;
mod function_call_error;
mod functions_namespace_function_prefixes;
mod image_detail;
mod indirect_namespace_prefixes;
mod json_schema;
mod mcp_tool;
mod output_schema;
mod request_plugin_install;
mod response_history;
mod responses_api;
mod tool_call;
mod tool_config;
mod tool_definition;
mod tool_discovery;
mod tool_executor;
mod tool_output;
mod tool_payload;
mod tool_search;
mod tool_spec;
pub use catalog_tool_message::with_catalog_tool_message;
pub use code_mode::augment_tool_spec_for_code_mode;
pub use code_mode::code_mode_name_for_tool_name;
pub use code_mode::collect_code_mode_exec_prompt_tool_definitions;
pub use code_mode::collect_code_mode_tool_definitions;
pub use code_mode::tool_spec_to_code_mode_tool_definition;
pub use codex_protocol::ToolName;
pub use dynamic_tool::parse_dynamic_tool;
pub use function_call_error::FunctionCallError;
pub use functions_namespace_function_prefixes::FunctionsNamespaceFunctionPrefixes;
pub use image_detail::can_request_original_image_detail;
pub use image_detail::normalize_output_image_detail;
pub use image_detail::sanitize_original_image_detail;
pub use indirect_namespace_prefixes::IndirectNamespacePrefixConflict;
pub use indirect_namespace_prefixes::IndirectNamespacePrefixes;
pub use json_schema::AdditionalProperties;
pub use json_schema::JsonSchema;
pub use json_schema::JsonSchemaPrimitiveType;
pub use json_schema::JsonSchemaType;
pub use json_schema::parse_catalog_tool_parameters;
pub use json_schema::parse_tool_input_schema;
pub use json_schema::parse_tool_input_schema_without_compaction;
pub use mcp_tool::mcp_call_tool_result_output_schema;
pub use mcp_tool::parse_agent_plugin_mcp_tool;
pub use mcp_tool::parse_mcp_tool;
pub use output_schema::ToolOutputSchema;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE;
pub use request_plugin_install::REQUEST_PLUGIN_INSTALL_PERSIST_KEY;
pub use request_plugin_install::RequestPluginInstallArgs;
pub use request_plugin_install::RequestPluginInstallMeta;
pub use request_plugin_install::RequestPluginInstallResult;
pub use request_plugin_install::all_requested_connectors_picked_up;
pub use request_plugin_install::build_request_plugin_install_elicitation_request;
pub use request_plugin_install::verified_connector_install_completed;
pub use response_history::retain_tail_from_last_n_user_messages;
pub use response_history::truncate_assistant_output_text_to_token_budget;
pub use responses_api::FreeformTool;
pub use responses_api::FreeformToolFormat;
pub use responses_api::LoadableToolSpec;
pub use responses_api::ResponsesApiNamespace;
pub use responses_api::ResponsesApiNamespaceTool;
pub use responses_api::ResponsesApiTool;
pub use responses_api::agent_plugin_mcp_tool_to_responses_api_tool;
pub use responses_api::coalesce_loadable_tool_specs;
pub use responses_api::default_namespace_description;
pub use responses_api::dynamic_tool_to_responses_api_tool;
pub use responses_api::mcp_tool_to_deferred_responses_api_tool;
pub use responses_api::mcp_tool_to_responses_api_tool;
pub use responses_api::tool_definition_to_responses_api_tool;
pub use tool_call::ConversationHistory;
pub use tool_call::ExtensionTurnItem;
pub use tool_call::NoopTurnItemEmitter;
pub use tool_call::ToolCall;
pub use tool_call::ToolCallSource;
pub use tool_call::ToolEnvironment;
pub use tool_call::TurnItemEmissionFuture;
pub use tool_call::TurnItemEmitter;
pub use tool_config::ToolEnvironmentMode;
pub use tool_config::request_user_input_available_modes;
pub use tool_definition::ToolDefinition;
pub use tool_discovery::DiscoverablePluginInfo;
pub use tool_discovery::DiscoverableTool;
pub use tool_discovery::DiscoverableToolAction;
pub use tool_discovery::DiscoverableToolType;
pub use tool_discovery::LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME;
pub use tool_discovery::ListAvailablePluginsToInstallResult;
pub use tool_discovery::REQUEST_PLUGIN_INSTALL_TOOL_NAME;
pub use tool_discovery::RequestPluginInstallEntry;
pub use tool_discovery::TOOL_SEARCH_DEFAULT_LIMIT;
pub use tool_discovery::TOOL_SEARCH_TOOL_NAME;
pub use tool_discovery::ToolSearchSourceInfo;
pub use tool_discovery::collect_request_plugin_install_entries;
pub use tool_discovery::filter_request_plugin_install_discoverable_tools_for_client;
pub use tool_executor::ToolExecutor;
pub use tool_executor::ToolExecutorFuture;
pub use tool_executor::ToolExposure;
pub use tool_executor::ToolExposures;
pub use tool_output::JsonToolOutput;
pub use tool_output::ToolOutput;
pub use tool_payload::ToolPayload;
pub use tool_search::ToolSearchEntry;
pub use tool_search::ToolSearchInfo;
pub use tool_spec::ResponsesApiWebSearchFilters;
pub use tool_spec::ResponsesApiWebSearchUserLocation;
pub use tool_spec::ToolSpec;
pub use tool_spec::create_tools_json_for_responses_api;
pub use tool_spec::create_tools_json_for_responses_lite;
pub use tool_spec::create_tools_raw_json_for_responses_api;

View File

@@ -0,0 +1,109 @@
use crate::ToolDefinition;
use crate::ToolOutputSchema;
use crate::json_schema::parse_tool_input_schema_with_max_bytes;
use crate::parse_tool_input_schema;
use codex_utils_string::take_bytes_at_char_boundary;
use serde_json::Value as JsonValue;
use serde_json::json;
const MAX_MCP_TOOL_DESCRIPTION_BYTES: usize = 1_000;
pub fn parse_mcp_tool(tool: &rmcp::model::Tool) -> Result<ToolDefinition, serde_json::Error> {
parse_mcp_tool_with_description_limit(
tool, /*description_limit*/ None, /*schema_max_bytes*/ None,
)
}
pub(crate) fn parse_mcp_tool_with_schema_max_bytes(
tool: &rmcp::model::Tool,
schema_max_bytes: usize,
) -> Result<ToolDefinition, serde_json::Error> {
parse_mcp_tool_with_description_limit(
tool,
/*description_limit*/ None,
Some(schema_max_bytes),
)
}
pub fn parse_agent_plugin_mcp_tool(
tool: &rmcp::model::Tool,
) -> Result<ToolDefinition, serde_json::Error> {
parse_mcp_tool_with_description_limit(
tool,
Some(MAX_MCP_TOOL_DESCRIPTION_BYTES),
/*schema_max_bytes*/ None,
)
}
fn parse_mcp_tool_with_description_limit(
tool: &rmcp::model::Tool,
description_limit: Option<usize>,
schema_max_bytes: Option<usize>,
) -> Result<ToolDefinition, serde_json::Error> {
let mut serialized_input_schema = serde_json::Value::Object(tool.input_schema.as_ref().clone());
// OpenAI models mandate the "properties" field in the schema. Some MCP
// servers omit it (or set it to null), so we insert an empty object to
// match the behavior of the Agents SDK.
if let serde_json::Value::Object(obj) = &mut serialized_input_schema
&& obj.get("properties").is_none_or(serde_json::Value::is_null)
{
obj.insert(
"properties".to_string(),
serde_json::Value::Object(serde_json::Map::new()),
);
}
let input_schema = if let Some(budget) = schema_max_bytes {
parse_tool_input_schema_with_max_bytes(&serialized_input_schema, budget)?
} else {
parse_tool_input_schema(&serialized_input_schema)?
};
Ok(ToolDefinition {
name: tool.name.to_string(),
description: tool
.description
.as_deref()
.map(|description| match description_limit {
Some(limit) => take_bytes_at_char_boundary(description, limit).to_string(),
None => description.to_string(),
})
.unwrap_or_default(),
input_schema,
output_schema: Some(ToolOutputSchema::from_mcp_output_schema(
tool.output_schema.clone(),
)),
defer_loading: false,
})
}
pub fn mcp_call_tool_result_output_schema(structured_content_schema: JsonValue) -> JsonValue {
let mut schema = json!({
"type": "object",
"properties": {
"content": {
"type": "array",
"items": {
"type": "object"
}
},
"structuredContent": null,
"isError": {
"type": "boolean"
},
"_meta": {
"type": "object"
}
},
"required": ["content"],
"additionalProperties": false
});
// Replacing the placeholder keeps the existing property order while moving
// the supplied schema instead of cloning it through json!.
schema["properties"]["structuredContent"] = structured_content_schema;
schema
}
#[cfg(test)]
#[path = "mcp_tool_tests.rs"]
mod tests;

View File

@@ -0,0 +1,189 @@
use super::mcp_call_tool_result_output_schema;
use super::parse_agent_plugin_mcp_tool;
use super::parse_mcp_tool;
use crate::JsonSchema;
use crate::ToolDefinition;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
fn mcp_tool(name: &str, description: &str, input_schema: serde_json::Value) -> rmcp::model::Tool {
rmcp::model::Tool::new(
name.to_string(),
description.to_string(),
std::sync::Arc::new(rmcp::model::object(input_schema)),
)
}
#[test]
fn mcp_schema_max_bytes_uses_the_utf8_compaction_threshold() {
let input_schema = serde_json::json!({
"type": "object",
"properties": {"query": {"type": "string", "description": "parameter guidance é ".repeat(400)}},
"required": ["query"],
"additionalProperties": false,
});
let tool = mcp_tool("search", "Search", input_schema.clone());
let schema_bytes = serde_json::to_vec(&input_schema)
.expect("schema JSON")
.len();
let compacted = super::parse_mcp_tool_with_schema_max_bytes(&tool, schema_bytes - 1)
.expect("argument types fit without descriptions");
let expanded = super::parse_mcp_tool_with_schema_max_bytes(&tool, schema_bytes)
.expect("parameter description fits");
let mut expected_compacted = input_schema.clone();
expected_compacted["properties"]["query"] = serde_json::json!({"type": "string"});
assert_eq!(
serde_json::to_value(compacted.input_schema).expect("schema"),
expected_compacted
);
assert_eq!(
serde_json::to_value(expanded.input_schema).expect("schema"),
input_schema
);
}
#[test]
fn parse_mcp_tool_inserts_empty_properties() {
let tool = mcp_tool(
"no_props",
"No properties",
serde_json::json!({
"type": "object"
}),
);
assert_eq!(
parse_mcp_tool(&tool).expect("parse MCP tool"),
ToolDefinition {
name: "no_props".to_string(),
description: "No properties".to_string(),
input_schema: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: Some(mcp_call_tool_result_output_schema(serde_json::json!({})).into()),
defer_loading: false,
}
);
}
#[test]
fn agent_plugin_mcp_tool_bounds_model_visible_description() {
let description = format!("{}é", "a".repeat(super::MAX_MCP_TOOL_DESCRIPTION_BYTES - 1));
let tool = mcp_tool(
"bounded_description",
&description,
serde_json::json!({"type": "object"}),
);
let parsed = parse_agent_plugin_mcp_tool(&tool).expect("parse Agent Plugin MCP tool");
assert_eq!(
parsed.description.len(),
super::MAX_MCP_TOOL_DESCRIPTION_BYTES - 1
);
}
#[test]
fn legacy_mcp_tool_preserves_long_description() {
let description = "a".repeat(super::MAX_MCP_TOOL_DESCRIPTION_BYTES + 100);
let tool = mcp_tool(
"legacy_description",
&description,
serde_json::json!({"type": "object"}),
);
assert_eq!(
parse_mcp_tool(&tool)
.expect("parse legacy MCP tool")
.description,
description
);
}
#[test]
fn parse_mcp_tool_preserves_top_level_output_schema() {
let mut tool = mcp_tool(
"with_output",
"Has output schema",
serde_json::json!({
"type": "object"
}),
);
tool.output_schema = Some(std::sync::Arc::new(rmcp::model::object(
serde_json::json!({
"properties": {
"result": {
"properties": {
"nested": {}
}
}
},
"required": ["result"]
}),
)));
assert_eq!(
parse_mcp_tool(&tool).expect("parse MCP tool"),
ToolDefinition {
name: "with_output".to_string(),
description: "Has output schema".to_string(),
input_schema: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: Some(
mcp_call_tool_result_output_schema(serde_json::json!({
"properties": {
"result": {
"properties": {
"nested": {}
}
}
},
"required": ["result"]
}))
.into()
),
defer_loading: false,
}
);
}
#[test]
fn parse_mcp_tool_preserves_output_schema_without_inferred_type() {
let mut tool = mcp_tool(
"with_enum_output",
"Has enum output schema",
serde_json::json!({
"type": "object"
}),
);
tool.output_schema = Some(std::sync::Arc::new(rmcp::model::object(
serde_json::json!({
"enum": ["ok", "error"]
}),
)));
assert_eq!(
parse_mcp_tool(&tool).expect("parse MCP tool"),
ToolDefinition {
name: "with_enum_output".to_string(),
description: "Has enum output schema".to_string(),
input_schema: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: Some(
mcp_call_tool_result_output_schema(serde_json::json!({
"enum": ["ok", "error"]
}))
.into()
),
defer_loading: false,
}
);
}

View File

@@ -0,0 +1,83 @@
//! Shares immutable output schema storage and materializes private JSON for consumers.
use crate::mcp_call_tool_result_output_schema;
use serde_json::Map;
use serde_json::Value;
use std::sync::Arc;
/// Immutable output schema that shares an MCP tool's structured result schema
/// until a consumer needs the complete call-result envelope.
#[derive(Debug, Clone)]
pub struct ToolOutputSchema(OutputSchemaStorage);
#[derive(Debug, Clone)]
enum OutputSchemaStorage {
Json(Arc<Value>),
McpCallToolResult(Option<Arc<Map<String, Value>>>),
}
impl ToolOutputSchema {
pub(crate) fn from_mcp_output_schema(
structured_content: Option<Arc<Map<String, Value>>>,
) -> Self {
Self(OutputSchemaStorage::McpCallToolResult(structured_content))
}
/// Materialize the schema for consumers that traverse JSON values.
pub fn to_value(&self) -> Value {
match &self.0 {
OutputSchemaStorage::Json(schema) => schema.as_ref().clone(),
OutputSchemaStorage::McpCallToolResult(structured_content) => {
mcp_call_tool_result_output_schema(Value::Object(
structured_content.as_deref().cloned().unwrap_or_default(),
))
}
}
}
/// Consume the schema, reusing uniquely owned JSON and cloning shared storage.
pub fn into_value(self) -> Value {
match self.0 {
OutputSchemaStorage::Json(schema) => Arc::unwrap_or_clone(schema),
OutputSchemaStorage::McpCallToolResult(structured_content) => {
mcp_call_tool_result_output_schema(Value::Object(
structured_content
.map(Arc::unwrap_or_clone)
.unwrap_or_default(),
))
}
}
}
}
impl From<Value> for ToolOutputSchema {
fn from(value: Value) -> Self {
Self(OutputSchemaStorage::Json(Arc::new(value)))
}
}
impl PartialEq for ToolOutputSchema {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(OutputSchemaStorage::Json(left), OutputSchemaStorage::Json(right)) => left == right,
(
OutputSchemaStorage::McpCallToolResult(left),
OutputSchemaStorage::McpCallToolResult(right),
) => match (left, right) {
(Some(left), Some(right)) => left == right,
(None, None) => true,
(Some(schema), None) | (None, Some(schema)) => schema.is_empty(),
},
(OutputSchemaStorage::Json(left), OutputSchemaStorage::McpCallToolResult(_)) => {
left.as_ref() == &other.to_value()
}
(OutputSchemaStorage::McpCallToolResult(_), OutputSchemaStorage::Json(right)) => {
&self.to_value() == right.as_ref()
}
}
}
}
#[cfg(test)]
#[path = "output_schema_tests.rs"]
mod tests;

View File

@@ -0,0 +1,69 @@
//! Verify materialization preserves schemas, isolates mutations, and respects equality.
use super::ToolOutputSchema;
use pretty_assertions::assert_eq;
use pretty_assertions::assert_ne;
use serde_json::Value;
use std::sync::Arc;
#[test]
fn materializing_mcp_output_preserves_json_and_keeps_mutations_private() {
let raw: serde_json::Map<String, Value> = serde_json::from_str(
r#"{"properties":{"z":{"enum":[9007199254740993,1.0]},"a":{"type":"string"}},"required":["z","a"]}"#,
)
.unwrap();
let raw = Arc::new(raw);
let schema = ToolOutputSchema::from_mcp_output_schema(Some(Arc::clone(&raw)));
let mut materialized = schema.to_value();
assert_eq!(
serde_json::to_string(&materialized["properties"]["structuredContent"]).unwrap(),
serde_json::to_string(&raw).unwrap(),
);
materialized["properties"]["structuredContent"] = Value::Null;
assert_eq!(
schema.to_value()["properties"]["structuredContent"],
Value::Object(raw.as_ref().clone()),
);
}
#[test]
fn materialized_and_lazy_schemas_compare_in_both_directions() {
let populated = serde_json::from_value(serde_json::json!({
"type": "object",
"properties": {"result": {"type": "string"}},
}))
.unwrap();
for structured_content in [None, Some(Arc::default()), Some(Arc::new(populated))] {
let lazy = ToolOutputSchema::from_mcp_output_schema(structured_content);
let materialized = ToolOutputSchema::from(lazy.to_value());
assert_eq!(materialized, lazy);
assert_eq!(lazy, materialized);
let mut different = lazy.to_value();
different["properties"]["structuredContent"] = serde_json::json!({"type": "null"});
let different = ToolOutputSchema::from(different);
assert_ne!(different, lazy);
assert_ne!(lazy, different);
assert_eq!(lazy.clone().into_value(), materialized.clone().into_value());
assert_eq!(lazy.into_value(), materialized.into_value());
}
}
#[test]
fn consuming_unique_json_schema_reuses_storage() {
let value = serde_json::json!({"description": "An output schema"});
let description_ptr = value["description"].as_str().unwrap().as_ptr();
let schema = ToolOutputSchema::from(value);
let value = schema.into_value();
assert_eq!(
value,
serde_json::json!({"description": "An output schema"})
);
assert_eq!(
value["description"].as_str().unwrap().as_ptr(),
description_ptr
);
}

View File

@@ -0,0 +1,124 @@
use codex_connectors::AppInfo;
use codex_protocol::approvals::ElicitationRequest;
use serde::Deserialize;
use serde::Serialize;
use serde_json::json;
use crate::DiscoverableTool;
use crate::DiscoverableToolAction;
use crate::DiscoverableToolType;
pub const REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE: &str = "tool_suggestion";
pub const REQUEST_PLUGIN_INSTALL_PERSIST_KEY: &str = "persist";
pub const REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE: &str = "always";
#[derive(Debug, Deserialize)]
pub struct RequestPluginInstallArgs {
pub tool_type: DiscoverableToolType,
pub action_type: DiscoverableToolAction,
pub tool_id: String,
pub suggest_reason: String,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct RequestPluginInstallResult {
pub completed: bool,
pub user_confirmed: bool,
pub tool_type: DiscoverableToolType,
pub action_type: DiscoverableToolAction,
pub tool_id: String,
pub tool_name: String,
pub suggest_reason: String,
}
#[derive(Debug, Serialize, PartialEq, Eq)]
pub struct RequestPluginInstallMeta<'a> {
pub codex_approval_kind: &'static str,
pub persist: &'static str,
pub tool_type: DiscoverableToolType,
pub suggest_type: DiscoverableToolAction,
pub suggest_reason: &'a str,
pub tool_id: &'a str,
pub tool_name: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pub suggestion_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub install_url: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub remote_plugin_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub app_connector_ids: Option<&'a [String]>,
}
pub fn build_request_plugin_install_elicitation_request(
suggest_reason: &str,
tool: &DiscoverableTool,
suggestion_id: &str,
) -> ElicitationRequest {
let message = suggest_reason.to_string();
ElicitationRequest::Form {
meta: Some(json!(build_request_plugin_install_meta(
suggest_reason,
tool,
suggestion_id,
))),
message,
requested_schema: json!({
"type": "object",
"properties": {},
}),
}
}
pub fn all_requested_connectors_picked_up(
expected_connector_ids: &[String],
accessible_connectors: &[AppInfo],
) -> bool {
expected_connector_ids.iter().all(|connector_id| {
verified_connector_install_completed(connector_id, accessible_connectors)
})
}
pub fn verified_connector_install_completed(
tool_id: &str,
accessible_connectors: &[AppInfo],
) -> bool {
accessible_connectors
.iter()
.find(|connector| connector.id == tool_id)
.is_some_and(|connector| connector.is_accessible)
}
fn build_request_plugin_install_meta<'a>(
suggest_reason: &'a str,
tool: &'a DiscoverableTool,
suggestion_id: &'a str,
) -> RequestPluginInstallMeta<'a> {
let (tool_type, suggestion_id, remote_plugin_id, app_connector_ids) = match tool {
DiscoverableTool::Connector(_) => (DiscoverableToolType::Connector, None, None, None),
DiscoverableTool::Plugin(plugin) => (
DiscoverableToolType::Plugin,
Some(suggestion_id),
plugin.remote_plugin_id.as_deref(),
Some(plugin.app_connector_ids.as_slice()),
),
};
RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type,
suggest_type: DiscoverableToolAction::Install,
suggest_reason,
tool_id: tool.id(),
tool_name: tool.name(),
suggestion_id,
install_url: tool.install_url(),
remote_plugin_id,
app_connector_ids,
}
}
#[cfg(test)]
#[path = "request_plugin_install_tests.rs"]
mod tests;

View File

@@ -0,0 +1,210 @@
use super::*;
use crate::DiscoverablePluginInfo;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn build_request_plugin_install_elicitation_request_uses_expected_shape() {
let connector = DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_2128aebfecb84f64a069897515042a44".to_string(),
name: "Google Calendar".to_string(),
description: Some("Plan events and schedules.".to_string()),
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some(
"https://chatgpt.com/apps/google-calendar/connector_2128aebfecb84f64a069897515042a44"
.to_string(),
),
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}));
let request = build_request_plugin_install_elicitation_request(
"Plan and reference events from your calendar",
&connector,
"request_plugin_install_connector-calendar",
);
assert_eq!(
request,
ElicitationRequest::Form {
meta: Some(json!(RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Connector,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Plan and reference events from your calendar",
tool_id: "connector_2128aebfecb84f64a069897515042a44",
tool_name: "Google Calendar",
suggestion_id: None,
install_url: Some(
"https://chatgpt.com/apps/google-calendar/connector_2128aebfecb84f64a069897515042a44"
),
remote_plugin_id: None,
app_connector_ids: None,
})),
message: "Plan and reference events from your calendar".to_string(),
requested_schema: json!({
"type": "object",
"properties": {},
}),
},
);
}
#[test]
fn build_request_plugin_install_elicitation_request_injects_plugin_metadata() {
let plugin = DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo {
id: "sample@openai-curated-remote".to_string(),
remote_plugin_id: Some("plugins~Plugin_sample".to_string()),
name: "Sample Plugin".to_string(),
description: Some("Includes skills, MCP servers, and apps.".to_string()),
has_skills: true,
mcp_server_names: vec!["sample-docs".to_string()],
app_connector_ids: vec!["connector_calendar".to_string()],
}));
let request = build_request_plugin_install_elicitation_request(
"Use the sample plugin's skills and MCP server",
&plugin,
"request_plugin_install_install-sample",
);
assert_eq!(
request,
ElicitationRequest::Form {
meta: Some(json!(RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Plugin,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Use the sample plugin's skills and MCP server",
tool_id: "sample@openai-curated-remote",
tool_name: "Sample Plugin",
suggestion_id: Some("request_plugin_install_install-sample"),
install_url: None,
remote_plugin_id: Some("plugins~Plugin_sample"),
app_connector_ids: Some(&["connector_calendar".to_string()]),
})),
message: "Use the sample plugin's skills and MCP server".to_string(),
requested_schema: json!({
"type": "object",
"properties": {},
}),
},
);
}
#[test]
fn build_request_plugin_install_meta_uses_expected_shape() {
let connector = DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_68df038e0ba48191908c8434991bbac2".to_string(),
name: "Gmail".to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some(
"https://chatgpt.com/apps/gmail/connector_68df038e0ba48191908c8434991bbac2".to_string(),
),
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}));
let meta = build_request_plugin_install_meta(
"Find and reference emails from your inbox",
&connector,
"request_plugin_install_connector-gmail",
);
assert_eq!(
meta,
RequestPluginInstallMeta {
codex_approval_kind: REQUEST_PLUGIN_INSTALL_APPROVAL_KIND_VALUE,
persist: REQUEST_PLUGIN_INSTALL_PERSIST_ALWAYS_VALUE,
tool_type: DiscoverableToolType::Connector,
suggest_type: DiscoverableToolAction::Install,
suggest_reason: "Find and reference emails from your inbox",
tool_id: "connector_68df038e0ba48191908c8434991bbac2",
tool_name: "Gmail",
suggestion_id: None,
install_url: Some(
"https://chatgpt.com/apps/gmail/connector_68df038e0ba48191908c8434991bbac2"
),
remote_plugin_id: None,
app_connector_ids: None,
},
);
}
#[test]
fn verified_connector_install_completed_requires_accessible_connector() {
let accessible_connectors = vec![AppInfo {
id: "calendar".to_string(),
name: "Google Calendar".to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: true,
is_enabled: false,
plugin_display_names: Vec::new(),
}];
assert!(verified_connector_install_completed(
"calendar",
&accessible_connectors,
));
assert!(!verified_connector_install_completed(
"gmail",
&accessible_connectors,
));
}
#[test]
fn all_requested_connectors_picked_up_requires_every_expected_connector() {
let accessible_connectors = vec![AppInfo {
id: "calendar".to_string(),
name: "Google Calendar".to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: true,
is_enabled: false,
plugin_display_names: Vec::new(),
}];
assert!(all_requested_connectors_picked_up(
&["calendar".to_string()],
&accessible_connectors,
));
assert!(!all_requested_connectors_picked_up(
&["calendar".to_string(), "gmail".to_string()],
&accessible_connectors,
));
}

View File

@@ -0,0 +1,154 @@
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_output_truncation::approx_token_count;
use codex_utils_output_truncation::truncate_text;
/// Retains items from the earliest of the last `user_message_count` user
/// messages through the latest user message.
pub fn retain_tail_from_last_n_user_messages(
items: &mut Vec<ResponseItem>,
user_message_count: usize,
) {
if user_message_count == 0 {
items.clear();
return;
}
let Some(latest_user_idx) = items.iter().rposition(ResponseItem::is_user_message) else {
items.clear();
return;
};
items.truncate(latest_user_idx + 1);
let earliest_retained_user_idx = items
.iter()
.enumerate()
.rev()
.filter(|(_, item)| item.is_user_message())
.take(user_message_count)
.last()
.map(|(idx, _)| idx)
.unwrap_or(latest_user_idx);
items.drain(..earliest_retained_user_idx);
}
/// Truncates assistant output text to a shared token budget across items.
pub fn truncate_assistant_output_text_to_token_budget(
items: &mut Vec<ResponseItem>,
max_tokens: usize,
) {
let mut remaining_budget = max_tokens;
items.retain_mut(|item| {
let ResponseItem::Message { role, content, .. } = item else {
return true;
};
if role != "assistant" {
return true;
}
content.retain_mut(|content_item| {
let ContentItem::OutputText { text, .. } = content_item else {
return true;
};
if remaining_budget == 0 {
return false;
}
let token_count = approx_token_count(text);
if token_count <= remaining_budget {
remaining_budget = remaining_budget.saturating_sub(token_count);
return true;
}
*text = truncate_text(text, TruncationPolicy::Tokens(remaining_budget));
remaining_budget = 0;
true
});
!content.is_empty()
});
}
#[cfg(test)]
mod tests {
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_output_truncation::truncate_text;
use pretty_assertions::assert_eq;
use super::retain_tail_from_last_n_user_messages;
use super::truncate_assistant_output_text_to_token_budget;
fn message(role: &str, text: &str) -> ResponseItem {
ResponseItem::Message {
status: None,
encrypted_content: None,
id: None,
role: role.to_string(),
content: vec![if role == "assistant" {
ContentItem::OutputText {
annotations: None,
logprobs: None,
text: text.to_string(),
}
} else {
ContentItem::InputText {
text: text.to_string(),
}
}],
phase: None,
internal_chat_message_metadata_passthrough: None,
}
}
#[test]
fn retains_tail_through_latest_user_message() {
let mut items = vec![
message("system", "system"),
message("user", "old user"),
message("assistant", "old assistant"),
message("user", "previous user"),
message("assistant", "previous assistant"),
message("user", "current user"),
message("assistant", "later assistant"),
];
retain_tail_from_last_n_user_messages(&mut items, /*user_message_count*/ 2);
assert_eq!(
items,
vec![
message("user", "previous user"),
message("assistant", "previous assistant"),
message("user", "current user"),
]
);
}
#[test]
fn truncates_assistant_output_text_across_items() {
let long_assistant = "a".repeat(16);
let mut items = vec![
message("user", "previous user"),
message("assistant", &long_assistant),
message("assistant", "after budget"),
message("user", "current user"),
];
truncate_assistant_output_text_to_token_budget(&mut items, /*max_tokens*/ 2);
assert_eq!(
items,
vec![
message("user", "previous user"),
message(
"assistant",
&truncate_text(&long_assistant, TruncationPolicy::Tokens(2)),
),
message("user", "current user"),
]
);
}
}

View File

@@ -0,0 +1,177 @@
use crate::JsonSchema;
use crate::ToolDefinition;
use crate::ToolName;
use crate::ToolOutputSchema;
use crate::mcp_tool::parse_mcp_tool_with_schema_max_bytes;
use crate::parse_agent_plugin_mcp_tool;
use crate::parse_dynamic_tool;
use crate::parse_mcp_tool;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
use serde::Deserialize;
use serde::Serialize;
const MAX_SERIALIZED_MCP_TOOL_BYTES: usize = 8_000;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FreeformTool {
pub name: String,
pub description: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub defer_loading: Option<bool>,
pub format: FreeformToolFormat,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FreeformToolFormat {
pub r#type: String,
pub syntax: String,
pub definition: String,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ResponsesApiTool {
pub name: String,
pub description: String,
/// TODO: Validation. When strict is set to true, the JSON schema,
/// `required` and `additional_properties` must be present. All fields in
/// `properties` must be present in `required`.
pub strict: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub defer_loading: Option<bool>,
pub parameters: JsonSchema,
#[serde(skip)]
pub output_schema: Option<ToolOutputSchema>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "type")]
#[allow(clippy::large_enum_variant)]
pub enum LoadableToolSpec {
#[allow(dead_code)]
#[serde(rename = "function")]
Function(ResponsesApiTool),
#[serde(rename = "namespace")]
Namespace(ResponsesApiNamespace),
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ResponsesApiNamespace {
pub name: String,
pub description: String,
pub tools: Vec<ResponsesApiNamespaceTool>,
}
pub fn default_namespace_description(namespace_name: &str) -> String {
if namespace_name == DEFAULT_FUNCTION_NAMESPACE {
String::new()
} else {
format!("Tools in the {namespace_name} namespace.")
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "type")]
#[allow(clippy::large_enum_variant)]
pub enum ResponsesApiNamespaceTool {
#[serde(rename = "function")]
Function(ResponsesApiTool),
#[serde(rename = "custom")]
Custom(FreeformTool),
}
pub fn dynamic_tool_to_responses_api_tool(
tool: &DynamicToolFunctionSpec,
) -> Result<ResponsesApiTool, serde_json::Error> {
Ok(tool_definition_to_responses_api_tool(parse_dynamic_tool(
tool,
)?))
}
pub fn coalesce_loadable_tool_specs(
specs: impl IntoIterator<Item = LoadableToolSpec>,
) -> Vec<LoadableToolSpec> {
let mut coalesced_specs = Vec::new();
for spec in specs {
match spec {
LoadableToolSpec::Function(tool) => {
coalesced_specs.push(LoadableToolSpec::Function(tool));
}
LoadableToolSpec::Namespace(mut namespace) => {
if let Some(existing_namespace) =
coalesced_specs.iter_mut().find_map(|spec| match spec {
LoadableToolSpec::Namespace(existing_namespace)
if existing_namespace.name == namespace.name =>
{
Some(existing_namespace)
}
LoadableToolSpec::Function(_) | LoadableToolSpec::Namespace(_) => None,
})
{
existing_namespace.tools.append(&mut namespace.tools);
} else {
coalesced_specs.push(LoadableToolSpec::Namespace(namespace));
}
}
}
}
coalesced_specs
}
pub fn mcp_tool_to_responses_api_tool(
tool_name: &ToolName,
tool: &rmcp::model::Tool,
schema_max_bytes: Option<usize>,
) -> Result<ResponsesApiTool, serde_json::Error> {
let definition = match schema_max_bytes {
Some(max_bytes) => parse_mcp_tool_with_schema_max_bytes(tool, max_bytes)?,
None => parse_mcp_tool(tool)?,
};
let mut tool =
tool_definition_to_responses_api_tool(definition.renamed(tool_name.name.clone()));
tool.parameters.mcp_input_schema_max_bytes = schema_max_bytes;
Ok(tool)
}
pub fn agent_plugin_mcp_tool_to_responses_api_tool(
tool_name: &ToolName,
tool: &rmcp::model::Tool,
) -> Result<ResponsesApiTool, serde_json::Error> {
let mut tool = tool_definition_to_responses_api_tool(
parse_agent_plugin_mcp_tool(tool)?.renamed(tool_name.name.clone()),
);
if serde_json::to_vec(&tool)?.len() > MAX_SERIALIZED_MCP_TOOL_BYTES {
tool.parameters = JsonSchema::object(
Default::default(),
/*required*/ None,
Some(true.into()),
);
}
Ok(tool)
}
pub fn mcp_tool_to_deferred_responses_api_tool(
tool_name: &ToolName,
tool: &rmcp::model::Tool,
) -> Result<ResponsesApiTool, serde_json::Error> {
Ok(tool_definition_to_responses_api_tool(
parse_mcp_tool(tool)?
.renamed(tool_name.name.clone())
.into_deferred(),
))
}
pub fn tool_definition_to_responses_api_tool(tool_definition: ToolDefinition) -> ResponsesApiTool {
ResponsesApiTool {
name: tool_definition.name,
description: tool_definition.description,
strict: false,
defer_loading: tool_definition.defer_loading.then_some(true),
parameters: tool_definition.input_schema,
output_schema: tool_definition.output_schema,
}
}
#[cfg(test)]
#[path = "responses_api_tests.rs"]
mod tests;

View File

@@ -0,0 +1,261 @@
use super::FreeformTool;
use super::LoadableToolSpec;
use super::ResponsesApiNamespace;
use super::ResponsesApiNamespaceTool;
use super::ResponsesApiTool;
use super::agent_plugin_mcp_tool_to_responses_api_tool;
use super::dynamic_tool_to_responses_api_tool;
use super::mcp_tool_to_deferred_responses_api_tool;
use super::tool_definition_to_responses_api_tool;
use crate::JsonSchema;
use crate::ToolDefinition;
use crate::ToolName;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
#[test]
fn freeform_tool_deferral_matches_function_tool_wire_shape() {
let mut expected_wire_shape = json!({
"name": "apply_patch",
"description": "Apply a patch",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": "start: \"patch\"",
},
});
let mut tool: FreeformTool = serde_json::from_value(expected_wire_shape.clone())
.expect("deserialize legacy freeform tool");
assert_eq!(tool.defer_loading, None);
assert_eq!(
serde_json::to_value(&tool).expect("serialize eager freeform tool"),
expected_wire_shape
);
tool.defer_loading = Some(true);
expected_wire_shape["defer_loading"] = json!(true);
assert_eq!(
serde_json::to_value(tool).expect("serialize deferred freeform tool"),
expected_wire_shape
);
}
#[test]
fn tool_definition_to_responses_api_tool_omits_false_defer_loading() {
assert_eq!(
tool_definition_to_responses_api_tool(ToolDefinition {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
input_schema: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(false.into())
),
output_schema: Some(json!({"type": "object"}).into()),
defer_loading: false,
}),
ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(false.into())
),
output_schema: Some(json!({"type": "object"}).into()),
}
);
}
#[test]
fn dynamic_tool_to_responses_api_tool_preserves_defer_loading() {
let tool = DynamicToolFunctionSpec {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
input_schema: json!({
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"],
"additionalProperties": false,
}),
defer_loading: true,
};
assert_eq!(
dynamic_tool_to_responses_api_tool(&tool).expect("convert dynamic tool"),
ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: Some(true),
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(false.into())
),
output_schema: None,
}
);
}
#[test]
fn mcp_tool_to_deferred_responses_api_tool_sets_defer_loading() {
let tool = rmcp::model::Tool::new(
"lookup_order",
"Look up an order",
std::sync::Arc::new(rmcp::model::object(json!({
"type": "object",
"properties": {
"order_id": {"type": "string"}
},
"required": ["order_id"],
"additionalProperties": false,
}))),
);
assert_eq!(
mcp_tool_to_deferred_responses_api_tool(
&ToolName::namespaced("mcp__codex_apps__", "lookup_order"),
&tool,
)
.expect("convert deferred tool"),
ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: Some(true),
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
Some(vec!["order_id".to_string()]),
Some(false.into())
),
output_schema: None,
}
);
}
#[test]
fn agent_plugin_mcp_tool_uses_fallback_for_oversized_schema() {
let properties: serde_json::Map<String, serde_json::Value> = (0..1_024)
.map(|index| (format!("property_{index}"), json!({"type": "string"})))
.collect();
let tool = rmcp::model::Tool::new(
"oversized",
"Large schema",
std::sync::Arc::new(rmcp::model::object(json!({
"type": "object",
"properties": properties,
}))),
);
assert_eq!(
agent_plugin_mcp_tool_to_responses_api_tool(&ToolName::from("oversized"), &tool)
.expect("Agent Plugin MCP tool should use a fallback schema")
.parameters,
JsonSchema::object(BTreeMap::new(), /*required*/ None, Some(true.into()))
);
}
#[test]
fn legacy_mcp_tool_accepts_oversized_schema() {
let properties: serde_json::Map<String, serde_json::Value> = (0..1_024)
.map(|index| (format!("property_{index}"), json!({"type": "string"})))
.collect();
let tool = rmcp::model::Tool::new(
"oversized",
"Large legacy schema",
std::sync::Arc::new(rmcp::model::object(json!({
"type": "object",
"properties": properties,
}))),
);
let schema_bytes = serde_json::to_vec(tool.input_schema.as_ref())
.expect("MCP input schema JSON")
.len();
assert!(schema_bytes > codex_code_mode::DEFAULT_INPUT_SCHEMA_MAX_BYTES);
for (server_limit, expected_limit, expected_type) in [
(
None,
codex_code_mode::DEFAULT_INPUT_SCHEMA_MAX_BYTES,
"args: unknown",
),
(Some(schema_bytes), schema_bytes, "property_1023?: string;"),
] {
let tool = super::mcp_tool_to_responses_api_tool(
&ToolName::from("oversized"),
&tool,
server_limit,
)
.expect("legacy MCP conversion must preserve existing acceptance");
let definition =
crate::tool_spec_to_code_mode_tool_definition(&crate::ToolSpec::Function(tool))
.expect("Code Mode tool");
assert_eq!(definition.input_schema_max_bytes, Some(expected_limit));
assert!(definition.description.contains(expected_type));
}
}
#[test]
fn loadable_tool_spec_namespace_serializes_with_deferred_child_tools() {
let namespace = LoadableToolSpec::Namespace(ResponsesApiNamespace {
name: "mcp__codex_apps__calendar".to_string(),
description: "Plan events".to_string(),
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
name: "create_event".to_string(),
description: "Create a calendar event.".to_string(),
strict: false,
defer_loading: Some(true),
parameters: JsonSchema::object(
Default::default(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: None,
})],
});
let value = serde_json::to_value(namespace).expect("serialize namespace");
assert_eq!(
value,
json!({
"type": "namespace",
"name": "mcp__codex_apps__calendar",
"description": "Plan events",
"tools": [
{
"type": "function",
"name": "create_event",
"description": "Create a calendar event.",
"strict": false,
"defer_loading": true,
"parameters": {
"type": "object",
"properties": {}
}
}
]
})
);
}

View File

@@ -0,0 +1,213 @@
use crate::FunctionCallError;
use crate::ToolName;
use crate::ToolPayload;
use codex_attachment_store::AttachmentStore;
use codex_extension_items::ExtensionItem;
use codex_file_system::EnvironmentAccess;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::EventMsg;
use codex_utils_output_truncation::TruncationPolicy;
use codex_utils_output_truncation::with_serialization_allowance;
use codex_utils_path_uri::PathUri;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::LazyLock;
/// Raw response history snapshot available when an extension tool is invoked.
#[derive(Clone)]
pub struct ConversationHistory {
items: Arc<LazyLock<Box<[ResponseItem]>, HistoryLoader>>,
}
type HistoryLoader = Box<dyn FnOnce() -> Box<[ResponseItem]> + Send + Sync>;
impl ConversationHistory {
pub fn new(items: Vec<ResponseItem>) -> Self {
Self::new_deferred(move || items)
}
/// Materializes an invocation-time snapshot only when a tool reads its history.
/// The loader must capture that snapshot rather than querying mutable session state.
pub fn new_deferred(load: impl FnOnce() -> Vec<ResponseItem> + Send + Sync + 'static) -> Self {
Self {
items: Arc::new(LazyLock::new(Box::new(move || load().into_boxed_slice()))),
}
}
pub fn items(&self) -> &[ResponseItem] {
&self.items
}
}
impl Default for ConversationHistory {
fn default() -> Self {
Self::new(Vec::new())
}
}
impl fmt::Debug for ConversationHistory {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ConversationHistory")
.finish_non_exhaustive()
}
}
/// Future returned when an extension tool emits a visible turn-item lifecycle event.
pub type TurnItemEmissionFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
/// Visible turn items that an extension may publish into the host lifecycle.
#[derive(Clone, Debug)]
pub struct ExtensionTurnItem {
/// Canonical extension item plus compatibility events derived by its owner.
///
/// Core intentionally does not inspect extension-owned payloads, so it
/// cannot derive their legacy fanout. It emits the canonical lifecycle
/// event first, then these extension-provided events. Core also skips
/// global turn-item contributors here so extensions cannot mutate items
/// owned by other extensions.
pub item: ExtensionItem,
pub legacy_events: Vec<EventMsg>,
}
/// Host-provided capability for extension tools to emit visible turn items.
///
/// Implementations route lifecycle events through the host's normal item event
/// pipeline and client delivery.
pub trait TurnItemEmitter: Send + Sync {
/// Emits the beginning of one visible turn item.
fn emit_started<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a>;
/// Emits one completed visible turn item.
fn emit_completed<'a>(&'a self, item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a>;
}
/// Callback-scoped view of a turn environment for extension tools.
///
/// The host retains its runtime and configuration, and supplies access with this callback's
/// grants already applied. Borrowing the accessor prevents retaining it for a later callback.
#[derive(Clone)]
pub struct ToolEnvironment<'call> {
/// Stable host environment id used to route executor-scoped capabilities.
pub environment_id: String,
/// Effective working directory for this turn in the environment.
pub cwd: PathUri,
file_system: &'call dyn EnvironmentAccess,
}
impl<'call> ToolEnvironment<'call> {
pub fn new(
environment_id: String,
cwd: PathUri,
file_system: &'call dyn EnvironmentAccess,
) -> Self {
Self {
environment_id,
cwd,
file_system,
}
}
/// Borrows filesystem access with the permissions captured for this callback.
pub fn fs(&self) -> &dyn EnvironmentAccess {
self.file_system
}
}
/// Turn-item emitter used when a caller does not expose visible item emission.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopTurnItemEmitter;
impl TurnItemEmitter for NoopTurnItemEmitter {
fn emit_started<'a>(&'a self, _item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> {
Box::pin(std::future::ready(()))
}
fn emit_completed<'a>(&'a self, _item: ExtensionTurnItem) -> TurnItemEmissionFuture<'a> {
Box::pin(std::future::ready(()))
}
}
/// Host-visible source for a model tool call.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ToolCallSource {
/// The model invoked the tool directly.
Direct,
/// Code mode invoked the tool while executing a runtime cell.
CodeMode {
/// Runtime cell that issued the nested tool request.
cell_id: String,
/// Code-mode's per-cell tool invocation id.
runtime_tool_call_id: String,
},
}
#[derive(Clone)]
pub struct ToolCall<'call> {
pub turn_id: String,
pub call_id: String,
pub tool_name: ToolName,
pub model: String,
pub codex_turn_metadata: Option<String>,
pub truncation_policy: TruncationPolicy,
pub source: ToolCallSource,
pub conversation_history: ConversationHistory,
pub turn_item_emitter: Arc<dyn TurnItemEmitter>,
pub attachment_store: Arc<dyn AttachmentStore>,
pub ephemeral: bool,
pub environments: Vec<ToolEnvironment<'call>>,
pub payload: ToolPayload,
}
impl std::fmt::Debug for ToolCall<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ToolCall")
.field("turn_id", &self.turn_id)
.field("call_id", &self.call_id)
.field("tool_name", &self.tool_name)
.field("model", &self.model)
.field(
"has_codex_turn_metadata",
&self.codex_turn_metadata.is_some(),
)
.field("truncation_policy", &self.truncation_policy)
.field("source", &self.source)
.field("conversation_history", &self.conversation_history)
.field("turn_item_emitter", &"<host turn item emitter>")
.field("attachment_store", &"<host attachment store>")
.field("ephemeral", &self.ephemeral)
.field("environment_count", &self.environments.len())
.field("payload", &self.payload)
.finish()
}
}
impl ToolCall<'_> {
/// Returns the response-content budget, bounded by the tool's own size limit.
///
/// Direct calls use the host's effective text-output allowance. Code Mode receives
/// typed results without that truncation, so only the tool's limit applies.
/// Callers must include serialization overhead when fitting a response to this budget.
pub fn response_byte_budget(&self, max_response_bytes: usize) -> usize {
match &self.source {
ToolCallSource::Direct => max_response_bytes
.min(with_serialization_allowance(self.truncation_policy).byte_budget()),
ToolCallSource::CodeMode {
cell_id: _,
runtime_tool_call_id: _,
} => max_response_bytes,
}
}
pub fn function_arguments(&self) -> Result<&str, FunctionCallError> {
match &self.payload {
ToolPayload::Function { arguments } => Ok(arguments),
_ => Err(FunctionCallError::Fatal(format!(
"tool {} invoked with incompatible payload",
self.tool_name
))),
}
}
}

View File

@@ -0,0 +1,40 @@
use codex_features::Feature;
use codex_features::Features;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::TUI_VISIBLE_COLLABORATION_MODES;
pub fn request_user_input_available_modes(features: &Features) -> Vec<ModeKind> {
TUI_VISIBLE_COLLABORATION_MODES
.into_iter()
.filter(|mode| {
mode.allows_request_user_input()
|| (features.enabled(Feature::DefaultModeRequestUserInput)
&& *mode == ModeKind::Default)
})
.collect()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolEnvironmentMode {
None,
Single,
Multiple,
}
impl ToolEnvironmentMode {
pub fn from_count(count: usize) -> Self {
match count {
0 => Self::None,
1 => Self::Single,
_ => Self::Multiple,
}
}
pub fn has_environment(self) -> bool {
!matches!(self, Self::None)
}
}
#[cfg(test)]
#[path = "tool_config_tests.rs"]
mod tests;

View File

@@ -0,0 +1,22 @@
use codex_features::Feature;
use codex_features::Features;
use codex_protocol::config_types::ModeKind;
use pretty_assertions::assert_eq;
use super::*;
#[test]
fn request_user_input_modes_follow_default_mode_feature() {
let mut features = Features::with_defaults();
features.disable(Feature::DefaultModeRequestUserInput);
assert_eq!(
request_user_input_available_modes(&features),
vec![ModeKind::Plan]
);
features.enable(Feature::DefaultModeRequestUserInput);
assert_eq!(
request_user_input_available_modes(&features),
vec![ModeKind::Default, ModeKind::Plan]
);
}

View File

@@ -0,0 +1,30 @@
use crate::JsonSchema;
use crate::ToolOutputSchema;
/// Tool metadata and schemas that downstream crates can adapt into higher-level
/// tool specs.
#[derive(Debug, PartialEq)]
pub struct ToolDefinition {
pub name: String,
pub description: String,
pub input_schema: JsonSchema,
pub output_schema: Option<ToolOutputSchema>,
pub defer_loading: bool,
}
impl ToolDefinition {
pub fn renamed(mut self, name: String) -> Self {
self.name = name;
self
}
pub fn into_deferred(mut self) -> Self {
self.output_schema = None;
self.defer_loading = true;
self
}
}
#[cfg(test)]
#[path = "tool_definition_tests.rs"]
mod tests;

View File

@@ -0,0 +1,46 @@
use super::ToolDefinition;
use crate::JsonSchema;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
fn tool_definition() -> ToolDefinition {
ToolDefinition {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
input_schema: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: Some(
serde_json::json!({
"type": "object",
})
.into(),
),
defer_loading: false,
}
}
#[test]
fn renamed_overrides_name_only() {
assert_eq!(
tool_definition().renamed("mcp__orders__lookup_order".to_string()),
ToolDefinition {
name: "mcp__orders__lookup_order".to_string(),
..tool_definition()
}
);
}
#[test]
fn into_deferred_drops_output_schema_and_sets_defer_loading() {
assert_eq!(
tool_definition().into_deferred(),
ToolDefinition {
output_schema: None,
defer_loading: true,
..tool_definition()
}
);
}

View File

@@ -0,0 +1,150 @@
use codex_connectors::AppInfo;
use serde::Deserialize;
use serde::Serialize;
const TUI_CLIENT_NAME: &str = "codex-tui";
pub const TOOL_SEARCH_TOOL_NAME: &str = "tool_search";
pub const TOOL_SEARCH_DEFAULT_LIMIT: usize = 8;
pub const LIST_AVAILABLE_PLUGINS_TO_INSTALL_TOOL_NAME: &str = "list_available_plugins_to_install";
pub const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ToolSearchSourceInfo {
pub name: String,
pub description: Option<String>,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DiscoverableToolType {
Connector,
Plugin,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum DiscoverableToolAction {
Install,
Enable,
}
#[derive(Clone, Debug, PartialEq)]
pub enum DiscoverableTool {
Connector(Box<AppInfo>),
Plugin(Box<DiscoverablePluginInfo>),
}
impl DiscoverableTool {
pub fn tool_type(&self) -> DiscoverableToolType {
match self {
Self::Connector(_) => DiscoverableToolType::Connector,
Self::Plugin(_) => DiscoverableToolType::Plugin,
}
}
pub fn id(&self) -> &str {
match self {
Self::Connector(connector) => connector.id.as_str(),
Self::Plugin(plugin) => plugin.id.as_str(),
}
}
pub fn name(&self) -> &str {
match self {
Self::Connector(connector) => connector.name.as_str(),
Self::Plugin(plugin) => plugin.name.as_str(),
}
}
pub fn install_url(&self) -> Option<&str> {
match self {
Self::Connector(connector) => connector.install_url.as_deref(),
Self::Plugin(_) => None,
}
}
}
impl From<AppInfo> for DiscoverableTool {
fn from(value: AppInfo) -> Self {
Self::Connector(Box::new(value))
}
}
impl From<DiscoverablePluginInfo> for DiscoverableTool {
fn from(value: DiscoverablePluginInfo) -> Self {
Self::Plugin(Box::new(value))
}
}
pub fn filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools: Vec<DiscoverableTool>,
app_server_client_name: Option<&str>,
) -> Vec<DiscoverableTool> {
if app_server_client_name != Some(TUI_CLIENT_NAME) {
return discoverable_tools;
}
discoverable_tools
.into_iter()
.filter(|tool| !matches!(tool, DiscoverableTool::Plugin(_)))
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DiscoverablePluginInfo {
pub id: String,
pub remote_plugin_id: Option<String>,
pub name: String,
pub description: Option<String>,
pub has_skills: bool,
pub mcp_server_names: Vec<String>,
pub app_connector_ids: Vec<String>,
}
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct RequestPluginInstallEntry {
pub id: String,
pub name: String,
pub description: Option<String>,
pub tool_type: DiscoverableToolType,
pub has_skills: bool,
pub mcp_server_names: Vec<String>,
pub app_connector_ids: Vec<String>,
}
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct ListAvailablePluginsToInstallResult {
pub tools: Vec<RequestPluginInstallEntry>,
}
pub fn collect_request_plugin_install_entries(
discoverable_tools: &[DiscoverableTool],
) -> Vec<RequestPluginInstallEntry> {
discoverable_tools
.iter()
.map(|tool| match tool {
DiscoverableTool::Connector(connector) => RequestPluginInstallEntry {
id: connector.id.clone(),
name: connector.name.clone(),
description: connector.description.clone(),
tool_type: DiscoverableToolType::Connector,
has_skills: false,
mcp_server_names: Vec::new(),
app_connector_ids: Vec::new(),
},
DiscoverableTool::Plugin(plugin) => RequestPluginInstallEntry {
id: plugin.id.clone(),
name: plugin.name.clone(),
description: plugin.description.clone(),
tool_type: DiscoverableToolType::Plugin,
has_skills: plugin.has_skills,
mcp_server_names: plugin.mcp_server_names.clone(),
app_connector_ids: plugin.app_connector_ids.clone(),
},
})
.collect()
}
#[cfg(test)]
#[path = "tool_discovery_tests.rs"]
mod tests;

View File

@@ -0,0 +1,74 @@
use super::*;
use codex_connectors::AppInfo;
use pretty_assertions::assert_eq;
use serde_json::json;
#[test]
fn discoverable_tool_enums_use_expected_wire_names() {
assert_eq!(
json!({
"tool_type": DiscoverableToolType::Connector,
"action_type": DiscoverableToolAction::Install,
}),
json!({
"tool_type": "connector",
"action_type": "install",
})
);
}
#[test]
fn filter_request_plugin_install_discoverable_tools_for_codex_tui_omits_plugins() {
let discoverable_tools = vec![
DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_google_calendar".to_string(),
name: "Google Calendar".to_string(),
description: Some("Plan events and schedules.".to_string()),
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some("https://example.test/google-calendar".to_string()),
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
})),
DiscoverableTool::Plugin(Box::new(DiscoverablePluginInfo {
id: "slack@openai-curated".to_string(),
remote_plugin_id: None,
name: "Slack".to_string(),
description: Some("Search Slack messages".to_string()),
has_skills: true,
mcp_server_names: vec!["slack".to_string()],
app_connector_ids: vec!["connector_slack".to_string()],
})),
];
assert_eq!(
filter_request_plugin_install_discoverable_tools_for_client(
discoverable_tools,
Some("codex-tui"),
),
vec![DiscoverableTool::Connector(Box::new(AppInfo {
id: "connector_google_calendar".to_string(),
name: "Google Calendar".to_string(),
description: Some("Plan events and schedules.".to_string()),
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: Some("https://example.test/google-calendar".to_string()),
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}))]
);
}

View File

@@ -0,0 +1,139 @@
use crate::FunctionCallError;
use crate::ToolName;
use crate::ToolOutput;
use crate::ToolSearchInfo;
use crate::ToolSpec;
use codex_protocol::config_types::ToolExposureSurface;
use std::future::Future;
use std::pin::Pin;
/// The boxed future returned by [`ToolExecutor::handle`].
pub type ToolExecutorFuture<'a> =
Pin<Box<dyn Future<Output = Result<Box<dyn ToolOutput>, FunctionCallError>> + Send + 'a>>;
bitflags::bitflags! {
/// Independent model-facing surfaces supported by a tool.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ToolExposures: u8 {
/// Keep the tool registered without making it model-visible.
const NONE = 0;
/// Include the tool in the initial model-visible tool list.
const DIRECT = 0b001;
/// Make the tool discoverable through tool search.
const DEFERRED = 0b010;
/// Make the tool callable from nested Code Mode scripts.
const CODE_MODE = 0b100;
/// Permit every supported model-facing surface.
const ALL = Self::DIRECT.bits() | Self::DEFERRED.bits() | Self::CODE_MODE.bits();
}
}
impl From<ToolExposureSurface> for ToolExposures {
fn from(surface: ToolExposureSurface) -> Self {
match surface {
ToolExposureSurface::CodeMode => Self::CODE_MODE,
ToolExposureSurface::Deferred => Self::DEFERRED,
ToolExposureSurface::Direct => Self::DIRECT,
}
}
}
impl FromIterator<ToolExposureSurface> for ToolExposures {
fn from_iter<T: IntoIterator<Item = ToolExposureSurface>>(surfaces: T) -> Self {
surfaces
.into_iter()
.fold(Self::NONE, |exposures, surface| exposures | surface.into())
}
}
/// Controls where a tool is exposed to the model.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ToolExposure {
/// Include this tool in the initial model-visible tool list.
///
/// When code mode is enabled, this tool is also available as a nested
/// code-mode tool.
Direct,
/// Register this tool for later discovery, but omit it from the initial
/// model-visible tool list. Deferred tools must provide search metadata via
/// [`ToolExecutor::search_info`]. The default implementation derives
/// metadata from function and namespace specs.
Deferred,
/// Make this tool discoverable through tool search without allowing nested
/// Code Mode calls.
DeferredModelOnly,
/// Include this tool in the initial model-visible tool list only.
///
/// In code-mode-only sessions, this keeps the tool callable as a normal
/// model tool while excluding it from the nested code-mode tool surface.
DirectModelOnly,
/// Expose this tool only to nested Code Mode calls, without including it in
/// the initial model-visible tool list or making it available to tool search.
CodeModeOnly,
/// Keep this tool registered for dispatch without exposing it to the model.
Hidden,
}
impl ToolExposure {
pub fn is_direct(self) -> bool {
matches!(self, Self::Direct | Self::DirectModelOnly)
}
/// Returns whether this tool can be discovered through tool search.
pub fn is_deferred(self) -> bool {
matches!(self, Self::Deferred | Self::DeferredModelOnly)
}
/// Returns whether this tool can participate in code mode.
pub fn is_available_in_code_mode(self) -> bool {
match self {
Self::Direct | Self::Deferred | Self::CodeModeOnly => true,
Self::DirectModelOnly | Self::DeferredModelOnly | Self::Hidden => false,
}
}
}
/// Shared runtime contract for model-visible tools.
///
/// Implementations keep the model-visible spec tied to the executable runtime.
/// Host crates can layer routing, hooks, telemetry, or other orchestration on
/// top without reopening the spec/runtime split.
pub trait ToolExecutor<Invocation>: Send + Sync {
/// The concrete tool name handled by this runtime instance.
fn tool_name(&self) -> ToolName;
fn spec(&self) -> ToolSpec;
/// The preferred exposure before the host applies step-specific policy.
fn exposure(&self) -> ToolExposure {
ToolExposure::Direct
}
fn search_info(&self) -> Option<ToolSearchInfo> {
let spec = self.spec();
ToolSearchInfo::from_tool_spec(spec, /*source_info*/ None)
}
fn supports_parallel_tool_calls(&self) -> bool {
false
}
/// Return the argument names and environment IDs used by this call. The host supplies their
/// filesystem accessors in the same order. An empty list keeps the turn-wide environment view.
fn environment_arguments(
&self,
_payload: &crate::ToolPayload,
) -> Result<Vec<(&'static str, String)>, FunctionCallError> {
Ok(Vec::new())
}
/// Handles one invocation without retaining capabilities borrowed by the host.
fn handle<'a>(&'a self, invocation: Invocation) -> ToolExecutorFuture<'a>
where
Invocation: 'a;
}

View File

@@ -0,0 +1,288 @@
use codex_protocol::models::FunctionCallOutputBody;
use codex_protocol::models::FunctionCallOutputContentItem;
use codex_protocol::models::FunctionCallOutputPayload;
use codex_protocol::models::ImageReference;
use codex_protocol::models::ResponseInputItem;
use codex_utils_path_uri::PathUri;
use serde_json::Value as JsonValue;
use crate::ToolPayload;
/// Model-facing output contract returned by executable tool runtimes.
pub trait ToolOutput: Send {
/// Returns a deliberately lossy diagnostic representation, before telemetry size limits.
/// Implementations may summarize results or omit media and encrypted content. This is not
/// the authoritative tool result; an untruncated log does not imply a complete result.
/// The logger owns the additional configurable byte limit.
fn log_output(&self) -> String;
fn success_for_logging(&self) -> bool;
/// Finalizes output using the same completed handler duration reported in tool-call logs.
/// Called before recording model-visible history; implementations must not measure time here.
fn set_handler_duration_ms(&mut self, _handler_duration_ms: u64) {}
/// Whether this output contains external context that should disable memory generation when
/// `memories.disable_on_external_context` is enabled.
fn contains_external_context(&self) -> bool {
false
}
/// Overrides history's fallback token limit after tool-specific truncation.
/// Include any serialization allowance; history uses this limit unchanged.
fn fallback_token_limit_override(&self) -> Option<usize> {
None
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem;
/// Returns the tool call id exposed to `PostToolUse` hooks for this output.
fn post_tool_use_id(&self, call_id: &str) -> String {
call_id.to_string()
}
/// Returns the original local execution cwd for hook input, including delayed
/// results. Remote commands return `None` to retain the host hook cwd.
/// This does not change the local directory used to launch the hook process.
fn post_tool_use_cwd(&self) -> Option<PathUri> {
None
}
/// Returns the tool input exposed to `PostToolUse` hooks for this output.
fn post_tool_use_input(&self, _payload: &ToolPayload) -> Option<JsonValue> {
None
}
/// Returns the stable value exposed to `PostToolUse` hooks for this tool output.
///
/// Tool handlers decide whether a tool participates in `PostToolUse`, but
/// this method lets the output type own any conversion from model-facing
/// response content to hook-facing data. Returning `None` means the output
/// should not produce a post-use hook payload, not merely that the tool had
/// empty output.
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<JsonValue> {
None
}
fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue {
response_input_to_code_mode_result(self.to_response_item("", payload))
}
/// Borrows original host-only metadata for recording, not for model output or logging.
fn tool_result_metadata(&self) -> Option<&JsonValue> {
None
}
}
impl<T> ToolOutput for Box<T>
where
T: ToolOutput + ?Sized,
{
fn log_output(&self) -> String {
(**self).log_output()
}
fn success_for_logging(&self) -> bool {
(**self).success_for_logging()
}
fn set_handler_duration_ms(&mut self, handler_duration_ms: u64) {
(**self).set_handler_duration_ms(handler_duration_ms);
}
fn contains_external_context(&self) -> bool {
(**self).contains_external_context()
}
fn fallback_token_limit_override(&self) -> Option<usize> {
(**self).fallback_token_limit_override()
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
(**self).to_response_item(call_id, payload)
}
fn post_tool_use_id(&self, call_id: &str) -> String {
(**self).post_tool_use_id(call_id)
}
fn post_tool_use_cwd(&self) -> Option<PathUri> {
(**self).post_tool_use_cwd()
}
fn post_tool_use_input(&self, payload: &ToolPayload) -> Option<JsonValue> {
(**self).post_tool_use_input(payload)
}
fn post_tool_use_response(&self, call_id: &str, payload: &ToolPayload) -> Option<JsonValue> {
(**self).post_tool_use_response(call_id, payload)
}
fn code_mode_result(&self, payload: &ToolPayload) -> JsonValue {
(**self).code_mode_result(payload)
}
fn tool_result_metadata(&self) -> Option<&JsonValue> {
(**self).tool_result_metadata()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct JsonToolOutput {
value: JsonValue,
success: Option<bool>,
contains_external_context: bool,
}
impl JsonToolOutput {
pub fn new(value: JsonValue) -> Self {
Self {
value,
success: Some(true),
contains_external_context: false,
}
}
pub fn with_success(value: JsonValue, success: Option<bool>) -> Self {
Self {
value,
success,
contains_external_context: false,
}
}
pub fn with_external_context(mut self) -> Self {
self.contains_external_context = true;
self
}
}
impl ToolOutput for JsonToolOutput {
fn log_output(&self) -> String {
self.value.to_string()
}
fn success_for_logging(&self) -> bool {
self.success.unwrap_or(true)
}
fn contains_external_context(&self) -> bool {
self.contains_external_context
}
fn to_response_item(&self, call_id: &str, payload: &ToolPayload) -> ResponseInputItem {
let output = FunctionCallOutputPayload {
body: FunctionCallOutputBody::Text(self.value.to_string()),
success: self.success,
};
if matches!(payload, ToolPayload::Custom { .. }) {
return ResponseInputItem::CustomToolCallOutput {
call_id: call_id.to_string(),
name: None,
output,
};
}
ResponseInputItem::FunctionCallOutput {
call_id: call_id.to_string(),
output,
}
}
fn post_tool_use_response(&self, _call_id: &str, _payload: &ToolPayload) -> Option<JsonValue> {
Some(self.value.clone())
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
self.value.clone()
}
}
impl ToolOutput for codex_protocol::mcp::CallToolResult {
fn log_output(&self) -> String {
let output = self.as_function_call_output_payload();
// Do not fall back to serializing media or encrypted content into logs.
output.body.to_text().unwrap_or_default()
}
fn success_for_logging(&self) -> bool {
self.success()
}
fn to_response_item(&self, call_id: &str, _payload: &ToolPayload) -> ResponseInputItem {
ResponseInputItem::McpToolCallOutput {
call_id: call_id.to_string(),
output: self.clone(),
}
}
fn code_mode_result(&self, _payload: &ToolPayload) -> JsonValue {
let mut result = serde_json::to_value(self).unwrap_or_else(|err| {
JsonValue::String(format!("failed to serialize mcp result: {err}"))
});
// MCP result metadata is private to clients and must not reach Code Mode.
if let JsonValue::Object(fields) = &mut result {
fields.remove("_meta");
}
result
}
}
fn response_input_to_code_mode_result(response: ResponseInputItem) -> JsonValue {
match response {
ResponseInputItem::Message { content, .. } => content_items_to_code_mode_result(
&content
.into_iter()
.map(FunctionCallOutputContentItem::from)
.collect::<Vec<_>>(),
),
ResponseInputItem::FunctionCallOutput { output, .. }
| ResponseInputItem::CustomToolCallOutput { output, .. } => match output.body {
FunctionCallOutputBody::Text(text) => JsonValue::String(text),
FunctionCallOutputBody::ContentItems(items) => {
content_items_to_code_mode_result(&items)
}
},
ResponseInputItem::ToolSearchOutput { tools, .. } => JsonValue::Array(tools),
ResponseInputItem::McpToolCallOutput { output, .. } => serde_json::to_value(output)
.unwrap_or_else(|err| {
JsonValue::String(format!("failed to serialize mcp result: {err}"))
}),
}
}
fn content_items_to_code_mode_result(items: &[FunctionCallOutputContentItem]) -> JsonValue {
JsonValue::String(
items
.iter()
.filter_map(|item| match item {
FunctionCallOutputContentItem::InputText { text } if !text.trim().is_empty() => {
Some(text.clone())
}
FunctionCallOutputContentItem::InputImage {
image: ImageReference::Inline { image_url },
..
} if !image_url.trim().is_empty() => Some(image_url.clone()),
FunctionCallOutputContentItem::InputImage {
image: ImageReference::File { file_id },
..
} if !file_id.trim().is_empty() => Some(file_id.clone()),
FunctionCallOutputContentItem::InputAudio { audio_url }
if !audio_url.trim().is_empty() =>
{
Some(audio_url.clone())
}
FunctionCallOutputContentItem::InputText { .. }
| FunctionCallOutputContentItem::InputImage { .. }
| FunctionCallOutputContentItem::InputAudio { .. }
| FunctionCallOutputContentItem::EncryptedContent { .. } => None,
})
.collect::<Vec<_>>()
.join("\n"),
)
}
#[cfg(test)]
#[path = "tool_output_tests.rs"]
mod tests;

View File

@@ -0,0 +1,54 @@
use codex_protocol::models::AudioReference;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ImageReference;
use codex_protocol::models::ResponseInputItem;
use pretty_assertions::assert_eq;
use super::response_input_to_code_mode_result;
#[test]
fn code_mode_text_preserves_message_content() {
let response = ResponseInputItem::Message {
role: "user".to_string(),
content: vec![
ContentItem::InputText {
text: "Input text".to_string(),
},
ContentItem::OutputText {
text: "Output text".to_string(),
annotations: Some(vec![serde_json::json!({"type": "citation"})]),
logprobs: Some(vec![serde_json::json!({"token": "Output"})]),
},
ContentItem::InputImage {
image: ImageReference::File {
file_id: "file_123".to_string(),
},
detail: None,
},
ContentItem::InputImage {
image: ImageReference::Inline {
image_url: "data:image/png;base64,abc".to_string(),
},
detail: None,
},
ContentItem::InputAudio {
audio: AudioReference::Inline {
audio_url: "data:audio/wav;base64,def".to_string(),
},
},
ContentItem::InputAudio {
audio: AudioReference::File {
file_id: "file_audio".to_string(),
},
},
],
phase: None,
};
assert_eq!(
response_input_to_code_mode_result(response),
serde_json::json!(
"Input text\nOutput text\nfile_123\ndata:image/png;base64,abc\ndata:audio/wav;base64,def\nfile_audio"
)
);
}

View File

@@ -0,0 +1,21 @@
use std::borrow::Cow;
use codex_protocol::models::SearchToolCallParams;
/// Canonical payload shapes accepted by model-visible tool runtimes.
#[derive(Clone, Debug, PartialEq)]
pub enum ToolPayload {
Function { arguments: String },
ToolSearch { arguments: SearchToolCallParams },
Custom { input: String },
}
impl ToolPayload {
pub fn log_payload(&self) -> Cow<'_, str> {
match self {
ToolPayload::Function { arguments } => Cow::Borrowed(arguments),
ToolPayload::ToolSearch { arguments } => Cow::Owned(arguments.query.clone()),
ToolPayload::Custom { input } => Cow::Borrowed(input),
}
}
}

View File

@@ -0,0 +1,207 @@
use crate::JsonSchema;
use crate::LoadableToolSpec;
use crate::ResponsesApiNamespace;
use crate::ResponsesApiNamespaceTool;
use crate::ResponsesApiTool;
use crate::ToolName;
use crate::ToolSearchSourceInfo;
use crate::ToolSpec;
use crate::default_namespace_description;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use std::sync::Arc;
#[derive(Clone, PartialEq)]
pub struct ToolSearchEntry {
pub search_text: String,
spec: Arc<ToolSpec>,
}
impl ToolSearchEntry {
/// Iterate candidate identities without materializing their tool schemas.
pub fn tool_names(&self) -> impl Iterator<Item = ToolName> + '_ {
let (namespace, name, tools): (&str, Option<&str>, &[ResponsesApiNamespaceTool]) =
match self.spec.as_ref() {
ToolSpec::Function(tool) => (DEFAULT_FUNCTION_NAMESPACE, Some(&tool.name), &[]),
ToolSpec::Freeform(tool) => (DEFAULT_FUNCTION_NAMESPACE, Some(&tool.name), &[]),
ToolSpec::Namespace(namespace) => {
(&namespace.name, None, namespace.tools.as_slice())
}
ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => {
unreachable!("search entries contain only loadable tools");
}
};
name.into_iter()
.chain(tools.iter().map(|tool| match tool {
ResponsesApiNamespaceTool::Function(tool) => tool.name.as_str(),
ResponsesApiNamespaceTool::Custom(tool) => tool.name.as_str(),
}))
.map(move |name| ToolName::namespaced(namespace, name))
}
/// Materialize only selected results; output schemas remain shared until discarded.
pub fn to_loadable_spec(&self) -> LoadableToolSpec {
let Some(output) = normalize_search_spec(self.spec.as_ref().clone()) else {
unreachable!("search entries contain only loadable tools");
};
output
}
}
#[derive(Clone, PartialEq)]
pub struct ToolSearchInfo {
pub entry: ToolSearchEntry,
pub source_info: Option<ToolSearchSourceInfo>,
}
impl ToolSearchInfo {
/// Keep the immutable catalog snapshot alive without duplicating its schemas.
pub fn from_shared_spec(
search_text: String,
spec: Arc<ToolSpec>,
source_info: Option<ToolSearchSourceInfo>,
) -> Option<Self> {
match spec.as_ref() {
ToolSpec::Function(_) | ToolSpec::Freeform(_) | ToolSpec::Namespace(_) => Some(Self {
entry: ToolSearchEntry { search_text, spec },
source_info,
}),
ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => None,
}
}
pub fn from_tool_spec(
spec: ToolSpec,
source_info: Option<ToolSearchSourceInfo>,
) -> Option<Self> {
let search_text = default_tool_search_text(&spec);
Self::from_spec(search_text, spec, source_info)
}
pub fn from_spec(
search_text: String,
spec: ToolSpec,
source_info: Option<ToolSearchSourceInfo>,
) -> Option<Self> {
// Dynamic-tool cache entries compare normalized specs by value.
// Preserve that behavior; shared MCP specs normalize only when selected.
let output = normalize_search_spec(spec)?;
Some(Self {
entry: ToolSearchEntry {
search_text,
spec: Arc::new(output.into()),
},
source_info,
})
}
}
fn normalize_search_spec(spec: ToolSpec) -> Option<LoadableToolSpec> {
let mut namespace = match spec {
ToolSpec::Function(tool) => ResponsesApiNamespace {
name: DEFAULT_FUNCTION_NAMESPACE.to_string(),
description: default_namespace_description(DEFAULT_FUNCTION_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Function(tool)],
},
ToolSpec::Freeform(tool) => ResponsesApiNamespace {
name: DEFAULT_FUNCTION_NAMESPACE.to_string(),
description: default_namespace_description(DEFAULT_FUNCTION_NAMESPACE),
tools: vec![ResponsesApiNamespaceTool::Custom(tool)],
},
ToolSpec::Namespace(namespace) => namespace,
ToolSpec::ToolSearch { .. } | ToolSpec::WebSearch { .. } => {
return None;
}
};
if namespace.description.trim().is_empty() {
namespace.description = default_namespace_description(&namespace.name);
}
for tool in &mut namespace.tools {
match tool {
ResponsesApiNamespaceTool::Function(tool) => {
tool.defer_loading = Some(true);
tool.output_schema = None;
tool.parameters.mcp_input_schema_max_bytes = None;
}
ResponsesApiNamespaceTool::Custom(tool) => {
tool.defer_loading = Some(true);
}
}
}
Some(LoadableToolSpec::Namespace(namespace))
}
fn default_tool_search_text(spec: &ToolSpec) -> String {
let mut parts = Vec::new();
match spec {
ToolSpec::Function(tool) => append_function_search_text(tool, &mut parts),
ToolSpec::Namespace(namespace) => {
push_search_part(&mut parts, namespace.name.clone());
push_search_part(&mut parts, namespace.description.clone());
for tool in &namespace.tools {
match tool {
ResponsesApiNamespaceTool::Function(tool) => {
append_function_search_text(tool, &mut parts);
}
ResponsesApiNamespaceTool::Custom(tool) => {
push_search_part(&mut parts, tool.name.clone());
push_search_part(&mut parts, tool.description.clone());
push_search_part(&mut parts, tool.format.syntax.clone());
}
}
}
}
ToolSpec::ToolSearch { description, .. } => {
push_search_part(&mut parts, description.clone());
}
ToolSpec::WebSearch { .. } => {
push_search_part(&mut parts, "web search".to_string());
}
ToolSpec::Freeform(tool) => {
push_search_part(&mut parts, tool.name.clone());
push_search_part(&mut parts, tool.description.clone());
push_search_part(&mut parts, tool.format.syntax.clone());
}
}
parts.join(" ")
}
fn append_function_search_text(tool: &ResponsesApiTool, parts: &mut Vec<String>) {
push_search_part(parts, tool.name.clone());
push_search_part(parts, tool.name.replace('_', " "));
push_search_part(parts, tool.description.clone());
append_schema_search_text(&tool.parameters, parts);
}
fn append_schema_search_text(schema: &JsonSchema, parts: &mut Vec<String>) {
if let Some(description) = &schema.description {
push_search_part(parts, description.to_string());
}
if let Some(properties) = schema.properties.as_deref() {
for (name, schema) in properties {
push_search_part(parts, name.clone());
append_schema_search_text(schema, parts);
}
}
if let Some(items) = &schema.items {
append_schema_search_text(items, parts);
}
if let Some(variants) = &schema.any_of {
for variant in variants {
append_schema_search_text(variant, parts);
}
}
}
fn push_search_part(parts: &mut Vec<String>, part: String) {
let part = part.trim();
if !part.is_empty() {
parts.push(part.to_string());
}
}
#[cfg(test)]
#[path = "tool_search_tests.rs"]
mod tests;

View File

@@ -0,0 +1,280 @@
use super::*;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
#[test]
fn shared_search_specs_preserve_results_and_release_the_source() {
let function = ResponsesApiTool {
name: "lookup".to_string(),
description: "Look up an item".to_string(),
strict: true,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: Some(serde_json::json!({"type": "object"}).into()),
};
let custom = crate::FreeformTool {
name: "patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: crate::FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
};
for (spec, expected_names) in [
(
ToolSpec::Function(function.clone()),
vec![ToolName::namespaced("functions", "lookup")],
),
(
ToolSpec::Freeform(custom.clone()),
vec![ToolName::namespaced("functions", "patch")],
),
(
ToolSpec::Namespace(ResponsesApiNamespace {
name: "example".to_string(),
description: String::new(),
tools: vec![
ResponsesApiNamespaceTool::Function(function),
ResponsesApiNamespaceTool::Custom(custom),
],
}),
vec![
ToolName::namespaced("example", "lookup"),
ToolName::namespaced("example", "patch"),
],
),
(
ToolSpec::Namespace(ResponsesApiNamespace {
name: "empty".to_string(),
description: String::new(),
tools: Vec::new(),
}),
Vec::new(),
),
] {
let normalized =
ToolSearchInfo::from_spec("query".to_string(), spec.clone(), /*source_info*/ None)
.unwrap();
assert_eq!(
normalized.entry.tool_names().collect::<Vec<_>>(),
expected_names
);
let expected = normalized.entry.to_loadable_spec();
let spec = Arc::new(spec);
let weak = Arc::downgrade(&spec);
let info = ToolSearchInfo::from_shared_spec(
"query".to_string(),
Arc::clone(&spec),
/*source_info*/ None,
)
.unwrap();
drop(spec);
assert!(
weak.upgrade().is_some(),
"search retains the original spec rather than a deep copy"
);
assert_eq!(info.entry.to_loadable_spec(), expected);
assert_eq!(info.entry.tool_names().collect::<Vec<_>>(), expected_names);
drop(info);
assert!(
weak.upgrade().is_none(),
"search does not keep discarded catalogs alive"
);
}
}
#[test]
fn top_level_function_search_results_use_the_default_namespace() {
let function_tool = ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: Some(serde_json::json!({ "type": "object" }).into()),
};
let mut configured_function_tool = function_tool.clone();
configured_function_tool
.parameters
.mcp_input_schema_max_bytes = Some(20_000);
let search_info = ToolSearchInfo::from_tool_spec(
ToolSpec::Function(configured_function_tool),
/*source_info*/ None,
)
.expect("top-level function should be searchable");
assert_eq!(
(
search_info.entry.search_text.clone(),
search_info.entry.to_loadable_spec()
),
(
"lookup_order lookup order Look up an order".to_string(),
LoadableToolSpec::Namespace(ResponsesApiNamespace {
name: "functions".to_string(),
description: String::new(),
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
defer_loading: Some(true),
output_schema: None,
..function_tool
})],
}),
)
);
}
#[test]
fn top_level_custom_tools_are_searchable() {
let custom_tool = crate::FreeformTool {
name: "apply_patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: crate::FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
};
let search_info = ToolSearchInfo::from_tool_spec(
ToolSpec::Freeform(custom_tool.clone()),
/*source_info*/ None,
)
.expect("top-level custom tool should be searchable");
assert_eq!(
(
search_info.entry.search_text.clone(),
search_info.entry.to_loadable_spec()
),
(
"apply_patch Apply a patch lark".to_string(),
LoadableToolSpec::Namespace(ResponsesApiNamespace {
name: "functions".to_string(),
description: String::new(),
tools: vec![ResponsesApiNamespaceTool::Custom(crate::FreeformTool {
defer_loading: Some(true),
..custom_tool
})],
}),
)
);
}
#[test]
fn default_search_text_uses_model_visible_namespace_metadata_once() {
let mut schedule_schema = JsonSchema::object(
BTreeMap::from([(
"timezone".to_string(),
JsonSchema::string(Some("IANA timezone.".to_string())),
)]),
/*required*/ None,
/*additional_properties*/ None,
);
schedule_schema.description = Some("Schedule settings.".into());
let mut parameters = JsonSchema::object(
BTreeMap::from([
(
"mode".to_string(),
JsonSchema::string(Some("Update mode.".to_string())),
),
("schedule".to_string(), schedule_schema),
]),
/*required*/ None,
/*additional_properties*/ None,
);
parameters.description = Some("Automation options.".into());
let spec = ToolSpec::Namespace(crate::ResponsesApiNamespace {
name: "codex_app".to_string(),
description: "Manage Codex automations.".to_string(),
tools: vec![ResponsesApiNamespaceTool::Function(ResponsesApiTool {
name: "automation_update".to_string(),
description: "Create or update automations.".to_string(),
strict: false,
defer_loading: None,
parameters,
output_schema: None,
})],
});
let search_info = ToolSearchInfo::from_tool_spec(spec, /*source_info*/ None)
.expect("namespace should be searchable");
assert_eq!(
search_info.entry.search_text,
"codex_app Manage Codex automations. automation_update automation update Create or update automations. Automation options. mode Update mode. schedule Schedule settings. timezone IANA timezone."
);
}
#[test]
fn mixed_namespaced_function_and_custom_tools_are_searchable() {
let function_tool = ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: Some(serde_json::json!({"type": "object"}).into()),
};
let custom_tool = crate::FreeformTool {
name: "apply_patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: crate::FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
};
let mut configured_function_tool = function_tool.clone();
configured_function_tool
.parameters
.mcp_input_schema_max_bytes = Some(20_000);
let spec = ToolSpec::Namespace(crate::ResponsesApiNamespace {
name: "editor".to_string(),
description: "Editing tools".to_string(),
tools: vec![
ResponsesApiNamespaceTool::Function(configured_function_tool),
ResponsesApiNamespaceTool::Custom(custom_tool.clone()),
],
});
let search_info = ToolSearchInfo::from_tool_spec(spec, /*source_info*/ None)
.expect("mixed namespace should be searchable");
assert_eq!(
search_info.entry.search_text,
"editor Editing tools lookup_order lookup order Look up an order apply_patch Apply a patch lark"
);
assert_eq!(
search_info.entry.to_loadable_spec(),
LoadableToolSpec::Namespace(crate::ResponsesApiNamespace {
name: "editor".to_string(),
description: "Editing tools".to_string(),
tools: vec![
ResponsesApiNamespaceTool::Function(ResponsesApiTool {
defer_loading: Some(true),
output_schema: None,
..function_tool
}),
ResponsesApiNamespaceTool::Custom(crate::FreeformTool {
defer_loading: Some(true),
..custom_tool
}),
],
})
);
}

View File

@@ -0,0 +1,193 @@
use crate::FreeformTool;
use crate::JsonSchema;
use crate::LoadableToolSpec;
use crate::ResponsesApiNamespace;
use crate::ResponsesApiNamespaceTool;
use crate::ResponsesApiTool;
use crate::default_namespace_description;
use codex_protocol::DEFAULT_FUNCTION_NAMESPACE;
use codex_protocol::config_types::WebSearchContextSize;
use codex_protocol::config_types::WebSearchFilters as ConfigWebSearchFilters;
use codex_protocol::config_types::WebSearchUserLocation as ConfigWebSearchUserLocation;
use codex_protocol::config_types::WebSearchUserLocationType;
use serde::Serialize;
use serde_json::Value;
use serde_json::value::RawValue;
use std::sync::Arc;
/// When serialized as JSON, this produces a valid "Tool" in the OpenAI
/// Responses API.
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(tag = "type")]
pub enum ToolSpec {
#[serde(rename = "function")]
Function(ResponsesApiTool),
#[serde(rename = "namespace")]
Namespace(ResponsesApiNamespace),
#[serde(rename = "tool_search")]
ToolSearch {
execution: String,
description: String,
parameters: JsonSchema,
},
// TODO: Understand why we get an error on web_search although the API docs
// say it's supported.
// https://platform.openai.com/docs/guides/tools-web-search?api-mode=responses#:~:text=%7B%20type%3A%20%22web_search%22%20%7D%2C
// `external_web_access` distinguishes cached from live-capable search, while
// `indexed_web_access` restricts live fetches to indexed URLs.
// https://platform.openai.com/docs/guides/tools-web-search#live-internet-access
#[serde(rename = "web_search")]
WebSearch {
#[serde(skip_serializing_if = "Option::is_none")]
external_web_access: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
indexed_web_access: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
filters: Option<ResponsesApiWebSearchFilters>,
#[serde(skip_serializing_if = "Option::is_none")]
user_location: Option<ResponsesApiWebSearchUserLocation>,
#[serde(skip_serializing_if = "Option::is_none")]
search_context_size: Option<WebSearchContextSize>,
#[serde(skip_serializing_if = "Option::is_none")]
search_content_types: Option<Vec<String>>,
},
#[serde(rename = "custom")]
Freeform(FreeformTool),
}
impl ToolSpec {
pub fn name(&self) -> &str {
match self {
ToolSpec::Function(tool) => tool.name.as_str(),
ToolSpec::Namespace(namespace) => namespace.name.as_str(),
ToolSpec::ToolSearch { .. } => "tool_search",
ToolSpec::WebSearch { .. } => "web_search",
ToolSpec::Freeform(tool) => tool.name.as_str(),
}
}
}
impl From<LoadableToolSpec> for ToolSpec {
fn from(value: LoadableToolSpec) -> Self {
match value {
LoadableToolSpec::Function(tool) => ToolSpec::Function(tool),
LoadableToolSpec::Namespace(namespace) => ToolSpec::Namespace(namespace),
}
}
}
/// Returns JSON values that are compatible with Function Calling in the
/// Responses API:
/// https://platform.openai.com/docs/guides/function-calling?api-mode=responses
pub fn create_tools_json_for_responses_api(
tools: &[ToolSpec],
) -> Result<Vec<Value>, serde_json::Error> {
let mut tools_json = Vec::new();
for tool in tools {
let json = serde_json::to_value(tool)?;
tools_json.push(json);
}
Ok(tools_json)
}
pub fn create_tools_json_for_responses_lite(
tools: &[ToolSpec],
) -> Result<Vec<Value>, serde_json::Error> {
let mut functions = ResponsesApiNamespace {
name: DEFAULT_FUNCTION_NAMESPACE.to_string(),
description: default_namespace_description(DEFAULT_FUNCTION_NAMESPACE),
tools: Vec::new(),
};
let mut functions_index = None;
let mut tools_json = Vec::new();
for tool in tools {
match tool {
ToolSpec::Function(tool) => {
functions
.tools
.push(ResponsesApiNamespaceTool::Function(tool.clone()));
}
ToolSpec::Freeform(tool) => {
functions
.tools
.push(ResponsesApiNamespaceTool::Custom(tool.clone()));
}
ToolSpec::Namespace(namespace) if namespace.name == DEFAULT_FUNCTION_NAMESPACE => {
if !namespace.description.trim().is_empty() {
functions.description = namespace.description.clone();
}
functions.tools.extend(namespace.tools.clone());
}
tool => {
tools_json.push(serde_json::to_value(tool)?);
continue;
}
}
functions_index.get_or_insert(tools_json.len());
}
if let Some(functions_index) = functions_index
&& !functions.tools.is_empty()
{
tools_json.insert(
functions_index,
serde_json::to_value(ToolSpec::Namespace(functions))?,
);
}
Ok(tools_json)
}
/// Returns raw JSON that can be embedded directly in a Responses API request.
pub fn create_tools_raw_json_for_responses_api(
tools: &[ToolSpec],
) -> Result<Arc<RawValue>, serde_json::Error> {
serde_json::value::to_raw_value(tools).map(Arc::from)
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ResponsesApiWebSearchFilters {
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_domains: Option<Vec<String>>,
}
impl From<ConfigWebSearchFilters> for ResponsesApiWebSearchFilters {
fn from(filters: ConfigWebSearchFilters) -> Self {
Self {
allowed_domains: filters.allowed_domains,
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ResponsesApiWebSearchUserLocation {
#[serde(rename = "type")]
pub r#type: WebSearchUserLocationType,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timezone: Option<String>,
}
impl From<ConfigWebSearchUserLocation> for ResponsesApiWebSearchUserLocation {
fn from(user_location: ConfigWebSearchUserLocation) -> Self {
Self {
r#type: user_location.r#type,
country: user_location.country,
region: user_location.region,
city: user_location.city,
timezone: user_location.timezone,
}
}
}
#[cfg(test)]
#[path = "tool_spec_tests.rs"]
mod tests;

View File

@@ -0,0 +1,413 @@
use super::ResponsesApiNamespace;
use super::ResponsesApiWebSearchFilters;
use super::ResponsesApiWebSearchUserLocation;
use super::ToolSpec;
use crate::AdditionalProperties;
use crate::FreeformTool;
use crate::FreeformToolFormat;
use crate::JsonSchema;
use crate::ResponsesApiNamespaceTool;
use crate::ResponsesApiTool;
use crate::create_tools_json_for_responses_api;
use crate::create_tools_json_for_responses_lite;
use crate::create_tools_raw_json_for_responses_api;
use codex_protocol::config_types::WebSearchContextSize;
use codex_protocol::config_types::WebSearchFilters as ConfigWebSearchFilters;
use codex_protocol::config_types::WebSearchUserLocation as ConfigWebSearchUserLocation;
use codex_protocol::config_types::WebSearchUserLocationType;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
#[test]
fn tool_spec_name_covers_all_variants() {
assert_eq!(
ToolSpec::Function(ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: None,
})
.name(),
"lookup_order"
);
assert_eq!(
ToolSpec::Namespace(ResponsesApiNamespace {
name: "mcp__demo__".to_string(),
description: "Demo tools".to_string(),
tools: Vec::new(),
})
.name(),
"mcp__demo__"
);
assert_eq!(
ToolSpec::ToolSearch {
execution: "sync".to_string(),
description: "Search for tools".to_string(),
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None
),
}
.name(),
"tool_search"
);
assert_eq!(
ToolSpec::WebSearch {
external_web_access: Some(true),
indexed_web_access: None,
filters: None,
user_location: None,
search_context_size: None,
search_content_types: None,
}
.name(),
"web_search"
);
assert_eq!(
ToolSpec::Freeform(FreeformTool {
name: "exec".to_string(),
description: "Run a command".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"exec\"".to_string(),
},
})
.name(),
"exec"
);
}
#[test]
fn web_search_config_converts_to_responses_api_types() {
assert_eq!(
ResponsesApiWebSearchFilters::from(ConfigWebSearchFilters {
allowed_domains: Some(vec!["example.com".to_string()]),
}),
ResponsesApiWebSearchFilters {
allowed_domains: Some(vec!["example.com".to_string()]),
}
);
assert_eq!(
ResponsesApiWebSearchUserLocation::from(ConfigWebSearchUserLocation {
r#type: WebSearchUserLocationType::Approximate,
country: Some("US".to_string()),
region: Some("California".to_string()),
city: Some("San Francisco".to_string()),
timezone: Some("America/Los_Angeles".to_string()),
}),
ResponsesApiWebSearchUserLocation {
r#type: WebSearchUserLocationType::Approximate,
country: Some("US".to_string()),
region: Some("California".to_string()),
city: Some("San Francisco".to_string()),
timezone: Some("America/Los_Angeles".to_string()),
}
);
}
#[test]
fn create_tools_json_for_responses_api_includes_top_level_name() {
assert_eq!(
create_tools_json_for_responses_api(&[ToolSpec::Function(ResponsesApiTool {
name: "demo".to_string(),
description: "A demo tool".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::from([("foo".to_string(), JsonSchema::string(/*description*/ None),)]),
/*required*/ None,
/*additional_properties*/ None
),
output_schema: None,
})])
.expect("serialize tools"),
vec![json!({
"type": "function",
"name": "demo",
"description": "A demo tool",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"foo": { "type": "string" }
},
},
})]
);
}
fn responses_lite_function(name: &str) -> ResponsesApiTool {
ResponsesApiTool {
name: name.to_string(),
description: format!("{name} tool"),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: None,
}
}
#[test]
fn responses_lite_groups_default_function_and_custom_tools() {
let tools = create_tools_json_for_responses_lite(&[
ToolSpec::ToolSearch {
execution: "client".to_string(),
description: "Search tools".to_string(),
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
},
ToolSpec::Function(responses_lite_function("lookup_order")),
ToolSpec::Namespace(ResponsesApiNamespace {
name: "editor".to_string(),
description: "Editing tools".to_string(),
tools: vec![ResponsesApiNamespaceTool::Function(
responses_lite_function("edit"),
)],
}),
ToolSpec::Freeform(FreeformTool {
name: "exec".to_string(),
description: "Run code".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: /.+/".to_string(),
},
}),
ToolSpec::Namespace(ResponsesApiNamespace {
name: "functions".to_string(),
description: "Existing default tools".to_string(),
tools: vec![ResponsesApiNamespaceTool::Function(
responses_lite_function("existing"),
)],
}),
ToolSpec::Function(responses_lite_function("last")),
])
.expect("serialize Responses Lite tools");
assert_eq!(tools.len(), 3);
assert_eq!(tools[0]["type"], "tool_search");
assert_eq!(tools[2]["type"], "namespace");
assert_eq!(tools[2]["name"], "editor");
assert_eq!(tools[2]["tools"][0]["name"], "edit");
assert_eq!(tools[1]["type"], "namespace");
assert_eq!(tools[1]["name"], "functions");
assert_eq!(tools[1]["description"], "Existing default tools");
assert_eq!(
tools[1]["tools"]
.as_array()
.expect("functions namespace should contain tools")
.iter()
.map(|tool| (tool["type"].as_str(), tool["name"].as_str()))
.collect::<Vec<_>>(),
[
(Some("function"), Some("lookup_order")),
(Some("custom"), Some("exec")),
(Some("function"), Some("existing")),
(Some("function"), Some("last")),
]
);
}
#[test]
fn responses_lite_preserves_empty_functions_namespace_description() {
let tools = create_tools_json_for_responses_lite(&[ToolSpec::Function(
responses_lite_function("lookup_order"),
)])
.expect("serialize Responses Lite tools");
assert_eq!(tools[0]["description"], "");
}
#[test]
fn responses_lite_does_not_add_an_empty_functions_namespace() {
let tools =
create_tools_json_for_responses_lite(&[ToolSpec::Namespace(ResponsesApiNamespace {
name: "functions".to_string(),
description: "Empty default tools".to_string(),
tools: Vec::new(),
})])
.expect("serialize Responses Lite tools");
assert!(tools.is_empty());
}
#[test]
fn raw_tool_json_matches_value_encoding() {
let specs = vec![ToolSpec::Function(ResponsesApiTool {
name: "demo".to_string(),
description: "A demo tool".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::new(),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: None,
})];
let expected = create_tools_json_for_responses_api(&specs).expect("serialize tools");
let raw = create_tools_raw_json_for_responses_api(&specs).expect("serialize raw tools");
assert_eq!(
serde_json::from_str::<Vec<serde_json::Value>>(raw.get()).expect("parse raw tools"),
expected,
);
}
#[test]
fn namespace_tool_spec_serializes_expected_wire_shape() {
assert_eq!(
serde_json::to_value(ToolSpec::Namespace(ResponsesApiNamespace {
name: "mcp__demo__".to_string(),
description: "Demo tools".to_string(),
tools: vec![
ResponsesApiNamespaceTool::Function(ResponsesApiTool {
name: "lookup_order".to_string(),
description: "Look up an order".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(
BTreeMap::from([(
"order_id".to_string(),
JsonSchema::string(/*description*/ None),
)]),
/*required*/ None,
/*additional_properties*/ None,
),
output_schema: None,
}),
ResponsesApiNamespaceTool::Custom(FreeformTool {
name: "apply_patch".to_string(),
description: "Apply a patch".to_string(),
defer_loading: None,
format: FreeformToolFormat {
r#type: "grammar".to_string(),
syntax: "lark".to_string(),
definition: "start: \"patch\"".to_string(),
},
}),
],
}))
.expect("serialize namespace tool"),
json!({
"type": "namespace",
"name": "mcp__demo__",
"description": "Demo tools",
"tools": [
{
"type": "function",
"name": "lookup_order",
"description": "Look up an order",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"order_id": { "type": "string" },
},
},
},
{
"type": "custom",
"name": "apply_patch",
"description": "Apply a patch",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": "start: \"patch\"",
},
},
],
})
);
}
#[test]
fn web_search_tool_spec_serializes_expected_wire_shape() {
assert_eq!(
serde_json::to_value(ToolSpec::WebSearch {
external_web_access: Some(true),
indexed_web_access: Some(true),
filters: Some(ResponsesApiWebSearchFilters {
allowed_domains: Some(vec!["example.com".to_string()]),
}),
user_location: Some(ResponsesApiWebSearchUserLocation {
r#type: WebSearchUserLocationType::Approximate,
country: Some("US".to_string()),
region: Some("California".to_string()),
city: Some("San Francisco".to_string()),
timezone: Some("America/Los_Angeles".to_string()),
}),
search_context_size: Some(WebSearchContextSize::High),
search_content_types: Some(vec!["text".to_string(), "image".to_string()]),
})
.expect("serialize web_search"),
json!({
"type": "web_search",
"external_web_access": true,
"indexed_web_access": true,
"filters": {
"allowed_domains": ["example.com"],
},
"user_location": {
"type": "approximate",
"country": "US",
"region": "California",
"city": "San Francisco",
"timezone": "America/Los_Angeles",
},
"search_context_size": "high",
"search_content_types": ["text", "image"],
})
);
}
#[test]
fn tool_search_tool_spec_serializes_expected_wire_shape() {
assert_eq!(
serde_json::to_value(ToolSpec::ToolSearch {
execution: "sync".to_string(),
description: "Search app tools".to_string(),
parameters: JsonSchema::object(
BTreeMap::from([(
"query".to_string(),
JsonSchema::string(Some("Tool search query".to_string()),),
)]),
Some(vec!["query".to_string()]),
Some(AdditionalProperties::Boolean(false))
),
})
.expect("serialize tool_search"),
json!({
"type": "tool_search",
"execution": "sync",
"description": "Search app tools",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Tool search query",
}
},
"required": ["query"],
"additionalProperties": false,
},
})
);
}