Recognize host-selected MCP handoffs in Guardian context (#65325)

## Why

Guardian uses native collaboration calls to identify which root-thread
context is relevant to a subagent. When an MCP server supplies those tools,
Guardian needs the server's registration to distinguish a handoff from an
unrelated call with the same name.

## What changed

Let the host opt in to handoff tracking for one local MCP plugin or extension
registration. Match the server name, source, and transport against the tool
registration used for routing. Persist the recipient of a matching direct
`spawn_agent`, `send_message`, or `followup_task` proposal so Guardian can
apply the handoff boundary when selecting context for that subagent.

Record a classification without a recipient for lookalike calls when needed
to prevent fallback to native name matching.

## Testing

Cover context filtering for the selected extension, calls without host
opt-in, and a configured MCP server using the native collaboration namespace.

GitOrigin-RevId: 40471f3cdfde88832c27c3a466e36723e42515d2
This commit is contained in:
rhan-oai
2026-12-02 20:09:58 +00:00
committed by copyberry
parent 587c151188
commit ea5f6b303c
11 changed files with 310 additions and 20 deletions
+1
View File
@@ -83,6 +83,7 @@ mod residency;
pub use residency::ThreadEvictionOutcome;
mod resume;
mod root_handoff;
pub(crate) use root_handoff::guardian_mcp_handoff;
mod runtime;
mod runtime_context;
mod sender_context;
@@ -1,7 +1,11 @@
//! Best-effort handoff windows plus recent root context, without saved handoff state.
//! Best-effort handoff windows plus recent root context.
//! History position approximates dispatch order; absent calls leave the existing context unchanged.
//! User inputs bypass relevance filtering; only assistant context is narrowed.
use crate::agent::host::GuardianMcpHandoffRecipient;
use crate::session::session::Session;
use crate::session::step_context::StepContext;
use codex_history::GuardianMcpHandoff;
use codex_history::ResponseItemEnvelope;
use codex_history::RetainedContextOrder;
use codex_protocol::AgentPath;
@@ -41,6 +45,19 @@ pub(super) fn handoffs(
let Some(boundary) = preceding_order else {
continue;
};
if let Some(handoff) = envelope
.metadata
.as_ref()
.and_then(|metadata| metadata.guardian_mcp_handoff.as_ref())
{
if let Some(recipient) = &handoff.recipient {
handoffs.push(RootHandoff {
recipient: recipient.clone(),
boundary,
});
}
continue;
}
if let ResponseItem::FunctionCall {
name,
namespace,
@@ -102,17 +119,77 @@ pub(super) fn handoff_boundaries(
}
fn recipient(name: &str, args: &serde_json::Value) -> Option<AgentPath> {
let name = name
.strip_prefix("collaboration.")
exact_recipient(native_handoff_name(name), args)
}
fn native_handoff_name(name: &str) -> &str {
name.strip_prefix("collaboration.")
.or_else(|| name.strip_prefix("collaboration__"))
.unwrap_or(name);
let field = match name {
"spawn_agent" => "task_name",
"send_message" | "followup_task" => "target",
_ => return None,
};
.unwrap_or(name)
}
fn exact_recipient(name: &str, args: &serde_json::Value) -> Option<AgentPath> {
let field = handoff_argument(name)?;
args[field]
.as_str()
.and_then(|target| AgentPath::root().resolve(target).ok())
.filter(|path| !path.is_root())
}
fn handoff_argument(name: &str) -> Option<&'static str> {
match name {
"spawn_agent" => Some("task_name"),
"send_message" | "followup_task" => Some("target"),
_ => None,
}
}
/// Record proposed direct calls using the same immutable tool plan that routes them.
pub(crate) fn guardian_mcp_handoff(
sess: &Session,
step: &StepContext,
item: &ResponseItem,
) -> Option<GuardianMcpHandoff> {
let ResponseItem::FunctionCall {
name,
namespace,
arguments,
..
} = item
else {
return None;
};
let opt_in = sess
.services
.thread_extension_data
.get::<GuardianMcpHandoffRecipient>();
if opt_in.is_none() && !step.turn.config.multi_agent_v2.disable_native_tools {
return None;
}
let info = step
.tool_router
.registered_tool(&ToolName::new(namespace.clone(), name.clone()))
.and_then(|tool| tool.runtime.mcp_tool_info());
if handoff_argument(native_handoff_name(name)).is_none()
&& info.is_none_or(|info| handoff_argument(&info.tool.name).is_none())
{
return None;
}
let args = serde_json::from_str(arguments).ok()?;
let Some(info) = info else {
return (step.turn.config.multi_agent_v2.disable_native_tools
&& recipient(name, &args).is_some())
.then_some(GuardianMcpHandoff { recipient: None });
};
let target = exact_recipient(&info.tool.name, &args);
if target.is_none() && recipient(name, &args).is_none() {
return None;
}
Some(GuardianMcpHandoff {
recipient: target.filter(|_| {
opt_in.is_some_and(|opt_in| {
opt_in.matches(info.server_key(), &step.mcp.config().mcp_server_catalog)
})
}),
})
}
+25 -1
View File
@@ -1,4 +1,4 @@
//! Bind private agent attribution to one host-selected MCP plugin registration.
//! Bind agent metadata and Guardian handoffs to host-selected MCP registrations.
use codex_config::McpServerTransportConfig;
use codex_mcp::McpServerKey;
@@ -37,6 +37,30 @@ impl AgentMcpMetadataRecipient {
}
}
/// Install in thread extension data to recognize direct Guardian handoffs from
/// one exact host-selected MCP plugin or extension registration. Transport may
/// contain credentials and must not be logged.
#[derive(Clone)]
pub struct GuardianMcpHandoffRecipient {
pub server_name: String,
pub source: McpServerSource,
pub transport: McpServerTransportConfig,
}
impl GuardianMcpHandoffRecipient {
pub(crate) fn matches(&self, server_key: &McpServerKey, catalog: &ResolvedMcpCatalog) -> bool {
matches!(
self.source,
McpServerSource::Plugin(_) | McpServerSource::Extension { .. }
) && catalog.server(server_key).is_some_and(|registration| {
registration.name() == self.server_name
&& registration.config().is_local_environment()
&& registration.source() == &self.source
&& registration.config().transport == self.transport
})
}
}
#[cfg(test)]
#[path = "mcp_metadata_tests.rs"]
mod tests;
@@ -1,10 +1,12 @@
#![cfg(test)]
use super::AgentMcpMetadataRecipient;
use super::GuardianMcpHandoffRecipient;
use codex_config::McpServerConfig;
use codex_mcp::McpPluginAttribution;
use codex_mcp::McpServerKey;
use codex_mcp::McpServerRegistration;
use codex_mcp::McpServerSource;
use codex_mcp::ResolvedMcpCatalog;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
@@ -17,6 +19,7 @@ use serde_json::json;
#[test_case::test_case("endpoint", false)]
#[test_case::test_case("environment", false)]
#[test_case::test_case("config_source", false)]
#[test_case::test_case("extension_contributor", false)]
fn agent_context_requires_the_exact_captured_recipient(mismatch: &str, expected: bool) {
let mut config: McpServerConfig = serde_json::from_value(json!({
"url": "https://coordinator.example/mcp"
@@ -28,6 +31,21 @@ fn agent_context_requires_the_exact_captured_recipient(mismatch: &str, expected:
server_name: "agents".into(),
transport: config.transport.clone(),
};
let guardian_recipient = GuardianMcpHandoffRecipient {
server_name: recipient.server_name.clone(),
source: if mismatch == "extension_contributor" {
McpServerSource::Extension {
id: "expected".into(),
host_owned_apps: false,
}
} else {
McpServerSource::Plugin(
McpPluginAttribution::new(recipient.plugin_id.clone(), "Agents".into())
.with_host_root(recipient.plugin_root.clone()),
)
},
transport: recipient.transport.clone(),
};
let mut plugin_id = recipient.plugin_id.clone();
let mut root = recipient.plugin_root.clone();
let mut name = recipient.server_name.clone();
@@ -42,15 +60,22 @@ fn agent_context_requires_the_exact_captured_recipient(mismatch: &str, expected:
.expect("replacement server config")
}
"environment" => config.environment_id = "remote".into(),
"exact" | "config_source" => {}
"exact" | "config_source" | "extension_contributor" => {}
_ => panic!("unknown mismatch"),
}
let key = if mismatch == "config_source" {
let key = if matches!(mismatch, "config_source" | "extension_contributor") {
McpServerKey::unscoped(&name)
} else {
McpServerKey::in_environment(&config.environment_id, &name)
};
let registration = if mismatch == "config_source" {
let registration = if mismatch == "extension_contributor" {
McpServerRegistration::from_extension(
name,
"unexpected",
/*contribution_order*/ 0,
config,
)
} else if mismatch == "config_source" {
McpServerRegistration::from_config(name, config)
} else {
McpServerRegistration::from_plugin(
@@ -62,5 +87,7 @@ fn agent_context_requires_the_exact_captured_recipient(mismatch: &str, expected:
};
let mut builder = ResolvedMcpCatalog::builder();
builder.register(registration);
assert_eq!(recipient.matches(&key, &builder.build()), expected);
let catalog = builder.build();
assert_eq!(recipient.matches(&key, &catalog), expected);
assert_eq!(guardian_recipient.matches(&key, &catalog), expected);
}
+1
View File
@@ -21,6 +21,7 @@ pub(crate) use invocation::create;
pub(crate) use invocation::prepare;
pub(crate) use invocation::tool_invocation;
pub use mcp_metadata::AgentMcpMetadataRecipient;
pub use mcp_metadata::GuardianMcpHandoffRecipient;
pub use ownership::AgentRuntimeOwnership;
pub(crate) use ownership::AgentRuntimeServices;
pub use service_tier::AgentServiceTier;
+1
View File
@@ -182,6 +182,7 @@ pub use agent::host::AgentTurnAdmissionRequest;
pub use agent::host::AgentTurnOutcomeReporter;
pub use agent::host::AgentUsageAccounting;
pub use agent::host::AgentUsageReport;
pub use agent::host::GuardianMcpHandoffRecipient;
pub use agent::host::HostThreadSpawnReservation;
pub use agent::host::HostToolInvocationLookup;
pub use agent::host::InheritedSessionId;
+10 -6
View File
@@ -97,17 +97,21 @@ pub(crate) async fn record_completed_response_item_with_finalized_facts(
finalized_facts: Option<&FinalizedTurnItemFacts>,
) {
let turn_context = &step_context.turn;
let mut metadata = step_context
.sampled_through_sequence
.map(|sequence| CodexHarnessMetadata {
sampled_through_sequence: Some(sequence),
..Default::default()
});
if let Some(handoff) = crate::agent::control::guardian_mcp_handoff(sess, step_context, item) {
metadata.get_or_insert_default().guardian_mcp_handoff = Some(handoff);
}
sess.record_annotated_conversation_items(
turn_context,
&step_context.settings.model_info,
vec![ResponseItemEnvelope {
item: item.clone(),
metadata: step_context
.sampled_through_sequence
.map(|sequence| CodexHarnessMetadata {
sampled_through_sequence: Some(sequence),
..Default::default()
}),
metadata,
}],
)
.await;
@@ -10,6 +10,7 @@ use std::time::Duration;
use codex_api::AuthError;
use codex_config::McpServerConfig;
use codex_core::GuardianMcpHandoffRecipient;
use codex_core::StartThreadOptions;
use codex_core::TurnInputRequest;
use codex_core::config::Config;
@@ -22,6 +23,7 @@ use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_features::Feature;
use codex_guardian_context::GuardianRootMessage;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_mcp::McpServerExposure;
use codex_mcp::McpServerKey;
@@ -32,6 +34,7 @@ use codex_mcp::McpToolRequestMetaHook;
use codex_mcp::McpToolRequestMetaProvider;
use codex_mcp::ReadResourceRequestParams;
use codex_mcp::ResolvedMcpCatalog;
use codex_protocol::AgentPath;
use codex_protocol::ThreadId;
use codex_protocol::approvals::ElicitationRequest;
use codex_protocol::mcp::ClientMcpExtensions;
@@ -79,6 +82,143 @@ impl McpServerContributor<Config> for ExtensionServers {
}
}
#[derive(Clone, Copy)]
enum GuardianHandoffCase {
Approved,
NoOptIn,
NativeNamespaceSpoof,
}
#[test_case(GuardianHandoffCase::Approved; "approved extension")]
#[test_case(GuardianHandoffCase::NoOptIn; "no host opt-in")]
#[test_case(GuardianHandoffCase::NativeNamespaceSpoof; "config registration spoofing native namespace")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn guardian_handoff_requires_the_selected_extension_registration(
case: GuardianHandoffCase,
) -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let calls = Arc::new(AtomicUsize::new(0));
core_test_support::hooks::mount_hook_mcp(&server, "guardian_fixture", &["send_message"], {
let calls = calls.clone();
move |params| {
assert_eq!(params["arguments"]["target"], "/root/alpha");
calls.fetch_add(1, Ordering::SeqCst);
json!({"content": []})
}
})
.await;
let mcp: McpServerConfig = serde_json::from_value(
json!({"url": format!("{}/repl", server.uri()), "default_tools_approval_mode": "approve"}),
)?;
let spoof = matches!(case, GuardianHandoffCase::NativeNamespaceSpoof);
let unprefixed = !matches!(case, GuardianHandoffCase::Approved);
let (server_name, namespace) = if unprefixed {
("collaboration", "collaboration")
} else {
("sample", "mcp__sample")
};
let mut extensions = ExtensionRegistryBuilder::new();
if !spoof {
extensions.mcp_server_contributor(Arc::new(ExtensionServers(vec![
McpServerContribution::Set {
name: server_name.into(),
config: Box::new(mcp.clone()),
},
])));
}
let config_mcp = mcp.clone();
let fixture = test_codex()
.with_extensions(Arc::new(extensions.build()))
.with_config(move |config| {
config
.features
.enable(Feature::GuardianRootHandoffContext)
.expect("enable Guardian handoff filtering");
config.multi_agent_v2.disable_native_tools = true;
if unprefixed {
config
.features
.enable(Feature::NonPrefixedMcpToolNames)
.expect("enable non-prefixed MCP names");
config.non_prefixed_mcp_tool_servers = Some(vec![server_name.into()]);
}
if spoof {
config
.mcp_servers
.set(HashMap::from([(server_name.into(), config_mcp)]))
.expect("set config server");
}
})
.build_with_auto_env(&server)
.await?;
if !matches!(case, GuardianHandoffCase::NoOptIn) {
fixture
.codex
.thread_extension_data()
.insert(GuardianMcpHandoffRecipient {
server_name: server_name.into(),
source: McpServerSource::Extension {
id: "apps_protocol_test".into(),
host_owned_apps: false,
},
transport: mcp.transport,
});
}
wait_for_mcp_server(&fixture.codex, server_name).await?;
let mut context = [
"unrelated context",
"earlier context",
"recent context",
"handoff context",
]
.into_iter()
.enumerate()
.map(|(i, text)| responses::ev_assistant_message(&format!("ctx-{i}"), text))
.collect::<Vec<_>>();
context.push(responses::ev_completed("context"));
let mut handoff = vec![responses::ev_function_call_with_namespace(
"handoff",
namespace,
"send_message",
r#"{"target":"/root/alpha","message":"Review this."}"#,
)];
if spoof {
handoff.push(responses::ev_function_call_with_namespace(
"unregistered",
namespace,
"followup_task",
r#"{"target":"/root/alpha","message":"Review this."}"#,
));
}
handoff.push(responses::ev_completed("calls"));
responses::mount_sse_sequence(
&server,
vec![
responses::sse(context),
responses::sse(handoff),
responses::sse(vec![
responses::ev_assistant_message("done", "done"),
responses::ev_completed("end"),
]),
],
)
.await;
fixture.submit_turn("Prepare context").await?;
fixture.submit_turn("Send the message").await?;
assert_eq!(calls.load(Ordering::SeqCst), 1);
let evidence = fixture.codex.capture_guardian_root_evidence().await?;
let unrelated = GuardianRootMessage::Assistant("unrelated context".into());
let alpha = evidence.project(&AgentPath::try_from("/root/alpha").expect("valid path"))?;
let beta = evidence.project(&AgentPath::try_from("/root/beta").expect("valid path"))?;
assert!(beta.messages.contains(&unrelated));
assert_eq!(
alpha.messages.contains(&unrelated),
!matches!(case, GuardianHandoffCase::Approved)
);
Ok(())
}
async fn mcp_methods(server: &MockServer) -> Vec<String> {
server
.received_requests()
+11
View File
@@ -67,6 +67,13 @@ pub struct ResponseItemEnvelope {
pub metadata: Option<CodexHarnessMetadata>,
}
/// A direct MCP handoff proposal; only a host-selected registration has a recipient.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
pub struct GuardianMcpHandoff {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recipient: Option<codex_protocol::AgentPath>,
}
/// Metadata owned by the Codex harness and persisted with a response item.
///
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
@@ -103,6 +110,10 @@ pub struct CodexHarnessMetadata {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub guardian_review_ids: Vec<codex_protocol::ResponseItemId>,
/// Direct MCP handoff classification, persisted with the call and never model-visible.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub guardian_mcp_handoff: Option<GuardianMcpHandoff>,
/// This complete message delivered the meaning of retained source-order labels.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub guardian_source_order_guidance: bool,
+4
View File
@@ -518,6 +518,7 @@ fn delivered_assistant_rollout_survives_an_earlier_read_and_rewrite() -> Result<
/// Keeps harness metadata beside, rather than inside, response-item payloads.
fn response_item_envelope_stores_metadata_beside_rollout_payload() -> Result<()> {
let response_item = response_message("developer");
let handoff = GuardianMcpHandoff { recipient: None };
let line = RolloutLine {
timestamp: "2025-01-03T12:00:00.000Z".to_string(),
ordinal: Some(7),
@@ -526,6 +527,7 @@ fn response_item_envelope_stores_metadata_beside_rollout_payload() -> Result<()>
metadata: Some(CodexHarnessMetadata {
history_sequence: Some(9),
sampled_through_sequence: Some(7),
guardian_mcp_handoff: Some(handoff.clone()),
client_authored: true,
history_truncation_token_limit: Some(20_000),
inherited_user_message: true,
@@ -545,6 +547,7 @@ fn response_item_envelope_stores_metadata_beside_rollout_payload() -> Result<()>
"metadata": {
"history_sequence": 9,
"sampled_through_sequence": 7,
"guardian_mcp_handoff": {},
"client_authored": true,
"fallback_token_limit_override": 20_000,
"inherited_user_message": true,
@@ -562,6 +565,7 @@ fn response_item_envelope_stores_metadata_beside_rollout_payload() -> Result<()>
Some(CodexHarnessMetadata {
history_sequence: Some(9),
sampled_through_sequence: Some(7),
guardian_mcp_handoff: Some(handoff),
client_authored: true,
history_truncation_token_limit: Some(20_000),
inherited_user_message: true,