Skip to content

Commit 745d8e1

Browse files
committed
feat(observability): trace bounded MCP inspection outcomes
Signed-off-by: Alex Fournier <afournier@nvidia.com>
1 parent 486e90e commit 745d8e1

10 files changed

Lines changed: 391 additions & 32 deletions

File tree

‎crates/openshell-supervisor-network/README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,12 @@ and borrows unchanged header blocks. It removes only protected receipt fields
9595
and their `Connection` or `Trailer` nominations, including folded continuations,
9696
without adding general response-header validation.
9797

98+
Actual JSON-RPC/MCP body inspections have `openshell.mcp.inspect` child spans.
99+
Each pass reports only its mode, selected revision, message shape and bounded
100+
request/notification counts. Inspection acceptance does not imply policy
101+
approval or remote tool execution. Method/tool names, arguments and payloads
102+
are not added to these spans, and inspection adds no audit records.
103+
98104
Credential preparation stages record bounded mechanism, placement and preparation
99105
outcomes, never credential values. A configured resolver without placeholders is
100106
`not_needed`; `prepared` means resolution or signing succeeded, not that the

‎crates/openshell-supervisor-network/src/l7/correlation.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
//! Request receipts and emission-time correlation without changing audit records.
55
6+
pub mod jsonrpc;
67
mod resources;
78

