Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

Support model catalog overrides for MCP resource tool specs (#47677)

rhan-oaib2aa42e6f103
diff --git a/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resource_templates.rs b/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resource_templates.rs
index 46a9297cc0..271b843594 100644
--- a/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resource_templates.rs
+++ b/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resource_templates.rs
@@ -4,6 +4,7 @@ use crate::tools::context::ToolPayload;
use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resource_templates_tool;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
+use codex_protocol::openai_models::ToolMessage;
use codex_protocol::protocol::McpInvocation;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
@@ -15,7 +16,9 @@ use super::parse_args_with_default;
use super::parse_arguments;
use super::run_resource_operation;
-pub struct ListMcpResourceTemplatesHandler;
+pub struct ListMcpResourceTemplatesHandler {
+ spec: ToolSpec,
+}
impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
fn tool_name(&self) -> ToolName {
@@ -23,7 +26,7 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
}
fn spec(&self) -> ToolSpec {
- create_list_mcp_resource_templates_tool()
+ self.spec.clone()
}
fn supports_parallel_tool_calls(&self) -> bool {
@@ -39,6 +42,12 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourceTemplatesHandler {
}
impl ListMcpResourceTemplatesHandler {
+ pub fn new(messages: Option<&ToolMessage>) -> Self {
+ Self {
+ spec: create_list_mcp_resource_templates_tool(messages),
+ }
+ }
+
async fn handle_call(
&self,
invocation: ToolInvocation,
diff --git a/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resources.rs b/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resources.rs
index ea39895d30..650673f76b 100644
--- a/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resources.rs
+++ b/codex-rs/core/src/tools/handlers/mcp_resource/list_mcp_resources.rs
@@ -4,6 +4,7 @@ use crate::tools::context::ToolPayload;
use crate::tools::handlers::mcp_resource_spec::create_list_mcp_resources_tool;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
+use codex_protocol::openai_models::ToolMessage;
use codex_protocol::protocol::McpInvocation;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
@@ -15,7 +16,9 @@ use super::parse_args_with_default;
use super::parse_arguments;
use super::run_resource_operation;
-pub struct ListMcpResourcesHandler;
+pub struct ListMcpResourcesHandler {
+ spec: ToolSpec,
+}
impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
fn tool_name(&self) -> ToolName {
@@ -23,7 +26,7 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
}
fn spec(&self) -> ToolSpec {
- create_list_mcp_resources_tool()
+ self.spec.clone()
}
fn supports_parallel_tool_calls(&self) -> bool {
@@ -39,6 +42,12 @@ impl ToolExecutor<ToolInvocation> for ListMcpResourcesHandler {
}
impl ListMcpResourcesHandler {
+ pub fn new(messages: Option<&ToolMessage>) -> Self {
+ Self {
+ spec: create_list_mcp_resources_tool(messages),
+ }
+ }
+
async fn handle_call(
&self,
invocation: ToolInvocation,
diff --git a/codex-rs/core/src/tools/handlers/mcp_resource/read_mcp_resource.rs b/codex-rs/core/src/tools/handlers/mcp_resource/read_mcp_resource.rs
index 8a5ac7f324..e8c828bf8c 100644
--- a/codex-rs/core/src/tools/handlers/mcp_resource/read_mcp_resource.rs
+++ b/codex-rs/core/src/tools/handlers/mcp_resource/read_mcp_resource.rs
@@ -4,6 +4,7 @@ use crate::tools::context::ToolPayload;
use crate::tools::handlers::mcp_resource_spec::create_read_mcp_resource_tool;
use crate::tools::registry::CoreToolRuntime;
use crate::tools::registry::ToolExecutor;
+use codex_protocol::openai_models::ToolMessage;
use codex_protocol::protocol::McpInvocation;
use codex_tools::ToolName;
use codex_tools::ToolSpec;
@@ -18,7 +19,9 @@ use super::parse_args;
use super::parse_arguments;
use super::run_resource_operation;
-pub struct ReadMcpResourceHandler;
+pub struct ReadMcpResourceHandler {
+ spec: ToolSpec,
+}
impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
fn tool_name(&self) -> ToolName {
@@ -26,7 +29,7 @@ impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
}
fn spec(&self) -> ToolSpec {
- create_read_mcp_resource_tool()
+ self.spec.clone()
}
fn supports_parallel_tool_calls(&self) -> bool {
@@ -42,6 +45,12 @@ impl ToolExecutor<ToolInvocation> for ReadMcpResourceHandler {
}
impl ReadMcpResourceHandler {
+ pub fn new(messages: Option<&ToolMessage>) -> Self {
+ Self {
+ spec: create_read_mcp_resource_tool(messages),
+ }
+ }
+
async fn handle_call(
&self,
invocation: ToolInvocation,
diff --git a/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs b/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs
index 526fb990c3..4c6d41f06b 100644
--- a/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs
+++ b/codex-rs/core/src/tools/handlers/mcp_resource_spec.rs
@@ -1,9 +1,10 @@
+use codex_protocol::openai_models::ToolMessage;
use codex_tools::JsonSchema;
use codex_tools::ResponsesApiTool;
use codex_tools::ToolSpec;
use std::collections::BTreeMap;
-pub fn create_list_mcp_resources_tool() -> ToolSpec {
+pub fn create_list_mcp_resources_tool(messages: Option<&ToolMessage>) -> ToolSpec {
let properties = BTreeMap::from([
(
"server".to_string(),
@@ -20,17 +21,18 @@ pub fn create_list_mcp_resources_tool() -> ToolSpec {
),
]);
- ToolSpec::Function(ResponsesApiTool {
+ let tool = ResponsesApiTool {
name: "list_mcp_resources".to_string(),
description: "Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(properties, /*required*/ None, Some(false.into())),
output_schema: None,
- })
+ };
+ with_model_messages(tool, messages)
}
-pub fn create_list_mcp_resource_templates_tool() -> ToolSpec {
+pub fn create_list_mcp_resource_templates_tool(messages: Option<&ToolMessage>) -> ToolSpec {
let properties = BTreeMap::from([
(
"server".to_string(),
@@ -48,17 +50,18 @@ pub fn create_list_mcp_resource_templates_tool() -> ToolSpec {
),
]);
- ToolSpec::Function(ResponsesApiTool {
+ let tool = ResponsesApiTool {
name: "list_mcp_resource_templates".to_string(),
description: "Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.".to_string(),
strict: false,
defer_loading: None,
parameters: JsonSchema::object(properties, /*required*/ None, Some(false.into())),
output_schema: None,
- })
+ };
+ with_model_messages(tool, messages)
}
-pub fn create_read_mcp_resource_tool() -> ToolSpec {
+pub fn create_read_mcp_resource_tool(messages: Option<&ToolMessage>) -> ToolSpec {
let properties = BTreeMap::from([
(
"server".to_string(),
@@ -76,7 +79,7 @@ pub fn create_read_mcp_resource_tool() -> ToolSpec {
),
]);
- ToolSpec::Function(ResponsesApiTool {
+ let tool = ResponsesApiTool {
name: "read_mcp_resource".to_string(),
description:
"Read a specific resource from an MCP server given the server name and resource URI."
@@ -89,7 +92,27 @@ pub fn create_read_mcp_resource_tool() -> ToolSpec {
Some(false.into()),
),
output_schema: None,
- })
+ };
+ with_model_messages(tool, messages)
+}
+
+fn with_model_messages(mut tool: ResponsesApiTool, messages: Option<&ToolMessage>) -> ToolSpec {
+ if let Some(messages) = messages {
+ if let Some(description) = &messages.description {
+ tool.description.clone_from(description);
+ }
+ if let Some(parameters) = &messages.parameters {
+ match crate::tools::catalog_parameters::parse(parameters) {
+ Ok(parameters) => tool.parameters = parameters,
+ Err(reason) => tracing::warn!(
+ tool = %tool.name,
+ reason,
+ "Invalid catalog tool parameters; using bundled parameters"
+ ),
+ }
+ }
+ }
+ ToolSpec::Function(tool)
}
#[cfg(test)]
diff --git a/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs b/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs
index a50879d9df..ec6839e4e8 100644
--- a/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs
+++ b/codex-rs/core/src/tools/handlers/mcp_resource_spec_tests.rs
@@ -6,7 +6,7 @@ use std::collections::BTreeMap;
#[test]
fn list_mcp_resources_tool_matches_expected_spec() {
assert_eq!(
- create_list_mcp_resources_tool(),
+ create_list_mcp_resources_tool(/*messages*/ None),
ToolSpec::Function(ResponsesApiTool {
name: "list_mcp_resources".to_string(),
description: "Lists resources provided by MCP servers. Resources allow servers to share data that provides context to language models, such as files, database schemas, or application-specific information. Prefer resources over web search when possible.".to_string(),
@@ -36,7 +36,7 @@ fn list_mcp_resources_tool_matches_expected_spec() {
#[test]
fn list_mcp_resource_templates_tool_matches_expected_spec() {
assert_eq!(
- create_list_mcp_resource_templates_tool(),
+ create_list_mcp_resource_templates_tool(/*messages*/ None),
ToolSpec::Function(ResponsesApiTool {
name: "list_mcp_resource_templates".to_string(),
description: "Lists resource templates provided by MCP servers. Parameterized resource templates allow servers to share data that takes parameters and provides context to language models, such as files, database schemas, or application-specific information. Prefer resource templates over web search when possible.".to_string(),
@@ -66,7 +66,7 @@ fn list_mcp_resource_templates_tool_matches_expected_spec() {
#[test]
fn read_mcp_resource_tool_matches_expected_spec() {
assert_eq!(
- create_read_mcp_resource_tool(),
+ create_read_mcp_resource_tool(/*messages*/ None),
ToolSpec::Function(ResponsesApiTool {
name: "read_mcp_resource".to_string(),
description:
@@ -94,3 +94,42 @@ fn read_mcp_resource_tool_matches_expected_spec() {
})
);
}
+
+#[test]
+fn catalog_fields_override_independently_and_invalid_parameters_fall_back() {
+ let parameters = r#"{"type":"object","properties":{"server":{"type":"string","description":"Catalog server guidance."}},"additionalProperties":false}"#;
+ for create_tool in [
+ create_list_mcp_resources_tool,
+ create_list_mcp_resource_templates_tool,
+ create_read_mcp_resource_tool,
+ ] {
+ for (description, schema, valid_schema) in [
+ (None, None, false),
+ (Some(""), None, false),
+ (None, Some(parameters), true),
+ (
+ Some(" Catalog {{literal}} guidance.\n"),
+ Some(parameters),
+ true,
+ ),
+ (Some("Catalog guidance."), Some("invalid JSON"), false),
+ (None, Some(r#"{"type":"string"}"#), false),
+ ] {
+ let messages = ToolMessage {
+ description: description.map(str::to_owned),
+ parameters: schema.map(str::to_owned),
+ };
+ let mut expected = create_tool(/*messages*/ None);
+ let ToolSpec::Function(tool) = &mut expected else {
+ panic!("expected a function tool");
+ };
+ if let Some(description) = description {
+ tool.description = description.to_owned();
+ }
+ if valid_schema {
+ tool.parameters = serde_json::from_str(parameters).unwrap();
+ }
+ assert_eq!(create_tool(Some(&messages)), expected);
+ }
+ }
+}
diff --git a/codex-rs/core/src/tools/spec_plan.rs b/codex-rs/core/src/tools/spec_plan.rs
index ddac78f3cd..738560ca71 100644
--- a/codex-rs/core/src/tools/spec_plan.rs
+++ b/codex-rs/core/src/tools/spec_plan.rs
@@ -1123,9 +1123,16 @@ fn unified_exec_should_include_shell_parameter(
#[instrument(level = "trace", skip_all)]
fn add_mcp_resource_tools(context: &CoreToolPlanContext<'_>, registry: &mut ToolRegistry) {
if context.mcp.has_servers() {
- registry.add(ListMcpResourcesHandler);
- registry.add(ListMcpResourceTemplatesHandler);
- registry.add(ReadMcpResourceHandler);
+ let messages = ResolvedModelMessages::from_model(context.model_info).mcp_resources();
+ registry.add(ListMcpResourcesHandler::new(
+ messages.and_then(|messages| messages.list_mcp_resources.as_ref()),
+ ));
+ registry.add(ListMcpResourceTemplatesHandler::new(
+ messages.and_then(|messages| messages.list_mcp_resource_templates.as_ref()),
+ ));
+ registry.add(ReadMcpResourceHandler::new(
+ messages.and_then(|messages| messages.read_mcp_resource.as_ref()),
+ ));
}
}
diff --git a/codex-rs/core/tests/suite/scenarios.rs b/codex-rs/core/tests/suite/scenarios.rs
index 46ca14959f..3a8c6a5361 100644
--- a/codex-rs/core/tests/suite/scenarios.rs
+++ b/codex-rs/core/tests/suite/scenarios.rs
@@ -88,6 +88,9 @@ mod guardian_extra_policy;
#[path = "scenarios_indirect_namespace_prefixes.rs"]
mod indirect_namespace_prefixes;
+#[path = "scenarios_mcp_resource_messages.rs"]
+mod mcp_resource_messages;
+
#[path = "scenarios_preparation.rs"]
mod preparation;
diff --git a/codex-rs/core/tests/suite/scenarios_mcp_resource_messages.rs b/codex-rs/core/tests/suite/scenarios_mcp_resource_messages.rs
new file mode 100644
index 0000000000..b2416201ce
--- /dev/null
+++ b/codex-rs/core/tests/suite/scenarios_mcp_resource_messages.rs
@@ -0,0 +1,162 @@
+//! Catalog resource-tool text reaches direct calls and Code Mode without changing MCP execution.
+
+use super::super::rmcp_client::remote_aware_environment_id;
+use super::super::rmcp_client::remote_aware_stdio_server_bin;
+use anyhow::Result;
+use codex_features::Feature;
+use codex_protocol::openai_models::ToolMode;
+use core_test_support::context_snapshot;
+use core_test_support::context_snapshot::ContextSnapshotOptions;
+use core_test_support::responses;
+use core_test_support::skip_if_no_network;
+use core_test_support::skip_if_wine_exec;
+use core_test_support::test_codex::test_codex;
+use core_test_support::wait_for_mcp_server;
+use pretty_assertions::assert_eq;
+use serde_json::json;
+use std::collections::HashMap;
+use test_case::test_case;
+
+#[test_case(ToolMode::Direct; "direct")]
+#[test_case(ToolMode::CodeModeOnly; "code_mode")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn mcp_resource_messages(tool_mode: ToolMode) -> Result<()> {
+ skip_if_no_network!(Ok(()));
+ skip_if_wine_exec!(Ok(()), "requires a Windows test_stdio_server binary");
+ let server = responses::start_mock_server().await;
+ let command = remote_aware_stdio_server_bin()?;
+ let calls = [
+ ("list_mcp_resources", r#"{"server":"resources"}"#),
+ ("list_mcp_resource_templates", r#"{"server":"resources"}"#),
+ (
+ "read_mcp_resource",
+ r#"{"server":"resources","uri":"memo://codex/example-note"}"#,
+ ),
+ ];
+ let mut messages = serde_json::Map::new();
+ for (name, _) in calls {
+ let mut parameters = json!({
+ "type": "object",
+ "properties": {"server": {"type": "string", "description": format!("Catalog server for {name}.")}},
+ "additionalProperties": false,
+ });
+ if name == "read_mcp_resource" {
+ parameters["properties"]["uri"] = json!({"type": "string", "description": "Catalog URI returned by resource discovery."});
+ parameters["required"] = json!(["server", "uri"]);
+ } else {
+ parameters["properties"]["cursor"] =
+ json!({"type": "string", "description": "Catalog cursor from the previous page."});
+ }
+ messages.insert(
+ name.to_string(),
+ json!({
+ "description": format!("Catalog instructions for {name}."),
+ "parameters": parameters.to_string(),
+ }),
+ );
+ }
+ let catalog = serde_json::from_value(json!(messages))?;
+ let test = test_codex()
+ .with_config(move |config| {
+ super::configure_scenario_catalog(config);
+ config.code_mode.disable_in_process_fallback = true;
+ config
+ .features
+ .enable(Feature::CodeModeHost)
+ .expect("enable Code Mode host");
+ config
+ .mcp_servers
+ .set(HashMap::from([(
+ "resources".to_string(),
+ serde_json::from_value(json!({
+ "command": command,
+ "environment_id": remote_aware_environment_id(),
+ "cwd": config.cwd,
+ }))
+ .expect("MCP resource fixture"),
+ )]))
+ .expect("configure resources server");
+ })
+ .with_model_info_override("gpt-6-astra", move |model| {
+ model.tool_mode = Some(tool_mode);
+ model.use_responses_lite = false;
+ let model_messages = model.model_messages.as_mut().expect("model messages");
+ model_messages
+ .tools
+ .get_or_insert_with(Default::default)
+ .mcp_resources = Some(catalog);
+ })
+ .build_with_auto_env(&server)
+ .await?;
+ wait_for_mcp_server(&test.codex, "resources").await?;
+ let mut events = vec![responses::ev_response_created("resources-response")];
+ events.extend(if tool_mode == ToolMode::CodeModeOnly {
+ let script = calls
+ .iter()
+ .map(|(name, arguments)| format!("text(await tools.{name}({arguments}));"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ vec![responses::ev_custom_tool_call(
+ "resources-call",
+ "exec",
+ &script,
+ )]
+ } else {
+ calls
+ .iter()
+ .map(|(name, arguments)| responses::ev_function_call(name, name, arguments))
+ .collect()
+ });
+ events.push(responses::ev_completed("resources-response"));
+ let mock = responses::mount_sse_sequence(
+ &server,
+ vec![responses::sse(events), responses::sse_completed("done")],
+ )
+ .await;
+ test.submit_turn("List the available resources and templates, then read the example note.")
+ .await?;
+ let requests = mock.requests();
+ assert_eq!(requests.len(), 2);
+ let body = requests[0].body_json();
+ for (name, message) in &messages {
+ if tool_mode == ToolMode::CodeModeOnly {
+ assert!(
+ requests[0]
+ .body_contains_text(message["description"].as_str().expect("description"))
+ );
+ assert!(requests[0].body_contains_text(&format!("Catalog server for {name}.")));
+ } else {
+ let tool = body["tools"]
+ .as_array()
+ .expect("tools")
+ .iter()
+ .find(|tool| tool["name"] == *name)
+ .expect("resource tool");
+ assert_eq!(
+ tool,
+ &json!({
+ "type": "function", "name": name, "description": message["description"],
+ "parameters": serde_json::from_str::<serde_json::Value>(message["parameters"].as_str().expect("parameters"))?,
+ "strict": false,
+ })
+ );
+ }
+ }
+ assert!(requests[1].body_contains_text("Example Note"));
+ assert!(requests[1].body_contains_text("memo://codex/{slug}"));
+ assert!(
+ requests[1]
+ .body_contains_text("This is a sample MCP resource served by the rmcp test server.")
+ );
+ if tool_mode == ToolMode::CodeModeOnly {
+ insta::assert_snapshot!(
+ "mcp_resource_messages",
+ context_snapshot::format_request_history_snapshot(
+ "Catalog resource descriptions and parameter guidance accompany discovery and reading through Code Mode.",
+ &requests,
+ &ContextSnapshotOptions::default().include_request_settings(),
+ )
+ );
+ }
+ Ok(())
+}
diff --git a/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__mcp_resource_messages__mcp_resource_messages.snap b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__mcp_resource_messages__mcp_resource_messages.snap
new file mode 100644
index 0000000000..828a74f9fe
--- /dev/null
+++ b/codex-rs/core/tests/suite/snapshots/all__suite__scenarios__mcp_resource_messages__mcp_resource_messages.snap
@@ -0,0 +1,109 @@
+---
+source: core/tests/suite/scenarios_mcp_resource_messages.rs
+expression: "context_snapshot::format_request_history_snapshot(\"Catalog resource descriptions and parameter guidance accompany discovery and reading through Code Mode.\",\n&requests, &ContextSnapshotOptions::default().include_request_settings(),)"
+---
+Scenario: Catalog resource descriptions and parameter guidance accompany discovery and reading through Code Mode.
+
+## Window 1
+Settings:
+ include: ["reasoning.encrypted_content"]
+ instructions: You are Codex, an agent based on GPT-6. You and the user share one workspace, and your job is to collabo...them until their intended goal is completely handled. [hash=efa50f074efa5803]
+
+ # When to ask the user for permission
+
+ Use your best judgement given task context for when you really need user permission, like a competent co...ork without ending the turn to clarify with the user. [hash=ca7367e658b51388]
+
+ User authorization and preferences persist across turns. Do not request permission again when the user h... any guidelines provided in skills or external files. [hash=911f91c92c72882c]
+
+ <OMITTED 155 LINES; ~4935 TOKENS; hash=5573869716192298>
+
+ - Skill naming: If a plugin contributes skills, those skill entries are prefixed with plugin_name: in the Skills list.
+ - MCP naming: Plugin-provided MCP tools keep standard MCP identifiers such as mcp__server__tool; use tool provenance to tell which plugin they come from.
+ - Trigger rules: If the user explicitly names a plugin, prefer capabilities associated with that plugin for that turn.
+ - Relationship to capabilities: Plugins are not invoked directly. Use their underlying skills, MCP tools, and app tools to help solve the task.
+ - Relevance: Determine what a plugin can help with from explicit user mention or from the plugin-associa..., MCP tools, and apps exposed elsewhere in this turn. [hash=620459a4e7b590f0]
+ - Missing/blocked: If the user requests a plugin that does not have relevant callable capabilities for t..., say so briefly and continue with the best fallback. [hash=746b0469a8f6cb3e]
+
+ model: "gpt-6-astra"
+ parallel_tool_calls: true
+ prompt_cache_key: "<PROMPT_CACHE_KEY 1>"
+ reasoning: {"effort":"low"}
+ store: false
+ stream: true
+ text: {"verbosity":"low"}
+ tool_choice: "auto"
+ tools (7; hash=de6aceb7b0185d08):
+ - custom/exec: Run JavaScript code to orchestrate/compose tool calls - Evaluates the provided JavaScript code in...; hash=50ea9b7f60e145b5
+ - function/wait: Waits on a yielded `exec` cell and returns new output or completion. - Use `wait` only after `exe...; args=[cell_id, max_tokens, terminate, yield_time_ms]; hash=6692d8f6c55be489
+ - function/request_user_input: Request user input for one to three short questions and wait for the response. This tool is only ...; args=[questions]; hash=64a729b25c424fc6
+ - function/request_user_input_async: Ask the user one or more questions during ongoing work. Use this tool only to request missing inf...; args=[questions]; hash=d6d74f33db330162
+ - namespace/clock: Tools for reading and waiting on time.; hash=f402e8c5e9b5e317
+ - function/sleep
+ - namespace/collaboration: Tools for spawning and managing sub-agents.; hash=fd994b11525da73c
+ - function/followup_task
+ - function/interrupt_agent
+ - function/list_agents
+ - function/send_message
+ - function/spawn_agent
+ - function/wait_agent
+ - web_search; hash=e214d4db1bc49e89
+-- request 1 (turn) --
+00:message/developer[2]:
+ [01] <permissions instructions>
+ Filesystem sandboxing defines which files can be read or written. `sandbox_mode` is `danger-full-access`...ll commands are permitted. Network access is enabled. [hash=c134061cebb94a1b]
+ Approval policy is currently never. Do not provide the `sandbox_permissions` for any reason, commands will be rejected.
+ </permissions instructions>
+ [02] <collaboration_mode># Collaboration Mode: Default
+
+ You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
+
+ Your active mode changes only when new developer instructions with a different `<collaboration_mode>...<...by themselves. Known mode names are Default and Plan. [hash=e75f6b12fc52d812]
+
+ ## request_user_input availability
+
+ Use the `request_user_input` tool only when it is listed in the available tools for this turn.
+
+ Use the `request_user_input` tool only for optional questions where the answer would materially improve the quality of the work.
+
+ If `request_user_input` returns no answers, continue with best judgment instead of asking again or treating the turn as blocked.
+
+ Never use the `request_user_input` tool for permission requests or permission-related escalations.
+ </collaboration_mode>
+01:message/developer:
+ <multi_agent_role>You are `/root`, the primary agent in a team of agents collaborating to fulfill the user's goals.
+
+ At the start of your turn, you are the active agent.
+ You can spawn sub-agents to handle subtasks, and those sub-agents can spawn their own sub-agents.
+ All agents in the team, including the agents that you can assign tasks to, are equally intelligent and capable, and have access to the same set of tools.
+
+ You can use `spawn_agent` to create a new agent, `followup_task` to give an existing agent a new task an...message to a running agent without triggering a turn. [hash=7d40ff8b58977202]
+ `send_message` calls may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.
+ <OMITTED 17 LINES; ~246 TOKENS; hash=780031e2df907944>
+ - All agents use the same current working directory.
+ - As a result, edits made by one agent are immediately visible to all other agents.
+
+ When calling `wait_agent`, prefer longer waits (minutes) to avoid busy polling.
+
+ There are 4 available concurrency slots, meaning that up to 4 agents can be active at once, including you.
+
+ Full-history forks (`fork_turns` omitted or `"all"`) inherit the parent model and reasoning effort and d...ne"` or a positive integer string.</multi_agent_role> [hash=c7f52e90688299ce]
+02:message/developer:
+ <multi_agent_mode>Any earlier instruction enabling proactive multi-agent delegation no longer applies. D...elegation, or parallel agent work.</multi_agent_mode> [hash=2b6e037067b4390c]
+03:message/user:
+ <environment_context>
+ <cwd><CWD></cwd>
+ <shell><HOST_SHELL></shell>
+ <current_date><CURRENT_DATE></current_date>
+ <timezone><HOST_TIMEZONE></timezone>
+ <filesystem><workspace_roots><root><WORKSPACE_ROOT 1></root></workspace_roots><permission_profile type...e="unrestricted" /></permission_profile></filesystem> [hash=0592734c170299c1]
+ </environment_context>
+04:message/user:
+ List the available resources and templates, then read the example note.
+-- request 2 (turn) --
+05:custom_tool_call/exec:text(await tools.list_mcp_resources({"server":"resources"}));
+ text(await tools.list_mcp_resource_templates({"server":"resources"}));
+ text(await tools.read_mcp_resource({"server":"resources","uri":"memo://codex/example-note"}));
+06:custom_tool_call_output:Script completed
+ Wall time <DURATION> seconds
+ Output:
+ | {"server":"resources","resources":[{"server":"resources","uri":"memo://codex/example-note","name":"examp...ed for integration tests.","mimeType":"text/plain"}]} [hash=75d187638a7af2d4] | {"server":"resources","resourceTemplates":[{"server":"resources","uriTemplate":"memo://codex/{slug}","na... resources used in tests.","mimeType":"text/plain"}]} [hash=b1c7082eb114fc9b] | {"server":"resources","uri":"memo://codex/example-note","contents":[{"uri":"memo://codex/example-note","...mple MCP resource served by the rmcp test server."}]} [hash=45385fc57640b555]
diff --git a/codex-rs/core/tests/suite/step_settings.rs b/codex-rs/core/tests/suite/step_settings.rs
index 833c6299fd..f12af89853 100644
--- a/codex-rs/core/tests/suite/step_settings.rs
+++ b/codex-rs/core/tests/suite/step_settings.rs
@@ -40,6 +40,7 @@ use codex_protocol::openai_models::CollaborationModeMessages;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::ConfirmationPolicies;
use codex_protocol::openai_models::InputModality;
+use codex_protocol::openai_models::McpResourceToolMessages;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelTokenBudgetConfig;
use codex_protocol::openai_models::ModelsResponse;
@@ -3089,6 +3090,17 @@ async fn captured_step_settings_and_history_reach_extension_executor(
async fn captured_step_controls_mcp_resource_output() -> Result<()> {
skip_if_no_network!(Ok(()));
core_test_support::skip_if_wine_exec!(Ok(()), "requires a Windows test_stdio_server binary");
+ let parameters = |model: &str| {
+ json!({
+ "type": "object",
+ "properties": {
+ "server": {"type": "string"},
+ "uri": {"type": "string", "description": format!("Resource URI for {model}.")},
+ },
+ "required": ["server", "uri"],
+ "additionalProperties": false,
+ })
+ };
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
@@ -3116,6 +3128,19 @@ async fn captured_step_controls_mcp_resource_output() -> Result<()> {
for model in &mut config.model_catalog.as_mut().expect("models").models {
model.truncation_policy =
TruncationPolicyConfig::bytes(if model.slug == MODEL_B { 80 } else { 8_000 });
+ model
+ .model_messages
+ .as_mut()
+ .expect("model messages")
+ .tools
+ .get_or_insert_with(Default::default)
+ .mcp_resources = Some(McpResourceToolMessages {
+ read_mcp_resource: Some(ToolMessage {
+ description: Some(format!("Read resource for {}.", model.slug)),
+ parameters: Some(parameters(&model.slug).to_string()),
+ }),
+ ..Default::default()
+ });
}
config
.mcp_servers
@@ -3148,7 +3173,35 @@ async fn captured_step_controls_mcp_resource_output() -> Result<()> {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
- let output = responses.requests()[2]
+ let requests = responses.requests();
+ assert_eq!(
+ requests
+ .iter()
+ .map(|request| {
+ let body = request.body_json();
+ let tool = body["tools"]
+ .as_array()
+ .expect("request tools")
+ .iter()
+ .find(|tool| tool["name"] == "read_mcp_resource")
+ .expect("resource tool");
+ (body["model"].clone(), tool.clone())
+ })
+ .collect::<Vec<_>>(),
+ [MODEL_A, MODEL_B, MODEL_B]
+ .map(|model| (
+ json!(model),
+ json!({
+ "type": "function",
+ "name": "read_mcp_resource",
+ "description": format!("Read resource for {model}."),
+ "parameters": parameters(model),
+ "strict": false,
+ })
+ ))
+ .to_vec(),
+ );
+ let output = requests[2]
.function_call_output_text("resource-b")
.expect("resource output");
assert!(output.starts_with("{\"server\":\"resources\""), "{output}");
diff --git a/codex-rs/prompts/src/model_messages.rs b/codex-rs/prompts/src/model_messages.rs
index 3d68ec518c..8e7a3158d8 100644
--- a/codex-rs/prompts/src/model_messages.rs
+++ b/codex-rs/prompts/src/model_messages.rs
@@ -6,6 +6,7 @@
use codex_protocol::openai_models::CodeModeToolMessages;
use codex_protocol::openai_models::ConfirmationPolicies;
use codex_protocol::openai_models::IndirectDescriptionPrefixes;
+use codex_protocol::openai_models::McpResourceToolMessages;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelMessages;
use codex_protocol::openai_models::ToolMessage;
@@ -172,6 +173,15 @@ impl<'a> ResolvedModelMessages<'a> {
.by_name(tool_name)
}
+ /// Selects resource helper messages; schema parsing belongs to the tool owner.
+ pub fn mcp_resources(&self) -> Option<&'a McpResourceToolMessages> {
+ self.catalog_messages?
+ .tools
+ .as_ref()?
+ .mcp_resources
+ .as_ref()
+ }
+
/// Selects indirect tool guidance; tool rendering owns namespace mapping and normalization.
pub fn indirect_description_prefixes(&self) -> Option<&'a IndirectDescriptionPrefixes> {
self.catalog_messages?
diff --git a/codex-rs/protocol/src/openai_models.rs b/codex-rs/protocol/src/openai_models.rs
index 05c38eec98..68d64fed4c 100644
--- a/codex-rs/protocol/src/openai_models.rs
+++ b/codex-rs/protocol/src/openai_models.rs
@@ -587,6 +587,8 @@ pub struct ToolMessages {
pub multi_agent: Option<MultiAgentToolMessages>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code_mode: Option<CodeModeToolMessages>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub mcp_resources: Option<McpResourceToolMessages>,
}
/// Plain-text prefixes for Code Mode documentation, ALL_TOOLS, and loaded tool-search namespaces.
@@ -611,7 +613,8 @@ pub struct ToolMessage {
/// text without disabling the tool. Tool-owned runtime guidance is retained.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
- /// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools and Code Mode wait.
+ /// Complete JSON Schema encoded as a string. Consumed by Multi-Agent V2 tools, Code Mode wait,
+ /// and the MCP resource helpers.
/// Uses the harness's supported schema subset; unrecognized keywords are ignored.
/// Missing, null, invalid or unsupported structures, or a root without `type: "object"`
/// retains the harness parameters. Schema semantics must remain API-compatible.
@@ -684,6 +687,17 @@ impl MultiAgentToolMessages {
}
}
+/// Model-owned descriptions and parameters for the built-in MCP resource helpers.
+#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
+pub struct McpResourceToolMessages {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub list_mcp_resources: Option<ToolMessage>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub list_mcp_resource_templates: Option<ToolMessage>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub read_mcp_resource: Option<ToolMessage>,
+}
+
/// Model-owned instructions for Code Mode's exec and wait tools.
#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq, TS, JsonSchema)]
pub struct CodeModeToolMessages {