feat(epic3): безопасное structured logging MCP (Story 3.18)
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Failing after 4m11s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Failing after 1s
CI / Deploy (pull_request) Skipped
Story 3.18 (#25) surface: клиент получает только закрытые structured `notifications/message` выбранного уровня, без запросов, секретов и internal causes. - `logging` capability advertising в обеих поддерживаемых revisions; `logging/setLevel` — legacy-only dispatch (modern — `_meta` per request); - закрытый словарь LoggingLevel (RFC 5424), malformed → -32602 с одним safe detail; закрытый набор safe events, task-local request scope; bounded in-memory opt-in, без миграций; - `notifications/message` идут перед ответом в SSE; JSON-режим их не несёт; - ATDD в `scripts/ci-story-checks.sh`: mcp_logging (10), inventory projection (3), protocol::logging unit (12); - проекция capability inventory/frozen oracle переведена на `logging`. Story ATDD и affected проверки пройдены на этом дереве (fmt, clippy, python oracle 56 OK, capability inventory valid). Полный `just verify` — NOT_RUN на story по validation-policy, остаётся на собранной фиче.
This commit is contained in:
1 parent
aed83268a0
commit
a438c1df42
24 files changed
+1883
-38
No files matched your search
@@ -67,6 +67,12 @@ pub(super) async fn handle_modern_request(
|
||||
.as_deref()
|
||||
.unwrap_or(crate::jsonrpc::MODERN_PROTOCOL_VERSION);
|
||||
|
||||
// Story 3.18: the modern revision carries the log level of this request in
|
||||
// `_meta["io.modelcontextprotocol/logLevel"]` (SEP-2577); the former `logging/setLevel` request
|
||||
// does not exist here. Absent, non-string or unknown values mean "not opted in", so no
|
||||
// `notifications/message` is emitted for this request.
|
||||
crate::protocol::set_active_level(crate::protocol::modern_request_level(message));
|
||||
|
||||
// A notification carries no `id`. It is acknowledged before the request-only header rules: the
|
||||
// mandatory `Mcp-Method`/`Mcp-Name` pair applies to requests, not to notifications (protocol era
|
||||
// matrix row 18). The envelope, identity and mixed-carrier checks — and authentication — have
|
||||
|
||||
@@ -14,20 +14,22 @@ use crate::{
|
||||
method_name, params, request_id,
|
||||
},
|
||||
protocol::{
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, EnvelopeKind,
|
||||
Kind, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome,
|
||||
RequestEra, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
ambiguous_session_carrier_response, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, handle_tools_command, resolve_request_identity,
|
||||
CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision,
|
||||
EVENT_LEVEL_APPLIED, EnvelopeKind, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler,
|
||||
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestEra,
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, SetLevelCommand, ToolCallCommand, ToolsCommand, ToolsListCommand,
|
||||
ToolsOutcome, ambiguous_session_carrier_response, handle_completion_command,
|
||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||
handle_tools_command, resolve_request_identity,
|
||||
},
|
||||
rate_limit::{rate_limited_jsonrpc_response, rate_limited_status_response},
|
||||
request_context::RequestContext,
|
||||
tool_error::execution_locale,
|
||||
transport::{
|
||||
negotiate_post_response_mode, session_id_from_headers, sse_response, transport_response,
|
||||
validate_get_accept_header, validate_origin, validate_session_protocol_version,
|
||||
with_request_id_header,
|
||||
accepts_event_stream, negotiate_post_response_mode, session_id_from_headers, sse_response,
|
||||
transport_response, validate_get_accept_header, validate_origin,
|
||||
validate_session_protocol_version, with_request_id_header,
|
||||
},
|
||||
};
|
||||
use axum::{
|
||||
@@ -224,8 +226,14 @@ pub(super) async fn mcp_post(
|
||||
"mcp request received"
|
||||
);
|
||||
|
||||
let response =
|
||||
mcp_post_response(&path, state, &headers, &message, &transport_correlation).await;
|
||||
let response = crate::protocol::logging_scope(mcp_post_response(
|
||||
&path,
|
||||
state,
|
||||
&headers,
|
||||
&message,
|
||||
&transport_correlation,
|
||||
))
|
||||
.await;
|
||||
request_metrics.complete(&response);
|
||||
with_request_id_header(response, &transport_request_id)
|
||||
}
|
||||
@@ -250,6 +258,13 @@ async fn mcp_post_response(
|
||||
Ok(mode) => mode,
|
||||
Err(status) => return status.into_response(),
|
||||
};
|
||||
// Story 3.18: a server notification is delivered only on the SSE stream, so the logging
|
||||
// projection records whether this request offered it. This is an admission fact of the same
|
||||
// `Accept` header the mode above was negotiated from.
|
||||
if accepts_event_stream(headers) {
|
||||
crate::protocol::set_sse_acceptable();
|
||||
}
|
||||
|
||||
// A conflicting duplicate session carrier is an ambiguous identity: it must not be resolved to
|
||||
// one of its values. The carrier itself cannot tell which era the request belongs to, so the
|
||||
// diagnostic is read from the non-ambiguous part of the request (matrix row 17) — a consumer of
|
||||
@@ -327,6 +342,17 @@ async fn mcp_post_response(
|
||||
}
|
||||
}
|
||||
|
||||
// Story 3.18: the legacy logging opt-in belongs to this session, so it is read before dispatch.
|
||||
// A session that never sent `logging/setLevel` has no level, which is what the pinned schema
|
||||
// describes as "not opted in" (no notification is delivered).
|
||||
if matches!(identity.era, RequestEra::Legacy) {
|
||||
crate::protocol::set_active_level(
|
||||
request_session_id
|
||||
.as_deref()
|
||||
.and_then(|session_id| state.logging_levels.get(session_id)),
|
||||
);
|
||||
}
|
||||
|
||||
let required_scope = match method_name(message) {
|
||||
Some("tools/call") => PlatformApiKeyScope::Write,
|
||||
_ => PlatformApiKeyScope::Read,
|
||||
@@ -953,6 +979,56 @@ async fn mcp_post_response(
|
||||
}
|
||||
}
|
||||
}
|
||||
// Story 3.18: the pinned legacy `logging/setLevel`. The level belongs to the initialized
|
||||
// session of this request, so setting it can never change another client's level. The request
|
||||
// answers an empty result; the acknowledgment event is filtered by the level it just set.
|
||||
DispatchDecision::Allowed {
|
||||
handler: MethodHandler::LoggingSetLevel,
|
||||
..
|
||||
} if is_request(message) => {
|
||||
let session = match require_initialized_session(&state, path, headers, message).await {
|
||||
Ok(session) => session,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let command: SetLevelCommand = match serde_json::from_value(params(message)) {
|
||||
Ok(command) => command,
|
||||
// A non-string, missing or otherwise unparsable level shares the one safe detail of a
|
||||
// value outside the pinned union: nothing the client sent is echoed back.
|
||||
Err(_) => {
|
||||
return transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, INVALID_LEVEL),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
);
|
||||
}
|
||||
};
|
||||
match handle_logging_command(&state.logging_levels, &session.id, command) {
|
||||
LoggingOutcome::Applied(level) => {
|
||||
crate::protocol::set_active_level(Some(level));
|
||||
crate::protocol::note(
|
||||
crate::protocol::LogLevel::Notice,
|
||||
EVENT_LEVEL_APPLIED,
|
||||
"applied",
|
||||
);
|
||||
transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), json!({})),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
)
|
||||
}
|
||||
LoggingOutcome::InvalidParams(detail) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, detail),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
}
|
||||
}
|
||||
// A notification whose method the registration does not map to this adapter's handlers is
|
||||
// acknowledged without being dispatched, exactly as before.
|
||||
_ if is_notification(message) => StatusCode::ACCEPTED.into_response(),
|
||||
|
||||
@@ -121,3 +121,53 @@ impl ActiveStreamGuard {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crank_metrics::McpMethod;
|
||||
use serde_json::json;
|
||||
|
||||
use super::normalized_mcp_method;
|
||||
|
||||
/// AT-3.18-02: the metric label of the logging request is a member of the closed label enum, so
|
||||
/// neither the level nor any other client-supplied identifier can reach the label space. There is
|
||||
/// no mapping from a request value to a label anywhere in this file.
|
||||
#[test]
|
||||
fn a_logging_request_can_only_produce_a_fixed_metric_label() {
|
||||
for level in [
|
||||
json!("debug"),
|
||||
json!("verbose"),
|
||||
json!("crank-canary-9f7620e5-aa41-4b0d"),
|
||||
json!(7),
|
||||
json!(null),
|
||||
] {
|
||||
let message = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "logging/setLevel",
|
||||
"params": {"level": level}
|
||||
});
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&message),
|
||||
McpMethod::Unsupported,
|
||||
"the method label is a fixed enum member, never the request value"
|
||||
);
|
||||
}
|
||||
assert_eq!(McpMethod::Unsupported.as_str(), "unsupported");
|
||||
// Every label value of the enum is a pinned literal, so the label domain cannot be widened by
|
||||
// a request at all.
|
||||
assert!(
|
||||
McpMethod::VALUES.iter().all(|value| value
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_lowercase() || character == '_')),
|
||||
"every method label is a fixed lowercase literal: {:?}",
|
||||
McpMethod::VALUES
|
||||
);
|
||||
|
||||
// A malformed envelope has its own fixed label as well.
|
||||
assert_eq!(
|
||||
normalized_mcp_method(&json!({"level": "debug"})),
|
||||
McpMethod::Invalid
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user