-
Notifications
You must be signed in to change notification settings - Fork 66
Add parent context to new trace spans #484
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1fa4b98
add parent context to new spans
david-castaneda 1c464f8
implemente middleware and instrument
david-castaneda 76143e9
remove unused dep
david-castaneda 2dcacb9
update import
david-castaneda eb8dca3
Merge branch 'main' into david/add-traceparent-context-to-new-spans
david-castaneda b3ca412
cargo fmt
david-castaneda ce43aa3
add simple test
david-castaneda c00e3c4
update test name
david-castaneda 6a4f8d5
add changeset
david-castaneda fea2783
Update .changesets/feat_david_support_traceparent_context.md
david-castaneda 54aa500
Merge branch 'main' into david/add-traceparent-context-to-new-spans
david-castaneda fd20647
add tests to telemetry module
david-castaneda e126e2c
remove unused imports
david-castaneda b9c613c
fix test
david-castaneda a1e32a8
defualt to no parent span
david-castaneda c41ce70
add test for keys fn
david-castaneda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| ### Server adds support for incoming distributed trace context propagation - @david-castaneda PR #484 | ||
|
|
||
| The MCP server now extracts W3C traceparent headers from incoming requests and uses this context for its own emitted traces, enabling handler spans to nest under parent traces for complete end-to-end observability. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
172 changes: 172 additions & 0 deletions
172
crates/apollo-mcp-server/src/server/states/telemetry.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| use axum::extract::Request; | ||
| use axum::middleware::Next; | ||
| use axum::response::Response; | ||
| use opentelemetry::global; | ||
| use opentelemetry::propagation::Extractor; | ||
| use rmcp::RoleServer; | ||
| use rmcp::service::RequestContext; | ||
| use tracing::Instrument; | ||
| use tracing_opentelemetry::OpenTelemetrySpanExt; | ||
|
|
||
| // Custom extractor for axum headers | ||
| struct HeaderExtractor<'a>(&'a axum::http::HeaderMap); | ||
|
|
||
| // Implement the Extractor trait for HeaderExtractor | ||
| impl<'a> Extractor for HeaderExtractor<'a> { | ||
| fn get(&self, key: &str) -> Option<&str> { | ||
| self.0.get(key).and_then(|v| v.to_str().ok()) | ||
| } | ||
|
|
||
| fn keys(&self) -> Vec<&str> { | ||
| self.0.keys().map(|k| k.as_str()).collect() | ||
| } | ||
| } | ||
|
|
||
| // Middleware that extracts and stores OpenTelemetry context in request extensions | ||
| pub async fn otel_context_middleware(mut request: Request, next: Next) -> Response { | ||
| let parent_cx = global::get_text_map_propagator(|propagator| { | ||
| propagator.extract(&HeaderExtractor(request.headers())) | ||
| }); | ||
|
|
||
| request.extensions_mut().insert(parent_cx.clone()); // Store the OtelContext directly in extensions | ||
|
|
||
| let span = tracing::info_span!( | ||
| "mcp_server", | ||
| method = %request.method(), | ||
| uri = %request.uri(), | ||
| session_id = tracing::field::Empty, | ||
| status_code = tracing::field::Empty, | ||
| ); | ||
| span.set_parent(parent_cx); | ||
|
|
||
| request.extensions_mut().insert(span.clone()); // Store the span in request extensions | ||
|
|
||
| let response = next.run(request).instrument(span.clone()).await; | ||
|
|
||
| span.record("status_code", tracing::field::display(response.status())); | ||
|
|
||
| if let Some(session_id) = response | ||
| .headers() | ||
| .get("mcp-session-id") | ||
| .and_then(|v| v.to_str().ok()) | ||
| { | ||
| span.record("session_id", tracing::field::display(session_id)); | ||
| } | ||
|
|
||
| response | ||
| } | ||
|
|
||
| // Helper function to retrieve the parent span from the request context | ||
| pub fn get_parent_span(context: &RequestContext<RoleServer>) -> tracing::Span { | ||
| context | ||
| .extensions | ||
| .get::<axum::http::request::Parts>() | ||
| .and_then(|parts| parts.extensions.get::<tracing::Span>()) | ||
| .cloned() | ||
| .unwrap_or_else(tracing::Span::none) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use axum::{Router, body::Body, http::Request, routing::get}; | ||
| use http::HeaderName; | ||
| use opentelemetry::Context as OtelContext; | ||
| use opentelemetry::trace::TraceContextExt; | ||
| use tower::ServiceExt; | ||
|
|
||
| #[tokio::test()] | ||
| async fn test_middleware_stores_span_context_and_handler_works() { | ||
| opentelemetry::global::set_text_map_propagator( | ||
| opentelemetry_sdk::propagation::TraceContextPropagator::new(), | ||
| ); | ||
|
|
||
| async fn test_handler(req: Request<Body>) -> &'static str { | ||
| let (parts, _body) = req.into_parts(); | ||
|
|
||
| // Get OtelContext from extensions | ||
| let otel_ctx = parts | ||
| .extensions | ||
| .get::<OtelContext>() | ||
| .expect("OtelContext should be in extensions"); | ||
|
|
||
| let trace_id = format!("{:032x}", otel_ctx.span().span_context().trace_id()); | ||
| assert_eq!(trace_id, "4bf92f3577b34da6a3ce929d0e0e4736"); | ||
|
|
||
| // Verify span is also stored | ||
| let span = parts.extensions.get::<tracing::Span>(); | ||
| assert!(span.is_some()); | ||
|
|
||
| "ok" | ||
| } | ||
|
|
||
| let app = Router::new() | ||
| .route("/test", get(test_handler)) | ||
| .layer(axum::middleware::from_fn(otel_context_middleware)); | ||
|
|
||
| let traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; | ||
| let request = Request::builder() | ||
| .uri("/test") | ||
| .header("traceparent", traceparent) | ||
| .body(Body::empty()) | ||
| .unwrap(); | ||
|
|
||
| let response = app.oneshot(request).await.unwrap(); | ||
| assert_eq!(response.status(), 200); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn test_middleware_works_without_traceparent() { | ||
| opentelemetry::global::set_text_map_propagator( | ||
| opentelemetry_sdk::propagation::TraceContextPropagator::new(), | ||
| ); | ||
|
|
||
| let app = Router::new() | ||
| .route("/test", get(|| async { "ok" })) | ||
| .layer(axum::middleware::from_fn(otel_context_middleware)); | ||
|
|
||
| let request = Request::builder().uri("/test").body(Body::empty()).unwrap(); | ||
|
|
||
| let response = app.oneshot(request).await.unwrap(); | ||
|
|
||
| assert_eq!(response.status(), 200); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_header_extractor_gets_values() { | ||
| let mut headers = axum::http::HeaderMap::new(); | ||
| headers.insert("traceparent", "test-value".parse().unwrap()); | ||
| headers.insert("x-custom", "custom-value".parse().unwrap()); | ||
|
|
||
| let extractor = HeaderExtractor(&headers); | ||
|
|
||
| assert_eq!(extractor.get("traceparent"), Some("test-value")); | ||
| assert_eq!(extractor.get("x-custom"), Some("custom-value")); | ||
| assert_eq!(extractor.get("missing"), None); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_header_extractor_keys() { | ||
| let mut headers = axum::http::HeaderMap::new(); | ||
| headers.insert("traceparent", "test-value".parse().unwrap()); | ||
| headers.insert("x-custom", "custom-value".parse().unwrap()); | ||
|
|
||
| let extractor = HeaderExtractor(&headers); | ||
|
|
||
| let mut keys = extractor | ||
| .keys() | ||
| .into_iter() | ||
| .map(|k| HeaderName::from_bytes(k.as_bytes()).unwrap()) | ||
| .collect::<Vec<_>>(); | ||
|
|
||
| let mut expected = vec![ | ||
| HeaderName::from_static("traceparent"), | ||
| HeaderName::from_static("x-custom"), | ||
| ]; | ||
|
|
||
| keys.sort_by(|a, b| a.as_str().cmp(b.as_str())); | ||
| expected.sort_by(|a, b| a.as_str().cmp(b.as_str())); | ||
|
|
||
| assert_eq!(keys, expected); | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.