Files
crank/crates/crank-community-mcp/src/app/lifecycle_tests.rs
T
bsodfather 48436538f1
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 41m28s
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
MCP: send progress through SDK Peer with private trace tokens
2026-11-14 11:22:32 +00:00

210 lines
7.5 KiB
Rust

//! Story 3.4 bounds that do not need the HTTP surface: token validation, the monotonic bounded
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
use super::*;
use serde_json::json;
fn token(value: Value) -> Option<ProgressToken> {
progress_token(&json!({ "_meta": { "progressToken": value } }))
}
#[tokio::test]
async fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
for wire_token in [
"\"token\"",
"-7",
"1.5",
"1.0",
"-0.0",
"18446744073709551615",
] {
let value: Value = serde_json::from_str(wire_token).unwrap();
for progress in [2, 9_007_199_254_740_993, u64::MAX] {
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(value.clone());
let frame = peer.notify(progress, "execution_dispatched").await.unwrap();
peer.finish().await;
assert_eq!(frame["params"]["progressToken"].to_string(), wire_token);
assert_eq!(
frame["params"]["progress"].to_string(),
progress.to_string()
);
assert_eq!(
frame["params"],
json!({
"progressToken": value, "progress": progress, "message": "execution_dispatched"
})
);
assert!(frame["params"].get("total").is_none());
assert!(frame["params"].get("_meta").is_none());
assert_eq!(frame["jsonrpc"], "2.0");
assert_eq!(frame["method"], "notifications/progress");
}
}
}
#[test]
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
assert_eq!(
token(json!("tok-1")),
Some(ProgressToken::Text("tok-1".to_owned()))
);
assert!(matches!(token(json!(7)), Some(ProgressToken::Number(_))));
assert!(matches!(token(json!(1.5)), Some(ProgressToken::Number(_))));
// Malformed and out-of-bound tokens disable progress instead of failing the call.
assert_eq!(token(json!("")), None);
assert_eq!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN + 1))), None);
assert_eq!(token(json!("line\nbreak")), None);
assert_eq!(token(json!(null)), None);
assert_eq!(token(json!(true)), None);
assert_eq!(token(json!({ "nested": 1 })), None);
assert_eq!(token(json!([1, 2])), None);
// A token at the bound is still accepted.
assert!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN))).is_some());
// Absent `_meta`, absent token and a non-object `_meta` are all "no progress".
assert_eq!(progress_token(&json!({})), None);
assert_eq!(progress_token(&json!({ "_meta": { "other": 1 } })), None);
assert_eq!(progress_token(&json!({ "_meta": "not-an-object" })), None);
}
#[tokio::test]
async fn real_steps_produce_strictly_increasing_bounded_progress_events() {
let (lifecycle, events) = ToolCallLifecycle::new(token(json!("tok-monotonic")));
let mut events = events.expect("a validated token opens the progress queue");
for phase in [Phase::Resolved, Phase::Authorized, Phase::Dispatching] {
lifecycle.advance(phase);
}
drop(lifecycle);
let mut observed = Vec::new();
while let Some(event) = events.recv().await {
observed.push((event.progress, event.message));
}
assert_eq!(
observed,
vec![
(1, "tool_resolved"),
(2, "authorization_resolved"),
(3, "execution_dispatched"),
]
);
assert!(
observed.windows(2).all(|pair| pair[0].0 < pair[1].0),
"progress must increase monotonically, got {observed:?}"
);
}
#[tokio::test]
async fn a_full_progress_queue_drops_events_instead_of_blocking_the_call() {
let (lifecycle, events) = ToolCallLifecycle::new(token(json!(9)));
let mut events = events.expect("a validated token opens the progress queue");
// Many more steps than the queue holds: the call must never wait for the reader.
for _ in 0..(PROGRESS_CAPACITY * 4) {
lifecycle.advance(Phase::Resolved);
}
let mut delivered = 0;
while events.try_recv().is_ok() {
delivered += 1;
}
assert_eq!(delivered, PROGRESS_CAPACITY);
}
#[tokio::test]
async fn without_a_token_no_progress_is_produced_at_all() {
let (lifecycle, events) = ToolCallLifecycle::new(None);
assert!(events.is_none());
lifecycle.advance(Phase::Resolved);
lifecycle.advance(Phase::Dispatching);
}
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
/// `total` absent because this server never invents one.
#[tokio::test]
async fn the_progress_frame_matches_the_pinned_notification_shape() {
let event = ProgressEvent {
progress: 2,
message: Phase::Authorized.message(),
};
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!("tok-2"));
assert_eq!(
peer.notify(event.progress, event.message).await.unwrap(),
json!({
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "tok-2",
"progress": 2,
"message": "authorization_resolved"
}
})
);
peer.finish().await;
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!(7));
assert_eq!(
peer.notify(event.progress, event.message).await.unwrap()["params"]["progressToken"],
json!(7)
);
peer.finish().await;
}
#[tokio::test]
async fn a_cancellation_only_reaches_the_call_of_the_same_session_and_credential() {
let registry = Arc::new(InFlightCalls::new(MAX_IN_FLIGHT_CALLS));
let scope = InFlightScope {
session_id: "sess-1".to_owned(),
owner: "pk_a".to_owned(),
};
let entry = registry
.register(&scope, &json!(42))
.expect("the table has room");
let mut signal = entry.cancel_signal();
// A foreign credential, a foreign session and a different request id cancel nothing.
for foreign in [
InFlightScope {
session_id: "sess-1".to_owned(),
owner: "pk_b".to_owned(),
},
InFlightScope {
session_id: "sess-2".to_owned(),
owner: "pk_a".to_owned(),
},
] {
assert!(!registry.cancel(&foreign, &json!(42)));
}
assert!(!registry.cancel(&scope, &json!(43)));
assert!(
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
.await
.is_err(),
"a foreign cancellation must not fire the signal"
);
assert!(registry.cancel(&scope, &json!(42)));
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
.await
.expect("the owner's cancellation fires the signal");
}
#[tokio::test]
async fn a_released_call_releases_its_slot_and_the_table_is_bounded() {
let registry = Arc::new(InFlightCalls::new(1));
let scope = InFlightScope {
session_id: "sess-1".to_owned(),
owner: "pk_a".to_owned(),
};
let entry = registry.register(&scope, &json!(1)).expect("first slot");
assert!(
registry.register(&scope, &json!(2)).is_none(),
"the table refuses a call beyond its bound instead of evicting the live one"
);
assert!(registry.cancel(&scope, &json!(1)));
drop(entry);
assert!(
!registry.cancel(&scope, &json!(1)),
"a terminal call is no longer cancellable"
);
assert!(registry.register(&scope, &json!(2)).is_some());
}