Trace each MCP tool-list page and its retries (#65060)

## Why

A tool-list page can take multiple attempts. Tracing the whole page
keeps retry warnings tied to the page that triggered them.

## What changed

Wrap each `tools/list` page request in an `mcp.tools.list_page` span
that covers the retry loop. Record whether the request has a cursor
via `mcp.has_cursor`.

## Testing

Extend the trace propagation test in both MCP protocol modes. Return
HTTP 503 on the first request for the second page and verify that the
requests carry the page span context, the cursor flag reflects the
request, and the retry warning appears on the page span.

GitOrigin-RevId: e4b695731d037f71c15660a826c9f2e59d02e55f
This commit is contained in:
Tom
2026-12-01 19:13:34 +00:00
committed by copyberry
parent 71f99fca5d
commit 278dd6cafd
2 changed files with 45 additions and 4 deletions
+38 -3
View File
@@ -10,6 +10,7 @@ use codex_rmcp_client::ElicitationResponse;
use codex_rmcp_client::McpProtocolMode;
use codex_rmcp_client::RmcpClient;
use futures::FutureExt;
use opentelemetry::KeyValue;
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_sdk::trace::InMemorySpanExporter;
use opentelemetry_sdk::trace::SdkTracerProvider;
@@ -27,6 +28,7 @@ use wiremock::Mock;
use wiremock::MockServer;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
#[tokio::test(flavor = "current_thread")]
@@ -43,6 +45,16 @@ async fn mcp_requests_preserve_trace_context_across_workers_and_continuations()
for mode in [McpProtocolMode::Legacy, McpProtocolMode::V20260728] {
let modern = mode == McpProtocolMode::V20260728;
let server = MockServer::start().await;
// Exercise work between attempts, outside the individual send futures.
Mock::given(method("POST"))
.and(body_partial_json(
json!({"method":"tools/list", "params":{"cursor":"page2"}}),
))
.respond_with(ResponseTemplate::new(503))
.up_to_n_times(1)
.with_priority(1)
.mount(&server)
.await;
Mock::given(method("POST")).respond_with(move |request: &Request| {
let body: Value = request.body_json().unwrap();
let result = match body["method"].as_str().unwrap() {
@@ -145,7 +157,7 @@ async fn mcp_requests_preserve_trace_context_across_workers_and_continuations()
.then_some((request, body))
})
.collect::<Vec<_>>();
assert_eq!(requests.len(), if modern { 5 } else { 4 });
assert_eq!(requests.len(), if modern { 6 } else { 5 });
for (request, body) in requests {
if matches!(body["method"].as_str(), Some("tools/list" | "tools/call")) {
assert_eq!(body["params"]["_meta"]["openai/readOnly"], true);
@@ -177,11 +189,34 @@ async fn mcp_requests_preserve_trace_context_across_workers_and_continuations()
.split('-')
.collect::<Vec<_>>();
assert_eq!(metadata_parent[1], parent[1]);
if metadata_parent[2] != parent[2] {
let caller = spans
let caller_id = if body["method"] == "tools/list" {
let page = spans
.iter()
.find(|span| span.span_context.span_id().to_string() == metadata_parent[2])
.unwrap();
assert_eq!(page.name, "mcp.tools.list_page");
assert!(page.attributes.contains(&KeyValue::new(
"mcp.has_cursor",
body["params"].get("cursor").is_some(),
)));
if body["params"]["cursor"] == "page2" {
assert!(
page.events.iter().any(|event| event
.attributes
.iter()
.any(|attr| attr.key.as_str() == "attempt")),
"the page span should contain the retry warning"
);
}
page.parent_span_id.to_string()
} else {
metadata_parent[2].to_string()
};
if caller_id != parent[2] {
let caller = spans
.iter()
.find(|span| span.span_context.span_id().to_string() == caller_id)
.unwrap();
assert_eq!(caller.name, "list_tools_with_connector_ids");
assert_eq!(caller.parent_span_id.to_string(), parent[2]);
}
+7 -1
View File
@@ -841,6 +841,11 @@ impl RmcpClient {
Ok(initialize_result)
}
#[instrument(
name = "mcp.tools.list_page",
skip_all,
fields(mcp.has_cursor = params.as_ref().is_some_and(|params| params.cursor.is_some()))
)]
pub async fn list_tools(
&self,
params: Option<PaginatedRequestParams>,
@@ -875,8 +880,9 @@ impl RmcpClient {
_ => Err(ServiceError::UnexpectedResponse),
}
}
.boxed()
})
// Box the retry loop once per page to bound the instrumented future's layout.
.boxed()
.await?;
self.persist_oauth_tokens().await;
Ok(result)