refactor(mcp): migrate compatible logging paths to rmcp SDK
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 27m19s
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) Successful in 1s
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-11-11 22:51:42 +00:00
1 parent 5bf4e3e9bf
commit 4832878468
6 files changed
+516 -28

No files matched your search

@@ -63,9 +63,24 @@ pub(crate) struct CounterSet {
sdk_prompts_get_result: AtomicUsize,
sdk_completion_dispatch: AtomicUsize,
sdk_completion_result: AtomicUsize,
sdk_logging_dispatch: AtomicUsize,
sdk_logging_level: AtomicUsize,
sdk_logging_notification: AtomicUsize,
}
impl CounterSet {
pub(crate) fn sdk_logging_dispatch(&self) -> usize {
self.sdk_logging_dispatch.load(Ordering::SeqCst)
}
pub(crate) fn sdk_logging_level(&self) -> usize {
self.sdk_logging_level.load(Ordering::SeqCst)
}
pub(crate) fn sdk_logging_notification(&self) -> usize {
self.sdk_logging_notification.load(Ordering::SeqCst)
}
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
self.sdk_completion_dispatch.load(Ordering::SeqCst)
}
@@ -269,6 +284,24 @@ pub(crate) fn sdk_completion_result_serialized() {
#[path = "../rmcp_completion_runtime_tests.rs"]
mod rmcp_completion_runtime_tests;
/// Mark only after constructing the real SDK typed legacy logging request.
pub(crate) fn sdk_logging_dispatch_enter() {
increment(|counters| &counters.sdk_logging_dispatch);
}
/// Mark only after successfully decoding a real SDK LoggingLevel at either input.
pub(crate) fn sdk_logging_level_parsed() {
increment(|counters| &counters.sdk_logging_level);
}
/// Mark only after serializing real SDK LoggingMessageNotificationParam params, not an envelope.
pub(crate) fn sdk_logging_notification_serialized() {
increment(|counters| &counters.sdk_logging_notification);
}
#[path = "../rmcp_logging_runtime_tests.rs"]
mod rmcp_logging_runtime_tests;
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
let _ = OBSERVER.try_with(|counters| {
counter(counters).fetch_add(1, Ordering::SeqCst);
@@ -41,6 +41,9 @@ use std::{
sync::{Mutex, MutexGuard},
};
// Both pinned revisions still require logging despite the SDK's SEP-2577 deprecation.
#[allow(deprecated)]
use rmcp::model::{LoggingLevel, LoggingMessageNotificationParam, SetLevelRequestParams};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::task_local;
@@ -61,7 +64,8 @@ pub(crate) enum LogLevel {
}
impl LogLevel {
/// The exact wire literal of this level.
/// The exact wire literal of this level (contract assertions only; runtime uses SDK serde).
#[cfg(test)]
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Debug => "debug",
@@ -80,17 +84,47 @@ impl LogLevel {
/// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that
/// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type
/// says and what `InvalidParamsError` is for.
#[allow(deprecated)]
pub(crate) fn parse(value: &str) -> Option<Self> {
match value {
"debug" => Some(Self::Debug),
"info" => Some(Self::Info),
"notice" => Some(Self::Notice),
"warning" => Some(Self::Warning),
"error" => Some(Self::Error),
"critical" => Some(Self::Critical),
"alert" => Some(Self::Alert),
"emergency" => Some(Self::Emergency),
_ => None,
if value.len() > MAX_LEVEL_BYTES {
return None;
}
let level: LoggingLevel = serde_json::from_value(Value::String(value.to_owned())).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_logging_level_parsed();
Some(level.into())
}
}
// Keep domain severity ordering independent of SDK enum discriminants (which have no Ord).
#[allow(deprecated)]
impl From<LoggingLevel> for LogLevel {
fn from(level: LoggingLevel) -> Self {
match level {
LoggingLevel::Debug => Self::Debug,
LoggingLevel::Info => Self::Info,
LoggingLevel::Notice => Self::Notice,
LoggingLevel::Warning => Self::Warning,
LoggingLevel::Error => Self::Error,
LoggingLevel::Critical => Self::Critical,
LoggingLevel::Alert => Self::Alert,
LoggingLevel::Emergency => Self::Emergency,
}
}
}
#[allow(deprecated)]
impl From<LogLevel> for LoggingLevel {
fn from(level: LogLevel) -> Self {
match level {
LogLevel::Debug => Self::Debug,
LogLevel::Info => Self::Info,
LogLevel::Notice => Self::Notice,
LogLevel::Warning => Self::Warning,
LogLevel::Error => Self::Error,
LogLevel::Critical => Self::Critical,
LogLevel::Alert => Self::Alert,
LogLevel::Emergency => Self::Emergency,
}
}
}
@@ -135,11 +169,20 @@ pub(crate) struct SetLevelCommand {
impl SetLevelCommand {
/// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a
/// malformed or oversized value is refused with bounded work and one safe detail.
pub(crate) fn validate(&self) -> Result<LogLevel, &'static str> {
#[allow(deprecated)]
pub(crate) fn validate(&self) -> Result<SetLevelRequestParams, &'static str> {
if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES {
return Err(INVALID_LEVEL);
}
LogLevel::parse(&self.level).ok_or(INVALID_LEVEL)
// Only level was part of the old command: unknown members (including _meta) stay ignored.
let request =
serde_json::from_value(json!({"level": self.level})).map_err(|_| INVALID_LEVEL)?;
#[cfg(test)]
{
crate::app::dispatch_observer::sdk_logging_level_parsed();
crate::app::dispatch_observer::sdk_logging_dispatch_enter();
}
Ok(request)
}
}
@@ -282,19 +325,22 @@ pub(crate) fn take_notifications() -> Vec<Value> {
}
std::mem::take(&mut log.pending)
.into_iter()
.map(|event| {
json!({
.filter_map(|event| {
#[allow(deprecated)]
let params = LoggingMessageNotificationParam::new(
event.level.into(),
json!({"event": event.event, "outcome": event.outcome}),
)
.with_logger(LOGGER_NAME);
// Logging remains best-effort: a serialization failure drops only this event.
let params = serde_json::to_value(params).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_logging_notification_serialized();
Some(json!({
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": event.level.as_str(),
"logger": LOGGER_NAME,
"data": {
"event": event.event,
"outcome": event.outcome,
}
}
})
"params": params,
}))
})
.collect()
})
@@ -354,7 +400,9 @@ pub(crate) fn handle_logging_command(
command: SetLevelCommand,
) -> LoggingOutcome {
match command.validate() {
Ok(level) => {
Ok(request) => {
#[allow(deprecated)]
let level = request.level.into();
store.set(session_id, level);
LoggingOutcome::Applied(level)
}
@@ -10,7 +10,8 @@ use super::*;
/// is malformed (which the adapter answers with the same safe detail).
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
Some(command.validate())
#[allow(deprecated)]
Some(command.validate().map(|request| request.level.into()))
}
#[test]
@@ -291,8 +292,11 @@ fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
fn the_command_records_the_level_of_its_own_session_only() {
let store = LogLevelStore::new();
store.set("other-session", LogLevel::Debug);
let command: SetLevelCommand =
serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses");
// Unknown members were ignored by the legacy command; SDK metadata must not narrow that wire.
let command: SetLevelCommand = serde_json::from_value(json!({
"level": "critical", "_meta": 7, "unknown": {"private": "ignored"}
}))
.expect("a pinned level parses regardless of unknown members");
let outcome = handle_logging_command(&store, "this-session", command);
assert!(matches!(
outcome,
@@ -0,0 +1,258 @@
//! #107 logging: existing HTTP wire control before the independent SDK marker assertions.
use super::{CounterSet, observe, support::*};
use axum::{body::Body, response::Response};
use futures_util::{StreamExt, stream};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
#[path = "rmcp_logging_test_support.rs"]
mod fixtures;
use fixtures::Endpoint;
const LEVEL: &str = "io.modelcontextprotocol/logLevel";
fn counts(c: &CounterSet) -> [usize; 3] {
[
c.sdk_logging_dispatch(),
c.sdk_logging_level(),
c.sdk_logging_notification(),
]
}
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
let (parts, body) = response.into_parts();
let body = stream::unfold(
(body.into_data_stream(), counters),
|(mut body, c)| async move {
observe(c.clone(), body.next())
.await
.map(|chunk| (chunk, (body, c)))
},
);
Response::from_parts(parts, Body::from_stream(body))
}
fn notification(level: &str, event: &str, outcome: &str) -> Value {
json!({"jsonrpc":"2.0","method":"notifications/message","params":{
"level":level,"logger":"crank-mcp-server","data":{"event":event,"outcome":outcome}}})
}
async fn reply(response: reqwest::Response) -> (Value, Vec<Value>, String) {
let status = response.status();
assert!(
status == 200 || status == 404,
"unexpected HTTP status {status}"
);
let sse = response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("text/event-stream");
let raw = tokio::time::timeout(Duration::from_secs(5), response.text())
.await
.unwrap()
.unwrap();
let mut frames: Vec<Value> = if sse {
raw.lines()
.filter_map(|line| {
line.strip_prefix("data:")
.map(|s| serde_json::from_str(s.trim()).unwrap())
})
.collect()
} else {
vec![serde_json::from_str(&raw).unwrap()]
};
let terminal = frames.pop().expect("one terminal response");
assert_eq!(terminal["jsonrpc"], "2.0");
assert_eq!(terminal["id"], 51);
assert_eq!(
status.as_u16(),
if terminal["error"]["code"] == -32601 {
404
} else {
200
}
);
if !frames.is_empty() {
assert!(sse, "notifications require SSE");
}
assert!(frames.iter().all(|f| f.get("id").is_none()));
(terminal, frames, raw)
}
fn opted(level: Value) -> Value {
let mut meta = modern_meta();
meta[LEVEL] = level;
json!({"_meta":meta})
}
async fn control(revision: &str) -> [usize; 3] {
let h = Endpoint::started().await;
let session = h.session(revision).await;
let session = session.as_deref();
// Negative opt-in controls precede any accepted level; a silent response is not enough alone.
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
if revision == MODERN_REVISION {
for value in [
json!("verbose"),
json!(7),
json!(null),
json!("CANARY".repeat(1000)),
] {
let (body, events, _) =
reply(h.post(revision, session, "tools/list", opted(value)).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
}
let (body, events, _) = reply(
h.post(
revision,
session,
"logging/setLevel",
json!({"level":"notice"}),
)
.await,
)
.await;
assert_eq!(body["error"]["code"], -32601);
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
} else {
for params in [
json!({}),
json!({"level":7}),
json!({"level":"CANARY".repeat(1000)}),
] {
let (body, events, raw) =
reply(h.post(revision, session, "logging/setLevel", params).await).await;
assert_eq!(body["error"]["code"], -32602);
assert_eq!(body["error"]["message"], "invalid logging level");
assert!(body.get("result").is_none());
assert!(!raw.contains("CANARY"));
assert!(raw.len() < 4096);
assert!(events.is_empty());
assert_eq!(h.counters.sdk_logging_level(), 0);
assert_eq!(h.counters.sdk_logging_notification(), 0);
}
}
let before = counts(&h.counters);
let (method, params, expected) = if revision == LEGACY_REVISION {
(
"logging/setLevel",
json!({"level":"notice"}),
notification("notice", "mcp.logging.level_applied", "applied"),
)
} else {
(
"tools/list",
opted(json!("info")),
notification("info", "mcp.request.served", "ok"),
)
};
let (body, events, raw) = reply(h.post(revision, session, method, params).await).await;
assert!(body.get("error").is_none(), "{body}");
if revision == LEGACY_REVISION {
assert_eq!(body["result"], json!({}));
} else {
assert!(body["result"]["tools"].is_array());
}
assert_eq!(events, vec![expected]);
assert!(raw.len() < 4096);
let after = counts(&h.counters);
let delta = std::array::from_fn(|i| after[i] - before[i]);
// Legacy severity persists, modern opt-in does not leak into the next request.
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
h.registry
.revoke_platform_api_key(
&workspace_id(),
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
let before = counts(&h.counters);
let era = h.counters.snapshot();
let response = h
.post(
revision,
session,
method,
if revision == LEGACY_REVISION {
json!({"level":"notice"})
} else {
opted(json!("info"))
},
)
.await;
assert_eq!(response.status(), 401);
let raw = response.text().await.unwrap();
assert!(!raw.contains("notifications/message"));
assert_eq!(counts(&h.counters), before);
let after = h.counters.snapshot();
assert_eq!(after.era_modern, era.era_modern);
assert_eq!(after.era_legacy, era.era_legacy);
eprintln!(
"existing GREEN logging HTTP {revision}: safe SSE, result, opt-in/invalid/era/auth controls passed; SDK positive delta={delta:?}"
);
delta
}
#[tokio::test]
async fn rmcp_logging_wire_legacy() {
control(LEGACY_REVISION).await;
}
#[tokio::test]
async fn rmcp_logging_wire_modern() {
control(MODERN_REVISION).await;
}
#[tokio::test]
async fn rmcp_logging_sdk_legacy() {
assert_eq!(
control(LEGACY_REVISION).await,
[1, 1, 1],
"missing SDK legacy request/level/notification after successful HTTP wire assertions"
);
}
#[tokio::test]
async fn rmcp_logging_sdk_modern() {
assert_eq!(
control(MODERN_REVISION).await,
[0, 1, 1],
"missing SDK modern level/notification after successful HTTP wire assertions"
);
}
#[tokio::test]
async fn rmcp_logging_observer_scope_control() {
use super::{
sdk_logging_dispatch_enter, sdk_logging_level_parsed, sdk_logging_notification_serialized,
};
let a = Arc::new(CounterSet::default());
let b = Arc::new(CounterSet::default());
sdk_logging_dispatch_enter();
sdk_logging_level_parsed();
sdk_logging_notification_serialized();
assert_eq!(counts(&a), [0; 3]);
tokio::join!(
observe(a.clone(), async {
sdk_logging_dispatch_enter();
tokio::task::yield_now().await;
sdk_logging_level_parsed();
}),
observe(b.clone(), async {
sdk_logging_notification_serialized();
})
);
assert_eq!(counts(&a), [1, 1, 0]);
assert_eq!(counts(&b), [0, 0, 1]);
let body = Body::from_stream(stream::once(async {
sdk_logging_notification_serialized();
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
}));
let response = observe_body(Response::new(body), a.clone());
assert_eq!(counts(&a), [1, 1, 0]);
assert_eq!(
&axum::body::to_bytes(response.into_body(), 100)
.await
.unwrap()[..],
b"data: terminal\n\n"
);
assert_eq!(counts(&a), [1, 1, 1]);
assert_eq!(counts(&b), [0, 0, 1]);
}
@@ -0,0 +1,143 @@
//! Minimal logging HTTP fixture; shared registry/auth/lifecycle fixtures remain authoritative.
use super::*;
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
};
pub(super) struct Endpoint {
pub registry: crank_registry::PostgresRegistry,
pub counters: Arc<CounterSet>,
key: String,
url: String,
server: tokio::task::JoinHandle<()>,
}
impl Drop for Endpoint {
fn drop(&mut self) {
self.server.abort();
}
}
impl Endpoint {
pub async fn started() -> Self {
crank_test_support::postgres_schema_url_for_task("logging_owner", "t_c28c3800").await;
let registry = test_registry().await;
let operation = test_operation("http://127.0.0.1:9");
registry
.create_operation(&workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(crank_registry::PublishRequest {
workspace_id: &workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &test_time(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent(&registry, &operation).await;
let key = create_api_key(&registry).await;
let counters = Arc::new(CounterSet::default());
let app = crate::build_app(
registry.clone(),
Duration::ZERO,
Some("https://crank.example.com".into()),
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
Arc::new(crate::session::InMemorySessionStore::default()),
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
);
let scope = counters.clone();
let app = app.layer(axum::middleware::from_fn(
move |request: axum::extract::Request, next: axum::middleware::Next| {
let counters = scope.clone();
async move {
let response = observe(counters.clone(), next.run(request)).await;
observe_body(response, counters)
}
},
));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!(
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
listener.local_addr().unwrap()
);
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
Self {
registry,
counters,
key,
url,
server,
}
}
pub async fn post(
&self,
revision: &str,
session: Option<&str>,
method: &str,
mut params: Value,
) -> reqwest::Response {
let mut request = reqwest::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.header("Accept", "text/event-stream, application/json")
.header("MCP-Protocol-Version", revision);
if let Some(session) = session {
request = request.header("MCP-Session-Id", session);
}
if revision == MODERN_REVISION {
request = request.header("Mcp-Method", method);
if params.get("_meta").is_none() {
params["_meta"] = modern_meta();
}
}
request
.json(&json!({"jsonrpc":"2.0", "id":51, "method":method, "params":params}))
.send()
.await
.unwrap()
}
pub async fn session(&self, revision: &str) -> Option<String> {
if revision == MODERN_REVISION {
return None;
}
let response = self
.post(
revision,
None,
"initialize",
json!({"protocolVersion":revision,"capabilities":{}}),
)
.await;
assert_eq!(response.status(), 200);
let session = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
assert_eq!(
reply(response).await.0["result"]["protocolVersion"],
revision
);
let response = reqwest::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", revision)
.header("MCP-Session-Id", &session)
.json(&initialized_notification())
.send()
.await
.unwrap();
assert_eq!(response.status(), 202);
response.bytes().await.unwrap();
Some(session)
}
}
+2
View File
@@ -39,6 +39,8 @@ Prompts-срез #107 подключает `prompts/list` и `prompts/get` об
Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `completion/complete` обеих revisions к тому же request-scoped `app/rmcp_dispatch.rs`: настоящие `CompleteRequestParams`/`Reference`/`ArgumentInfo` передают reference и argument прежнему shared service. SDK context представляет только строки, поэтому исходный Crank JSON context сохраняется отдельно без фильтрации/приведения типов и проходит прежнюю domain validation. `app/response.rs` заменяет handwritten completion builder сериализацией `CompleteResult`/`CompletionInfo`, сохраняя omission `hasMore=false`, точный bounded total либо его отсутствие при partial scan и прежнюю внешнюю modern/legacy result projection. Потребитель — штатный `build_app` MCP HTTP JSON/SSE. Runtime ATDD отдельно наблюдает SDK request/result seam и сохранение Prompt/Resource refs, pinned/archive, populated/empty/bounded результатов, safe refusals/context, correlation/IDs и revoked-key rejection. Domain/storage/auth/envelopes/transport/lifecycle не меняются; signals/logging/subscriptions ещё не перенесены. Это не завершение #107, не external-client/feature qualification и не production deployment.
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
Проверяемый результат:
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.