Continue MCP callback traces into Guardian reviews (#65254)

## Why

When a Node REPL-backed MCP tool requests approval through an elicitation
callback, the trace loses the parent-child relationship between the callback
and the Guardian review.

## What changed

Parent the Guardian review span to the callback span when its
`traceparent` is well formed and its trace ID matches the active tool
invocation. Preserve the invocation's sampling flags and `tracestate`,
and strip both trace fields from the elicitation metadata before it
reaches approval handling or user prompts.

## Testing

Cover callback span parenting and trace propagation to Guardian inference,
including rejection of unrelated trace IDs and malformed headers. Verify
that form and URL prompts retain other metadata while dropping trace fields.

GitOrigin-RevId: 942b61a0da81b5d549c9f4813b28101bba622a26
This commit is contained in:
Ben Romano
2026-12-02 13:21:09 +00:00
committed by copyberry
parent 76d282ae2e
commit ba4148faaf
12 changed files with 246 additions and 45 deletions
+6 -1
View File
@@ -59,6 +59,8 @@ pub struct ElicitationReviewRequest {
pub server_name: String,
pub request_id: RequestId,
pub elicitation: Elicitation,
/// W3C parent carried by the callback, kept separate from the approval payload.
pub traceparent: Option<String>,
}
pub trait ElicitationReviewer: Send + Sync {
@@ -437,13 +439,14 @@ impl ElicitationRequestManager {
.is_some_and(Value::is_object);
let router = self.router.clone();
let authority = self.authority.clone();
Box::new(move |id, elicitation| {
Box::new(move |id, mut elicitation| {
let router = router.clone();
let tx_event = tx_event.clone();
let server_name = server_name.clone();
let server_key = server_key.clone();
let authority = authority.clone();
async move {
let traceparent = elicitation.take_traceparent();
let authority = authority
.lock()
.ok()
@@ -538,6 +541,7 @@ impl ElicitationRequestManager {
server_name,
request_id: id,
elicitation,
traceparent,
})
.await
{
@@ -617,6 +621,7 @@ impl ElicitationRequestManager {
server_name: server_name.clone(),
request_id: id.clone(),
elicitation: elicitation.clone(),
traceparent,
};
if let Some(response) = reviewer.review(request).await? {
return Ok(response);
+7
View File
@@ -1355,6 +1355,7 @@ pub(crate) struct McpToolApprovalMetadata {
pub(crate) struct McpToolApprovalContext {
pub(crate) invocation: Option<McpInvocation>,
pub(crate) invocation_trace: Option<codex_otel::SpanLink>,
pub(crate) metadata: McpToolApprovalMetadata,
pub(crate) review_context: GuardianReviewContext,
pub(crate) requested_reviewer: ApprovalsReviewer,
@@ -1391,6 +1392,12 @@ impl Session {
invocation: (invocation.server == CODEX_APPS_MCP_SERVER_NAME
|| is_node_repl_backed_server(&invocation.server))
.then(|| invocation.clone()),
invocation_trace: is_node_repl_backed_connector(
&invocation.server,
metadata.connector_id.as_deref(),
)
.then(|| codex_otel::SpanLink::capture(&Span::current()))
.flatten(),
metadata,
review_context,
requested_reviewer,
+23 -3
View File
@@ -1092,18 +1092,27 @@ async fn review_guardian_mcp_elicitation(
// The invocation identifies the tool event, but a nested elicitation can
// review a different action and connector than the enclosing JavaScript.
let (originating_call_id, guardian_scope) = if let Some(call_id) = call_id
let (originating_call_id, guardian_scope, invocation_trace) = if let Some(call_id) = call_id
&& let Some(McpToolApprovalContext {
invocation: Some(invocation),
invocation_trace,
metadata,
..
}) = approval_context.as_deref()
&& invocation.server == request.server_name
&& is_node_repl_backed_connector(&invocation.server, metadata.connector_id.as_deref())
{
(Some(call_id), GuardianScope::ComputerUse)
(
Some(call_id),
GuardianScope::ComputerUse,
invocation_trace.as_ref(),
)
} else {
(None, GuardianScope::for_mcp_server(&request.server_name))
(
None,
GuardianScope::for_mcp_server(&request.server_name),
None,
)
};
let require_synchronous_review = approval_context.is_none()
@@ -1324,6 +1333,16 @@ async fn review_guardian_mcp_elicitation(
*prompt_permissions = Some(permissions);
}
let declined_reason = guardian_request.request.as_ref().err().cloned();
let review_span = if let Some(invocation) = invocation_trace
&& let Some(traceparent) = request.traceparent.as_deref()
&& let Some(parent) = invocation.verified_callback_parent(traceparent)
{
let span = info_span!("guardian.mcp.elicitation");
codex_otel::set_parent_from_context(&span, parent);
span
} else {
tracing::Span::none()
};
// Release the registry entry before awaiting review. The tool owns its lifetime.
drop(approval_context);
let decision = crate::guardian::decide_approval(
@@ -1343,6 +1362,7 @@ async fn review_guardian_mcp_elicitation(
require_synchronous_review,
},
)
.instrument(review_span)
.await;
Ok(decision.map(|decision| {
if let Some(reason) = declined_reason {
+1
View File
@@ -9755,6 +9755,7 @@ async fn mcp_elicitation_reviewer_uses_active_reviewer_and_latest_runtime_policy
server_name: "browser-use".to_string(),
server_key: McpServerKey::unscoped("browser-use"),
request_id: rmcp::model::NumberOrString::Number(7),
traceparent: None,
elicitation: codex_rmcp_client::Elicitation::Mcp(
rmcp::model::ElicitRequestParams::FormElicitationParams {
meta: Some(rmcp::model::RequestMetaObject::from(
+23
View File
@@ -7,6 +7,29 @@ use tracing::dispatcher::DefaultGuard;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
/// Runs this libtest case alone so its process-wide subscriber sees worker spans.
/// Returns true in the parent once the child has passed. The child runs the test body.
pub async fn run_in_trace_subprocess() -> anyhow::Result<bool> {
const CHILD: &str = "CODEX_TRACE_TEST_CHILD";
if std::env::var_os(CHILD).is_some() {
return Ok(false);
}
let thread = std::thread::current();
let name = thread.name().context("libtest case name")?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args(["--exact", name])
.env(CHILD, "1")
.output()
.await?;
let stdout = String::from_utf8_lossy(&output.stdout);
anyhow::ensure!(
output.status.success() && stdout.contains("1 passed"),
"isolated {name} failed: {stdout}{}",
String::from_utf8_lossy(&output.stderr)
);
Ok(true)
}
/// Receives named trace events on a test's current-thread runtime.
pub struct NamedTraceEvents {
events: tokio::sync::mpsc::UnboundedReceiver<()>,
+1
View File
@@ -2973,6 +2973,7 @@ ZDOTDIR = "{}"
EnvironmentVariablePattern::new_case_insensitive("EXCLUDED_SETTING"),
);
if request_extra_permissions {
config.approvals_reviewer = ApprovalsReviewer::User;
config
.features
.enable(Feature::ExecPermissionApprovals)
@@ -23,6 +23,7 @@ use codex_protocol::protocol::GuardianAssessmentStatus;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::protocol::TurnEnvironmentRequests;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::apps_test_server::apps_enabled_builder;
@@ -34,10 +35,15 @@ use core_test_support::skip_if_wine_exec;
use core_test_support::test_codex::local_request;
use core_test_support::test_codex::local_requests;
use core_test_support::test_codex::test_codex;
use core_test_support::tracing::run_in_trace_subprocess;
use core_test_support::wait_for_event;
use core_test_support::wait_for_mcp_server;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
use opentelemetry_sdk::metrics::data::MetricData;
use opentelemetry_sdk::propagation::TraceContextPropagator;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
@@ -46,6 +52,8 @@ use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use test_case::test_case;
use tracing::Instrument;
use tracing_subscriber::prelude::*;
use wiremock::matchers::body_partial_json;
// The tool itself needs no approval. Its server requests a separate Guardian
@@ -101,6 +109,12 @@ for line in sys.stdin:
if len(sys.argv) > 2 and sys.argv[2] in ("forward", "browser", "rewrite"):
key = "_codex_apps" if browser else "callId"
invocation_meta[key] = request["params"]["_meta"][key]
if parent := request["params"]["_meta"].get("traceparent"):
invocation_meta["traceparent"] = (
f"00-{parent.split('-')[1]}-2222222222222222-00" if index == 0
else "00-33333333333333333333333333333333-4444444444444444-01"
)
invocation_meta["tracestate"] = "vendor=callback"
pending_elicitations.append({
"id": f"server-approval-{index}" if multiple else "server-approval",
"method": "elicitation/create", "params": {
@@ -635,7 +649,6 @@ enum NestedApprovalContext {
#[test_case("codex_apps", false, CallIdSource::Host; "browser_connector")]
#[test_case("codex_apps", true, CallIdSource::Host; "strict_browser_connector")]
#[test_case("node_repl", true, CallIdSource::Host; "strict_node_repl")]
#[test_case("cua_repl", false, CallIdSource::Host; "ordinary_cua_repl")]
#[test_case("cua_repl", true, CallIdSource::Host; "strict_cua_repl")]
#[test_case("node_repl", false, CallIdSource::Missing; "missing_call_id")]
@@ -683,6 +696,72 @@ pub(super) async fn nested_elicitation_request_history() -> Result<Vec<Responses
.await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn guardian_inference_continues_the_verified_node_elicitation_trace() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_wine_exec!(Ok(()), "the MCP fixture requires a host Python interpreter");
if run_in_trace_subprocess().await? {
return Ok(());
}
opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
let exported = InMemorySpanExporter::default();
let telemetry = SdkTracerProvider::builder()
.with_simple_exporter(exported.clone())
.build();
tracing_subscriber::registry()
.with(tracing_opentelemetry::layer().with_tracer(telemetry.tracer("guardian-elicitation")))
.try_init()?;
let trace_id = "11111111111111111111111111111111";
let turn = tracing::info_span!("browser_turn");
assert!(codex_otel::set_parent_from_w3c_trace_context(
&turn,
&W3cTraceContext {
traceparent: Some(format!("00-{trace_id}-1111111111111111-01")),
tracestate: Some("vendor=original".to_string()),
}
));
let requests = assert_nested_elicitation_reviews(
"node_repl",
/*strict_auto_review*/ true,
CallIdSource::Host,
NestedApprovalContext::Enabled,
)
.instrument(turn)
.await?;
let reviews = requests
.iter()
.filter(|request| request.header("x-openai-subagent").as_deref() == Some("guardian"))
.collect::<Vec<_>>();
let [verified, unrelated] = reviews.as_slice() else {
anyhow::bail!("expected two Guardian requests");
};
let parent = verified
.header("traceparent")
.context("Guardian inference traceparent")?;
assert!(parent.starts_with(&format!("00-{trace_id}-")));
assert!(parent.ends_with("-01"));
assert_eq!(
verified.header("tracestate").as_deref(),
Some("vendor=original")
);
assert!(
!unrelated
.header("traceparent")
.is_some_and(|parent| parent.contains("33333333333333333333333333333333"))
);
let parents = exported
.get_finished_spans()?
.into_iter()
.filter(|span| span.name == "guardian.mcp.elicitation")
.map(|span| format!("{}-{}", span.span_context.trace_id(), span.parent_span_id))
.collect::<Vec<_>>();
assert_eq!(parents, [format!("{trace_id}-2222222222222222")]);
Ok(())
}
async fn assert_nested_elicitation_reviews(
server_name: &str,
strict_auto_review: bool,
@@ -785,8 +864,8 @@ async fn assert_nested_elicitation_reviews(
let test = builder.build_with_remote_and_local_env(&server).await?;
wait_for_mcp_server(&test.codex, server_name).await?;
let attributed = call_id_source == CallIdSource::Host && server_name != "elicitation";
let capture_history = attributed && server_name == "node_repl" && !strict_auto_review;
if capture_history
let capture_history = attributed && server_name == "node_repl";
if (capture_history && !strict_auto_review)
|| matches!(
call_id_source,
CallIdSource::WrongServer | CallIdSource::PreviousTurn
@@ -1137,11 +1216,15 @@ async fn user_review_preserves_unsupported_guardian_elicitations(mode: &str) ->
} else {
json!({"requestedSchema": form_schema})
};
let meta = json!({
"traceparent": "00-11111111111111111111111111111111-2222222222222222-01",
"tracestate": "vendor=callback",
});
let mcp_servers = serde_json::from_value(json!({
"elicitation": {
"command": if cfg!(windows) { "python" } else { "python3" },
"cwd": std::env::current_dir()?,
"args": ["-u", "-c", ELICITATION_SERVER, "{}", "", params.to_string()],
"args": ["-u", "-c", ELICITATION_SERVER, meta.to_string(), "", params.to_string()],
"default_tools_approval_mode": "approve",
}
}))?;
@@ -1201,17 +1284,25 @@ async fn user_review_preserves_unsupported_guardian_elicitations(mode: &str) ->
let EventMsg::ElicitationRequest(request) = event else {
panic!("expected a user elicitation, got {event:?}");
};
match &request.request {
let meta = match &request.request {
codex_protocol::approvals::ElicitationRequest::Form {
requested_schema, ..
requested_schema,
meta,
..
} => {
assert_eq!(requested_schema, &form_schema);
meta
}
codex_protocol::approvals::ElicitationRequest::Url { url, .. } => {
codex_protocol::approvals::ElicitationRequest::Url { url, meta, .. } => {
assert_eq!(url, "https://example.com/approve");
meta
}
other => panic!("unexpected elicitation: {other:?}"),
}
};
let meta = meta.as_ref().context("elicitation metadata")?;
assert_eq!(meta["tool_name"], "write_record");
assert!(meta.get("traceparent").is_none());
assert!(meta.get("tracestate").is_none());
test.codex
.submit(Op::ResolveElicitation {
server_name: request.server_name,
+2 -28
View File
@@ -20,6 +20,7 @@ use core_test_support::responses::mount_sse_once;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::test_codex;
use core_test_support::tracing::run_in_trace_subprocess;
use core_test_support::wait_for_event;
use opentelemetry::KeyValue;
use opentelemetry::trace::TracerProvider as _;
@@ -30,11 +31,8 @@ use opentelemetry_sdk::trace::SpanData;
use pretty_assertions::assert_eq;
use std::time::Duration;
use test_case::test_case;
use tokio::process::Command;
use tracing_subscriber::prelude::*;
const SUBPROCESS_ENV_VAR: &str = "CODEX_TURN_PHASE_TRACE_TEST_SUBPROCESS";
fn attribute(attributes: &[KeyValue], key: &str) -> Option<String> {
attributes
.iter()
@@ -72,31 +70,7 @@ async fn steer_joins_existing_turn_without_extending_sampling(
finish: Finish,
critical_path_timing: bool,
) -> anyhow::Result<()> {
if std::env::var_os(SUBPROCESS_ENV_VAR).is_none() {
let case = match finish {
Finish::Reply => "reply",
Finish::Interrupt => "interrupt",
};
let capture = if critical_path_timing {
"enabled"
} else {
"disabled"
};
let test_name = format!(
"suite::turn_phase_trace::steer_joins_existing_turn_without_extending_sampling::{case}_{capture}"
);
let output = Command::new(std::env::current_exe()?)
.arg("--exact")
.arg(&test_name)
.env(SUBPROCESS_ENV_VAR, "1")
.output()
.await?;
assert!(
output.status.success(),
"subprocess test `{test_name}` failed\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
if run_in_trace_subprocess().await? {
return Ok(());
}
@@ -35,6 +35,7 @@ fn form_request(meta: Option<RequestMetaObject>) -> ElicitationReviewRequest {
server_name: "browser-use".to_string(),
server_key: McpServerKey::unscoped("browser-use"),
request_id: rmcp::model::NumberOrString::Number(7),
traceparent: None,
elicitation: Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
meta,
message: "Allow origin?".to_string(),
@@ -114,6 +115,7 @@ fn guardian_elicitation_review_request_declines_unsupported_opt_in_shapes() {
server_name: "browser-use".to_string(),
server_key: McpServerKey::unscoped("browser-use"),
request_id: rmcp::model::NumberOrString::Number(8),
traceparent: None,
elicitation: Elicitation::Mcp(rmcp::model::ElicitRequestParams::UrlElicitationParams {
meta: guardian_meta(Some(json!({}))),
message: "Open URL".to_string(),
@@ -130,6 +132,7 @@ fn guardian_elicitation_review_request_declines_unsupported_opt_in_shapes() {
server_name: "browser-use".to_string(),
server_key: McpServerKey::unscoped("browser-use"),
request_id: rmcp::model::NumberOrString::Number(9),
traceparent: None,
elicitation: Elicitation::Mcp(rmcp::model::ElicitRequestParams::FormElicitationParams {
meta: guardian_meta(Some(json!({}))),
message: "Allow origin?".to_string(),
@@ -0,0 +1,26 @@
#![cfg(test)]
//! Checks which callback headers can supply a parent for a live invocation.
use super::SpanLink;
use super::context_from_trace_headers;
use opentelemetry::trace::TraceContextExt;
#[test]
fn callback_ids_must_be_full_width_even_when_they_parse_to_the_same_number() {
let valid = "00-00000000000000000000000000000001-0000000000000002-01";
let context = context_from_trace_headers(Some(valid), /*tracestate*/ None).unwrap();
let invocation = SpanLink(context.span().span_context().clone());
assert!(invocation.verified_callback_parent(valid).is_some());
for malformed in [
"00-00000000000000000000000000000001-2-01",
"00-1-0000000000000002-01",
"00-00000000000000000000000000000001-+000000000000002-01",
"00-00000000000000000000000000000001-0000000000000002-01-",
] {
assert!(
invocation.verified_callback_parent(malformed).is_none(),
"{malformed}"
);
}
}
+36
View File
@@ -31,6 +31,38 @@ static TRACESTATE_ENTRIES: OnceLock<RwLock<BTreeMap<String, BTreeMap<String, Str
pub struct SpanLink(SpanContext);
impl SpanLink {
/// Trust only the callback's span ID, and only within the captured trace.
pub fn verified_callback_parent(&self, traceparent: &str) -> Option<Context> {
// OpenTelemetry parses IDs as numbers and silently zero-pads short IDs.
// Check the wire format before letting it interpret the parent.
let mut fields = traceparent.split('-');
for width in [2, 32, 16, 2] {
let field = fields.next()?;
if field.len() != width
|| !field
.bytes()
.all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
{
return None;
}
}
if traceparent.starts_with("00-") && fields.next().is_some() {
return None;
}
let callback = context_from_trace_headers(Some(traceparent), /*tracestate*/ None)?;
let span = callback.span();
let parent = span.span_context();
(self.0.trace_id() == parent.trace_id()).then(|| {
Context::new().with_remote_span_context(SpanContext::new(
self.0.trace_id(),
parent.span_id(),
self.0.trace_flags(),
/*is_remote*/ true,
self.0.trace_state().clone(),
))
})
}
/// Captures the span's own context if OpenTelemetry assigned it valid IDs.
pub fn capture(span: &Span) -> Option<Self> {
let context = span.context();
@@ -355,6 +387,10 @@ fn merge_tracestate_member_fields(
fields.join(";")
}
#[cfg(test)]
#[path = "callback_parent_tests.rs"]
mod callback_parent_tests;
#[cfg(test)]
mod tests {
use super::context_from_trace_headers;
+19 -5
View File
@@ -410,14 +410,28 @@ pub enum Elicitation {
}
impl Elicitation {
pub fn meta(&self) -> Option<&serde_json::Map<String, serde_json::Value>> {
pub fn meta(&self) -> Option<&serde_json::Map<String, Value>> {
match self {
Self::Mcp(request) => request.meta().map(|meta| &meta.0.0),
Self::Mcp(request) => Some(request.meta()?),
Self::OpenAiForm { meta, .. }
| Self::OpenAiElicitationForm { meta, .. }
| Self::UserVerification { meta, .. } => {
meta.as_ref().and_then(serde_json::Value::as_object)
}
| Self::UserVerification { meta, .. } => meta.as_ref()?.as_object(),
}
}
/// Strip transport tracing fields before exposing metadata to approvals or user prompts.
/// Return the parent for verification. The invocation supplies trusted trace state.
pub fn take_traceparent(&mut self) -> Option<String> {
let meta: &mut serde_json::Map<String, Value> = match self {
Self::Mcp(request) => request.meta_mut().as_mut()?,
Self::OpenAiForm { meta, .. }
| Self::OpenAiElicitationForm { meta, .. }
| Self::UserVerification { meta, .. } => meta.as_mut()?.as_object_mut()?,
};
meta.remove("tracestate");
match meta.remove("traceparent")? {
Value::String(parent) => Some(parent),
_ => None,
}
}
}