89
use std::fmt;
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
//! Bounded observations of actual JSON-RPC inspection passes, not execution.
5+
6+
use super::{RequestTrace, current_request};
7+
use crate::l7::jsonrpc::{
8+
JsonRpcInspectionError, JsonRpcInspectionErrorKind, JsonRpcInspectionMode,
9+
JsonRpcInspectionOptions, JsonRpcRequestInfo,
10+
};
11+
12+
const MAX_RECORDED_CALLS: usize = 64;
13+
14+
pub fn inspect(
15+
options: JsonRpcInspectionOptions,
16+
operation: impl FnOnce() -> JsonRpcRequestInfo,
17+
) -> JsonRpcRequestInfo {
18+
let span = current_request()
19+
.filter(|scope| scope.inspected)
20+
.and_then(|scope| {
21+
scope
22+
.trace
23+
.lock()
24+
.unwrap_or_else(std::sync::PoisonError::into_inner)
25+
.as_ref()
26+
.map(RequestTrace::mcp_inspection_span)
27+
})
28+
.unwrap_or_else(tracing::Span::none);
29+
if span.is_disabled() {
30+
return operation();
31+
}
32+
33+
let info = span.in_scope(operation);
34+
span.record(
35+
"openshell.mcp.protocol",
36+
match options.mode {
37+
JsonRpcInspectionMode::Mcp => "mcp",
38+
JsonRpcInspectionMode::JsonRpc => "jsonrpc",
39+
},
40+
);
41+
if let Some(revision) = info.mcp_revision.or(options.mcp_revision) {
42+
span.record("openshell.mcp.revision", revision.as_str());
43+
}
44+
span.record(
45+
"openshell.mcp.inspection.shape",
46+
if info.receive_stream {
47+
"receive_stream"
48+
} else if info.is_batch {
49+
"batch"
50+
} else {
51+
"single"
52+
},
53+
);
54+
let (requests, notifications) = info.calls.iter().take(MAX_RECORDED_CALLS).fold(
55+
(0_i64, 0_i64),
56+
|(requests, notifications), call| {
57+
if call.is_notification {
58+
(requests, notifications + 1)
59+
} else {
60+
(requests + 1, notifications)
61+
}
62+
},
63+
);
64+
span.record("openshell.mcp.request_count", requests);
65+
span.record("openshell.mcp.notification_count", notifications);
66+
span.record("openshell.mcp.has_response", info.has_response);
67+
span.record(
68+
"openshell.mcp.counts_truncated",
69+
info.calls.len() > MAX_RECORDED_CALLS,
70+
);
71+
72+
let (outcome, failure) = match info.error.as_ref().map(JsonRpcInspectionError::kind) {
73+
None => ("accepted", None),
74+
// Transport selection may re-inspect under the selected profile.
75+
Some(JsonRpcInspectionErrorKind::RevisionNotSelected) => ("revision_required", None),
76+
Some(JsonRpcInspectionErrorKind::InvalidJson) => ("rejected", Some("invalid_json")),
77+
Some(JsonRpcInspectionErrorKind::InvalidMessage) => ("rejected", Some("invalid_message")),
78+
Some(JsonRpcInspectionErrorKind::McpProfileViolation) => {
79+
("rejected", Some("mcp_profile_violation"))
80+
}
81+
Some(JsonRpcInspectionErrorKind::McpLifecycleViolation) => {
82+
("rejected", Some("mcp_lifecycle_violation"))
83+
}
84+
};
85+
span.record("openshell.mcp.inspection.outcome", outcome);
86+
if let Some(reason) = failure {
87+
span.record("openshell.mcp.inspection.failure_kind", reason);
88+
span.record("openshell.request.failure_reason", reason);
89+
span.record("otel.status_code", "ERROR");
90+
} else {
91+
span.record("otel.status_code", "OK");
92+
}
93+
info
94+
}
95+
96+
pub fn receive_stream(options: JsonRpcInspectionOptions) -> JsonRpcRequestInfo {
97+
inspect(options, JsonRpcRequestInfo::receive_stream)
98+
}
99+
100+
#[cfg(test)]
101+
mod tests;
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
use super::*;
5+
use crate::l7::correlation::{HttpOutcome, RequestCorrelation, scope_connection};
6+
use crate::l7::jsonrpc::parse_jsonrpc_body_with_options;
7+
use crate::l7::relay::L7EvalContext;
8+
use crate::test_support::request_tracing::{RequestTracing, span_attribute};
9+
use opentelemetry_sdk::trace::Sampler;
10+
use tracing::instrument::WithSubscriber as _;
11+
12+
#[tokio::test]
13+
async fn inspection_metadata_is_bounded_and_does_not_expose_parser_input() {
14+
let _lock = openshell_otel_test_support::tracing_test_lock().await;
15+
let capture = RequestTracing::new(Some(Sampler::AlwaysOn));
16+
let options = JsonRpcInspectionMode::JsonRpc.into();
17+
let mut messages = (0..70)
18+
.map(|id| {
19+
let mut message = serde_json::json!({
20+
"jsonrpc": "2.0", "method": "DO-NOT-RECORD-METHOD",
21+
"params": { "secret": "DO-NOT-RECORD-PAYLOAD" }
22+
});
23+
if id % 2 == 0 {
24+
message["id"] = id.into();
25+
}
26+
message
27+
})
28+
.collect::<Vec<_>>();
29+
messages.push(serde_json::json!({"jsonrpc":"2.0", "id":123, "result":"DO-NOT-RECORD-RESULT"}));
30+
let body = serde_json::to_vec(&messages).unwrap();
31+
scope_connection(async {
32+
let correlation = RequestCorrelation::new_http(
33+
"POST",
34+
b"POST /rpc HTTP/1.1\r\nHost: example.test\r\n\r\n",
35+
&L7EvalContext::default(),
36+
);
37+
let info = parse_jsonrpc_body_with_options(&body, options);
38+
assert_eq!(info.calls.len(), 70);
39+
assert_eq!(info.calls[0].method, "DO-NOT-RECORD-METHOD");
40+
assert!(info.has_response);
41+
let malformed = parse_jsonrpc_body_with_options(
42+
br#"{"DO-NOT-RECORD-KEY":1,"DO-NOT-RECORD-KEY":2}"#,
43+
options,
44+
);
45+
assert_eq!(
46+
malformed.error.as_ref().unwrap().kind(),
47+
JsonRpcInspectionErrorKind::InvalidJson
48+
);
49+
correlation.record_outcome(HttpOutcome::Allowed);
50+
})
51+
.with_subscriber(capture.subscriber())
52+
.await;
53+
54+
// The public parser is also used without an inspected request.
55+
tracing::subscriber::with_default(capture.subscriber(), || {
56+
assert_eq!(
57+
parse_jsonrpc_body_with_options(&body, options).calls.len(),
58+
70
59+
);
60+
});
61+
let spans = capture.spans();
62+
let inspections = spans
63+
.iter()
64+
.filter(|span| span.name == "openshell.mcp.inspect")
65+
.collect::<Vec<_>>();
66+
assert_eq!(inspections.len(), 2);
67+
let batch = inspections
68+
.iter()
69+
.find(|span| {
70+
span_attribute(span, "openshell.mcp.inspection.shape")
71+
.is_some_and(|value| value.as_str() == "batch")
72+
})
73+
.unwrap();
74+
for (key, value) in [
75+
("openshell.mcp.request_count", 32_i64),
76+
("openshell.mcp.notification_count", 32_i64),
77+
] {
78+
assert_eq!(
79+
span_attribute(batch, key),
80+
Some(&opentelemetry::Value::I64(value))
81+
);
82+
}
83+
assert_eq!(
84+
span_attribute(batch, "openshell.mcp.has_response"),
85+
Some(&opentelemetry::Value::Bool(true))
86+
);
87+
assert_eq!(
88+
span_attribute(batch, "openshell.mcp.counts_truncated"),
89+
Some(&opentelemetry::Value::Bool(true))
90+
);
91+
let rejected = inspections
92+
.iter()
93+
.find(|span| {
94+
span_attribute(span, "openshell.mcp.inspection.outcome")
95+
.is_some_and(|value| value.as_str() == "rejected")
96+
})
97+
.unwrap();
98+
assert_eq!(
99+
span_attribute(rejected, "openshell.mcp.inspection.failure_kind")
100+
.unwrap()
101+
.as_str(),
102+
"invalid_json"
103+
);
104+
assert!(matches!(
105+
rejected.status,
106+
opentelemetry::trace::Status::Error { .. }
107+
));
108+
assert!(!format!("{spans:?}").contains("DO-NOT-RECORD"));
109+
assert!(capture.events.json_events().is_empty());
110+
capture.shutdown();
111+
}

