Files
crank/crates/crank-community-mcp/src/app/metrics.rs
T
bsodfather a438c1df42
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
feat(epic3): безопасное structured logging MCP (Story 3.18)
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, остаётся на собранной фиче.
2026-10-25 12:50:00 +00:00

174 lines
5.5 KiB
Rust

use std::{sync::Arc, time::Instant};
use axum::{http::header::CONTENT_TYPE, response::Response};
use crank_metrics::{
ExemplarTraceId, InFlightGuard, LimitStage, McpMethod, McpOutcome, McpResponseMode,
record_limit_rejection, record_mcp_request_with_exemplar,
};
use serde_json::Value;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use crate::jsonrpc::{is_notification, is_response, method_name};
pub(super) struct McpRequestMetrics {
method: McpMethod,
response_mode: McpResponseMode,
outcome: McpOutcome,
started_at: Instant,
exemplar: Option<ExemplarTraceId>,
}
impl McpRequestMetrics {
pub(super) fn invalid(started_at: Instant, exemplar: Option<ExemplarTraceId>) -> Self {
Self {
method: McpMethod::Invalid,
response_mode: McpResponseMode::Unknown,
outcome: McpOutcome::Aborted,
started_at,
exemplar,
}
}
pub(super) fn new(
message: &Value,
started_at: Instant,
exemplar: Option<ExemplarTraceId>,
) -> Self {
Self {
method: normalized_mcp_method(message),
response_mode: McpResponseMode::Unknown,
outcome: McpOutcome::Aborted,
started_at,
exemplar,
}
}
pub(super) fn complete(&mut self, response: &Response) {
self.response_mode = response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.map_or(McpResponseMode::Unknown, |content_type| {
if content_type.starts_with("application/json") {
McpResponseMode::Json
} else if content_type.starts_with("text/event-stream") {
McpResponseMode::Sse
} else {
McpResponseMode::Unknown
}
});
self.outcome = if response.status().is_success() {
response
.extensions()
.get::<McpOutcome>()
.copied()
.unwrap_or_else(|| McpOutcome::from_http_status(response.status().as_u16()))
} else {
McpOutcome::from_http_status(response.status().as_u16())
};
}
#[cfg(test)]
pub(super) const fn outcome(&self) -> McpOutcome {
self.outcome
}
#[cfg(test)]
pub(super) const fn response_mode(&self) -> McpResponseMode {
self.response_mode
}
}
impl Drop for McpRequestMetrics {
fn drop(&mut self) {
record_mcp_request_with_exemplar(
self.method,
self.response_mode,
self.outcome,
self.started_at.elapsed(),
self.exemplar,
);
}
}
pub(super) fn normalized_mcp_method(message: &Value) -> McpMethod {
match method_name(message) {
Some("initialize") => McpMethod::Initialize,
Some("notifications/initialized") => McpMethod::Initialized,
Some("ping") => McpMethod::Ping,
Some("tools/list") => McpMethod::ToolsList,
Some("tools/call") => McpMethod::ToolsCall,
Some(_) if is_notification(message) => McpMethod::Notification,
Some(_) => McpMethod::Unsupported,
None if is_response(message) => McpMethod::Response,
None => McpMethod::Invalid,
}
}
pub(super) struct ActiveStreamGuard {
_permit: OwnedSemaphorePermit,
_inflight: InFlightGuard,
}
impl ActiveStreamGuard {
pub(super) fn try_acquire(slots: &Arc<Semaphore>) -> Result<Self, ()> {
let permit = Arc::clone(slots).try_acquire_owned().map_err(|_| {
record_limit_rejection(LimitStage::McpStream);
})?;
Ok(Self {
_permit: permit,
_inflight: InFlightGuard::mcp_stream(),
})
}
}
#[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
);
}
}