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

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:
bsodfather committed 2026-10-25 12:50:00 +00:00
1 parent aed83268a0
commit a438c1df42
24 files changed
+1883 -38

No files matched your search

+59 -1
View File
@@ -116,6 +116,19 @@ fn accepted_media_types(headers: &HeaderMap) -> Option<Vec<String>> {
)
}
/// Whether this request offered `text/event-stream`.
///
/// Story 3.18: the SSE response stream is the only carrier of a server `notifications/message`, so
/// the logging projection asks this before it promises a notification. It is the same admission rule
/// the response-mode negotiation already applies, not a second interpretation of the header.
pub(super) fn accepts_event_stream(headers: &HeaderMap) -> bool {
accepted_media_types(headers).is_some_and(|media_types| {
media_types
.iter()
.any(|media_type| media_type == "text/event-stream")
})
}
pub(super) fn negotiate_post_response_mode(
headers: &HeaderMap,
) -> Result<ResponseMode, StatusCode> {
@@ -266,8 +279,26 @@ pub(super) fn transport_response(
protocol_version: Option<&str>,
) -> Response {
let outcome = payload_outcome(&payload);
// Story 3.18: this is the single projection point of the adapter's own safe structured event.
// The severity is derived from the already-decided outcome of the payload, so no request payload,
// credential, error cause or user value is read here.
note_logging_outcome(&payload);
let notifications = crate::protocol::take_notifications();
// A pending `notifications/message` has no carrier in a JSON body. When the client offered both
// media types and opted in to logging, the negotiated mode is the SSE stream, so the notification
// precedes the response instead of being silently dropped.
let response_mode = if notifications.is_empty() {
response_mode
} else {
ResponseMode::Sse
};
if status == StatusCode::OK && matches!(response_mode, ResponseMode::Sse) {
let stream = stream::iter([Ok(Event::default().data(payload.to_string()))]);
let mut messages = Vec::with_capacity(notifications.len() + 1);
for notification in notifications {
messages.push(Ok(Event::default().data(notification.to_string())));
}
messages.push(Ok(Event::default().data(payload.to_string())));
let stream = stream::iter(messages);
let mut response = sse_response(status, stream, session_id, protocol_version);
if let Some(outcome) = outcome {
@@ -279,6 +310,33 @@ pub(super) fn transport_response(
json_response(status, payload, session_id, protocol_version)
}
/// Record the closed safe event of one response: served, rejected as invalid, failed, or a tool-level
/// error. Every label is a fixed string of the closed vocabulary; nothing from the payload or the
/// request is copied into it.
fn note_logging_outcome(payload: &Value) {
use crate::protocol::{EVENT_FAILED, EVENT_REJECTED, EVENT_SERVED, LogLevel, note};
if payload.get("error").is_some() {
match payload.pointer("/error/code").and_then(Value::as_i64) {
// The pinned client-error codes: a malformed request, a method that this era does not
// implement, and invalid params. The client can correct all three, so they are a
// rejection rather than a server failure; the closed label stays the one client-error
// label of the vocabulary instead of growing a new one.
Some(-32602..=-32600) => note(LogLevel::Warning, EVENT_REJECTED, "invalid_params"),
_ => note(LogLevel::Error, EVENT_FAILED, "internal"),
}
return;
}
if payload
.pointer("/result/isError")
.and_then(Value::as_bool)
.unwrap_or(false)
{
note(LogLevel::Warning, EVENT_REJECTED, "tool_error");
return;
}
note(LogLevel::Info, EVENT_SERVED, "ok");
}
fn payload_outcome(payload: &Value) -> Option<McpOutcome> {
if payload.get("error").is_some() {
return Some(McpOutcome::JsonRpcError);