‎crates/openshell-supervisor-network/src/l7/jsonrpc.rs‎

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use tower_mcp_types::{
1818
protocol::{InitializeParams, JSONRPC_VERSION, McpRequest, RequestMeta, validate_meta_object},
1919
};
2020

21-
use crate::l7::provider::{L7Provider, L7Request};
21+
use crate::l7::provider::L7Request;
2222

2323
pub const DEFAULT_MAX_BODY_BYTES: usize = 64 * 1024;
2424

@@ -114,26 +114,19 @@ pub struct JsonRpcHttpRequest {
114114
pub info: JsonRpcRequestInfo,
115115
}
116116

117-
pub(crate) async fn parse_jsonrpc_http_request<C: AsyncRead + AsyncWrite + Unpin + Send>(
117+
pub(crate) async fn inspect_jsonrpc_http_request_body<C: AsyncRead + AsyncWrite + Unpin + Send>(
118118
client: &mut C,
119+
request: &mut L7Request,
119120
max_body_bytes: usize,
120-
canonicalize_options: crate::l7::path::CanonicalizeOptions,
121121
inspection_options: JsonRpcInspectionOptions,
122-
) -> Result<Option<JsonRpcHttpRequest>> {
123-
let provider = crate::l7::rest::RestProvider::with_options(canonicalize_options);
124-
let Some(mut request) = provider.parse_request(client).await? else {
125-
return Ok(None);
126-
};
127-
if jsonrpc_receive_stream_request(&request) {
128-
return Ok(Some(JsonRpcHttpRequest {
129-
request,
130-
info: JsonRpcRequestInfo::receive_stream(),
131-
}));
122+
) -> Result<JsonRpcRequestInfo> {
123+
if jsonrpc_receive_stream_request(request) {
124+
return Ok(crate::l7::correlation::jsonrpc::receive_stream(
125+
inspection_options,
126+
));
132127
}
133-
let body =
134-
crate::l7::http::read_body_for_inspection(client, &mut request, max_body_bytes).await?;
135-
let info = parse_jsonrpc_body_with_options(&body, inspection_options);
136-
Ok(Some(JsonRpcHttpRequest { request, info }))
128+
let body = crate::l7::http::read_body_for_inspection(client, request, max_body_bytes).await?;
129+
Ok(parse_jsonrpc_body_with_options(&body, inspection_options))
137130
}
138131

139132
/// Reinspect a fully buffered JSON-RPC-family HTTP request after middleware.
@@ -148,7 +141,9 @@ pub(crate) fn inspect_buffered_jsonrpc_http_request(
148141
inspection_options: JsonRpcInspectionOptions,
149142
) -> Result<JsonRpcRequestInfo> {
150143
if jsonrpc_receive_stream_request(request) {
151-
return Ok(JsonRpcRequestInfo::receive_stream());
144+
return Ok(crate::l7::correlation::jsonrpc::receive_stream(
145+
inspection_options,
146+
));
152147
}
153148

154149
let header_end = request
@@ -416,6 +411,15 @@ pub fn parse_jsonrpc_body(
416411
pub fn parse_jsonrpc_body_with_options(
417412
body: &[u8],
418413
inspection_options: JsonRpcInspectionOptions,
414+
) -> JsonRpcRequestInfo {
415+
crate::l7::correlation::jsonrpc::inspect(inspection_options, || {
416+
parse_jsonrpc_body_inner(body, inspection_options)
417+
})
418+
}
419+
420+
fn parse_jsonrpc_body_inner(
421+
body: &[u8],
422+
inspection_options: JsonRpcInspectionOptions,
419423
) -> JsonRpcRequestInfo {
420424
let value = match parse_unique_json_value(body) {
421425
Ok(value) => value,

‎crates/openshell-supervisor-network/src/l7/relay.rs‎

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1686,7 +1686,9 @@ where
16861686
};
16871687
let mut jsonrpc_info = if config.protocol.is_jsonrpc_family() {
16881688
if crate::l7::jsonrpc::jsonrpc_receive_stream_request(&req) {
1689-
Some(crate::l7::jsonrpc::JsonRpcRequestInfo::receive_stream())
1689+
Some(crate::l7::correlation::jsonrpc::receive_stream(
1690+
crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(config),
1691+
))
16901692
} else {
16911693
match crate::l7::http::read_body_for_inspection(
16921694
client,
@@ -3113,17 +3115,36 @@ where
31133115
.endpoint_observation_tx
31143116
.as_ref()
31153117
.and_then(EndpointObservationSender::capture);
3116-
let parsed = match crate::l7::jsonrpc::parse_jsonrpc_http_request(
3117-
client,
3118-
config.json_rpc_max_body_bytes,
3119-
crate::l7::path::CanonicalizeOptions {
3118+
let provider =
3119+
crate::l7::rest::RestProvider::with_options(crate::l7::path::CanonicalizeOptions {
31203120
allow_encoded_slash: config.allow_encoded_slash,
31213121
..Default::default()
3122-
},
3123-
crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(config),
3124-
)
3125-
.await
3126-
{
3122+
});
3123+
// Retain the scope while body-parse failures are audited.
3124+
let mut correlation = None;
3125+
let parsed: Result<_> = async {
3126+
let Some(mut request) = provider.parse_request(client).await? else {
3127+
return Ok(None);
3128+
};
3129+
let request_correlation = RequestCorrelation::new(&request, ctx);
3130+
request_correlation
3131+
.record_policy_generation(engine.generation_guard().captured_generation());
3132+
request_correlation.record_selected_endpoint(config);
3133+
correlation = Some(request_correlation);
3134+
let info = crate::l7::jsonrpc::inspect_jsonrpc_http_request_body(
3135+
client,
3136+
&mut request,
3137+
config.json_rpc_max_body_bytes,
3138+
crate::l7::jsonrpc::JsonRpcInspectionOptions::for_config(config),
3139+
)
3140+
.await?;
3141+
Ok(Some(crate::l7::jsonrpc::JsonRpcHttpRequest {
3142+
request,
3143+
info,
3144+
}))
3145+
}
3146+
.await;
3147+
let parsed = match parsed {
31273148
Ok(Some(parsed)) => parsed,
31283149
Ok(None) => return Ok(()),
31293150
Err(e) => {
@@ -3145,9 +3166,7 @@ where
31453166

31463167
let req = parsed.request;
31473168
let jsonrpc_info = parsed.info;
3148-
let correlation = RequestCorrelation::new(&req, ctx);
3149-
correlation.record_policy_generation(engine.generation_guard().captured_generation());
3150-
correlation.record_selected_endpoint(config);
3169+
let correlation = correlation.expect("a parsed request has a correlation scope");
31513170
let capture_error = |error| correlation.capture_error(error);
31523171
let observer = EndpointObserver::begin_captured(
31533172
ctx.endpoint_observation_tx.as_ref(),

0 commit comments

Comments
 (0)