Let extensions attach metadata to MCP tool requests (#62435)

## What changed

Add `ToolLifecycleContributor::mcp_tool_request_meta` so an extension can
use thread and turn data and the captured tool registration to attach an
entry to the outgoing request's `_meta`. Codex rejects duplicate keys.
Expose the registering plugin's package ID in `McpToolContext` so
contributors can scope metadata to that plugin.

Export `PERSISTED_MCP_RESULT_MAX_BYTES`, the existing 64 KiB limit for
untruncated MCP results in durable history.

## Testing

Extend the multi-environment MCP scenario to check that only the call
for the selected plugin receives the metadata and that the result
callback sees the same plugin context.

GitOrigin-RevId: 25a2afc5402a5c9323de184313d614aede3692fb
This commit is contained in:
Oliver Tepman
2026-11-19 05:37:58 +00:00
committed by copyberry
parent 524e15989b
commit c764c44a05
6 changed files with 82 additions and 7 deletions
+23 -4
View File
@@ -553,6 +553,10 @@ async fn handle_approved_mcp_tool_call(
}
Ok(())
};
let mcp_tool = McpToolContext::from_prepared_call(
&prepared_call,
turn_context.config.mcp_servers.get().get(&server),
);
let result = async {
let result = async {
let result = prepared_call
@@ -702,6 +706,25 @@ async fn handle_approved_mcp_tool_call(
)
.await?;
}
for contributor in sess.services.extensions.tool_lifecycle_contributors() {
if let Some((key, value)) = contributor.mcp_tool_request_meta(
&sess.services.thread_extension_data,
&turn_context.extension_data,
&mcp_tool,
) {
let meta = request_meta
.get_or_insert_with(|| serde_json::json!({}))
.as_object_mut()
.ok_or_else(|| {
anyhow::anyhow!("missing MCP request metadata object")
})?;
anyhow::ensure!(
!meta.contains_key(key),
"MCP request metadata already contains {key}"
);
meta.insert(key.to_owned(), value);
}
}
Ok((rewritten_arguments, request_meta))
})
.await
@@ -735,10 +758,6 @@ async fn handle_approved_mcp_tool_call(
);
// Capture trusted server metadata before result callbacks or model-facing rewrites.
elicitation_type = mcp_tool_call_auth_elicitation_type(&server, connector_id, &result);
let mcp_tool = McpToolContext::from_prepared_call(
&prepared_call,
turn_context.config.mcp_servers.get().get(&server),
);
process_mcp_tool_result(
sess,
turn_context,
@@ -32,6 +32,33 @@ use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
struct NotesMetadata;
impl codex_extension_api::ToolLifecycleContributor for NotesMetadata {
fn mcp_tool_request_meta(
&self,
_thread: &codex_extension_api::ExtensionData,
_turn: &codex_extension_api::ExtensionData,
tool: &codex_extension_api::McpToolContext,
) -> Option<(&'static str, Value)> {
(tool.plugin_id.as_deref() == Some("env-a:notes")).then(|| ("x-notes-preview", json!(true)))
}
fn on_mcp_tool_result<'a>(
&'a self,
input: codex_extension_api::McpToolResultInput<'a>,
) -> codex_extension_api::ToolLifecycleFuture<'a> {
if input.call_id.starts_with("plugin-") {
assert_eq!(
self.mcp_tool_request_meta(input.thread_store, input.turn_store, input.mcp_tool)
.is_some(),
input.call_id == "plugin-first",
);
}
Box::pin(async {})
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn same_named_executor_mcps_keep_calls_and_approvals_separate() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -39,6 +66,7 @@ async fn same_named_executor_mcps_keep_calls_and_approvals_separate() -> Result<
let first_endpoint = start_mock_server().await;
let second_endpoint = start_mock_server().await;
let mut extensions = ExtensionRegistryBuilder::new();
extensions.tool_lifecycle_contributor(Arc::new(NotesMetadata));
codex_mcp_extension::install_plugins(
&mut extensions,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
@@ -146,7 +174,7 @@ async fn same_named_executor_mcps_keep_calls_and_approvals_separate() -> Result<
),
)?;
// Keep config-backed docs and add a separate plugin-backed server on each executor.
let plugin_root = home.path().join("notes");
let plugin_root = home.path().join("plugins/cache/market/notes/1.0.0");
fs::create_dir_all(plugin_root.join(".codex-plugin"))?;
fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
@@ -383,6 +411,15 @@ async fn same_named_executor_mcps_keep_calls_and_approvals_separate() -> Result<
] {
let calls = recorded_apps_tool_calls(endpoint).await;
assert_eq!(calls[2]["params"]["_meta"]["plugin_id"], plugin_id);
for call in &calls {
let title = call["params"]["arguments"]["title"].as_str();
assert_eq!(
call["params"]["_meta"]
.get("x-notes-preview")
.and_then(Value::as_bool),
(title == Some("plugin-first")).then_some(true),
);
}
assert_eq!(
calls
.iter()
@@ -468,6 +468,17 @@ pub trait ToolLifecycleContributor: Send + Sync {
Box::pin(std::future::ready(()))
}
/// Provides one private request metadata entry for an MCP call. Use the captured
/// registration to scope data to its intended recipient. Keys must be unique.
fn mcp_tool_request_meta(
&self,
_thread_store: &ExtensionData,
_turn_store: &ExtensionData,
_mcp_tool: &McpToolContext,
) -> Option<(&'static str, serde_json::Value)> {
None
}
/// Runs before the MCP result is sent to the client and model.
fn on_mcp_tool_result<'a>(&'a self, _input: McpToolResultInput<'a>) -> ToolLifecycleFuture<'a> {
Box::pin(std::future::ready(()))
@@ -65,6 +65,8 @@ pub enum McpToolSource {
pub struct McpToolContext {
tool: crate::McpToolInfo,
source: McpToolSource,
/// Package ID of the plugin that registered this call's MCP server.
pub plugin_id: Option<String>,
}
impl McpToolContext {
@@ -100,7 +102,11 @@ impl McpToolContext {
McpToolSource::Other
};
Self { tool, source }
Self {
tool,
source,
plugin_id: call.plugin_id().map(str::to_owned),
}
}
/// Returns frozen metadata for the exact model-visible MCP tool being executed.
+1
View File
@@ -149,6 +149,7 @@ pub use model_context::ModelContextScanProgress;
pub use persistence_metrics::RolloutPersistenceBatchMeasurement;
pub use persistence_metrics::RolloutPersistenceTelemetry;
pub use persistence_metrics::measure_and_filter_rollout_items;
pub use policy::PERSISTED_MCP_RESULT_MAX_BYTES;
pub use policy::into_persisted_rollout_items;
pub use policy::persisted_rollout_item;
pub use policy::persisted_rollout_items;
+2 -1
View File
@@ -13,7 +13,8 @@ use codex_protocol::protocol::ThreadHistoryMode;
use codex_utils_output_truncation::truncate_mcp_tool_result;
use codex_utils_string::truncate_middle_with_marker;
const PERSISTED_MCP_RESULT_MAX_BYTES: usize = 64 * 1024;
/// Maximum encoded size of an untruncated MCP result in durable history.
pub const PERSISTED_MCP_RESULT_MAX_BYTES: usize = 64 * 1024;
pub(super) const PERSISTED_COMMAND_OUTPUT_MAX_BYTES: usize = 64 * 1024;
const PERSISTED_COMMAND_OUTPUT_TRUNCATION_MARKER: &str =
"\n... command output truncated for persistence ...\n";