Files
crank/crates/crank-community-mcp/src/rmcp_tools_handler_tests.rs
T
bsodfather 3b30aad28e
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 35m42s
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: execute Tools through request-scoped SDK handlers
2026-11-13 16:57:28 +00:00

326 lines
13 KiB
Rust

//! Real trait-result consumption controls and request-owned cancellation.
use super::*;
use serde_json::json;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
#[derive(Default)]
pub(super) struct Domain {
outcome: Mutex<Option<ToolsOutcome>>,
calls: AtomicUsize,
pending: bool,
started: tokio::sync::Notify,
dropped: AtomicBool,
}
struct Witness<'a>(&'a AtomicBool);
impl Drop for Witness<'_> {
fn drop(&mut self) {
self.0.store(true, SeqCst);
}
}
impl Domain {
pub(super) async fn execute(&self, scope: &Scope, command: ToolsCommand) -> ToolsOutcome {
self.calls.fetch_add(1, SeqCst);
assert_eq!(scope.workspace, "workspace");
assert_eq!(scope.agent, "agent");
assert_eq!(
scope
.credential
.platform_api_key_id
.as_ref()
.unwrap()
.as_str(),
"key"
);
assert_eq!(scope.locale, ExecutionLocale::En);
match command {
ToolsCommand::List(list) => {
assert_eq!(list.cursor.as_deref(), Some("cursor"));
assert_eq!(list.limit, Some(7));
}
ToolsCommand::Call(call) => {
assert_eq!(call.tool_name, "bound");
assert_eq!(call.arguments, json!({"number":42,"nested":[null]}));
assert_eq!(call.confirmation_token.as_deref(), Some("confirmation"));
assert!(scope.lifecycle.is_some());
}
}
let _witness = Witness(&self.dropped);
self.started.notify_one();
if self.pending {
std::future::pending::<()>().await;
}
self.outcome
.lock()
.unwrap()
.take()
.expect("one domain call")
}
}
fn scope() -> Scope {
Scope {
workspace: "workspace".into(),
agent: "agent".into(),
credential: VerifiedMachineCredential {
machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey,
max_security_level: crank_core::OperationSecurityLevel::Standard,
scopes: vec![crank_core::PlatformApiKeyScope::Read],
platform_api_key_id: Some("key".into()),
},
correlation: CorrelationContext::generate(),
continuation: ContinuationSupport::ElicitationUnsupported,
locale: ExecutionLocale::En,
limit: Some(7),
confirmation: Some("confirmation".into()),
lifecycle: Some(ToolCallLifecycle::new(None).0),
}
}
async fn state() -> Arc<AppState> {
crank_test_support::postgres_schema_url_for_task("tools_handler_local", "t_75a3342f").await;
super::super::rmcp_tools_tests::test_state().await
}
fn handler(state: &Arc<AppState>, outcome: ToolsOutcome) -> Handler {
let mut h = Handler::new(state);
h.domain = Some(Arc::new(Domain {
outcome: Mutex::new(Some(outcome)),
..Default::default()
}));
h
}
async fn context(h: &Handler) -> RequestContext<RoleServer> {
let context = request_context(h, scope()).await.unwrap();
assert!(context.peer.is_transport_closed());
assert_eq!(Arc::strong_count(&h.extras), 1);
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 0);
context
}
fn call() -> CallToolRequestParams {
CallToolRequestParams::new("bound").with_arguments(
json!({"number":42,"nested":[null]})
.as_object()
.unwrap()
.clone(),
)
}
fn payload(outcome: Outcome, version: &str) -> Value {
match super::super::response::sdk_tools_payload(&json!({"id":17}), version, outcome) {
super::super::response::ToolCommandPayload::Ok(value) => value,
_ => panic!("expected wire payload"),
}
}
#[tokio::test]
async fn rmcp_tools_handler_list_typed_mutation_and_lossless_catalog() {
let state = state().await;
for version in ["2025-11-25", "2026-07-28"] {
let raw = json!({"name":"original","inputSchema":{"type":"object"},"description":null,
"annotations":{"readOnlyHint":true,"x-extra":[null]},"icons":null,"x-tool":{}});
let h = handler(
&state,
ToolsOutcome::List {
tools: vec![raw.clone()],
next_cursor: Some("next".into()),
},
);
let mut result = ServerHandler::list_tools(
&h,
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
context(&h).await,
)
.await
.unwrap();
result.tools[0].name = "mutated".into();
result.tools[0].description = Some("typed description".into());
result.next_cursor = Some("changed".into());
let wire = payload(
projection::consume_list(Ok(result), h.take_extras()),
version,
);
let mut expected = raw;
expected["name"] = json!("mutated");
expected["description"] = json!("typed description");
assert_eq!(wire["result"]["tools"], json!([expected]));
assert_eq!(wire["result"]["nextCursor"], "changed");
assert_eq!(
wire["result"].get("resultType").is_some(),
version == "2026-07-28"
);
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
}
}
#[tokio::test]
async fn rmcp_tools_handler_call_typed_content_structured_and_is_error_mutations() {
let state = state().await;
for version in ["2025-11-25", "2026-07-28"] {
for original in [
ToolCallOutcome::Completed(Value::Null),
ToolCallOutcome::ApprovalPending(json!({"approval":true})),
] {
let h = handler(&state, ToolsOutcome::Call(original));
let result = ServerHandler::call_tool(&h, call(), context(&h).await)
.await
.unwrap();
let CallToolResponse::Complete(mut result) = result else {
panic!("complete result");
};
result.content = vec![ContentBlock::text("typed content")];
result.structured_content = Some(json!({"typed":42}));
result.is_error = Some(true);
let wire = payload(projection::consume_call(Ok(result.into())), version);
assert_eq!(
wire["result"]["content"],
json!([{"type":"text","text":"typed content"}])
);
assert_eq!(wire["result"]["structuredContent"], json!({"typed":42}));
assert_eq!(wire["result"]["isError"], true);
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
}
}
}
#[tokio::test]
async fn rmcp_tools_handler_typed_list_and_call_errors_are_consumed() {
let state = state().await;
for version in ["2025-11-25", "2026-07-28"] {
let h = handler(&state, ToolsOutcome::InvalidParams("original list".into()));
let result = ServerHandler::list_tools(
&h,
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
context(&h).await,
)
.await;
let mut error = result.unwrap_err();
error.message = "mutated list".into();
error.data = Some(json!({"typed":true}));
let wire = payload(
projection::consume_list(Err(error), h.take_extras()),
version,
);
assert_eq!(wire["error"]["message"], "mutated list");
assert_eq!(wire["error"]["data"], json!({"typed":true}));
let h = handler(
&state,
ToolsOutcome::Call(ToolCallOutcome::InvalidParams("original call".into())),
);
let mut error = ServerHandler::call_tool(&h, call(), context(&h).await)
.await
.unwrap_err();
error.code = ErrorCode(-32001);
error.message = "mutated call".into();
error.data = Some(json!({"typed":42}));
let wire = payload(projection::consume_call(Err(error)), version);
assert_eq!(wire["error"]["code"], -32001);
assert_eq!(wire["error"]["message"], "mutated call");
assert_eq!(wire["error"]["data"], json!({"typed":42}));
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
}
}
#[tokio::test]
async fn rmcp_tools_handler_domain_outcomes_keep_wire_semantics() {
use crate::tool_error::{McpControlError, control_tool_error_contract};
let state = state().await;
for version in ["2025-11-25", "2026-07-28"] {
for kind in 0..6 {
let outcome = || match kind {
0 => ToolCallOutcome::Completed(Value::Null),
1 => ToolCallOutcome::ApprovalPending(json!({"approval":"pending"})),
2 => ToolCallOutcome::ApprovalUnavailable(
McpControlError::ApprovalElicitationNotSupported,
),
3 => ToolCallOutcome::Error(control_tool_error_contract(
McpControlError::CatalogRevisionChanged,
"request",
"trace",
ExecutionLocale::En,
)),
4 => ToolCallOutcome::InvalidParams("invalid argument".into()),
_ => ToolCallOutcome::InternalFailure,
};
let h = handler(&state, ToolsOutcome::Call(outcome()));
let ctx = context(&h).await;
let correlation = Handler::scope(&ctx).unwrap().correlation;
let result = ServerHandler::call_tool(&h, call(), ctx).await;
let actual = payload(projection::consume_call(result), version);
let expected = super::super::response::tool_command_payload(
&json!({"id":17}),
version,
&correlation,
ToolsOutcome::Call(outcome()),
);
match expected {
super::super::response::ToolCommandPayload::Ok(expected) => {
assert_eq!(actual, expected)
}
super::super::response::ToolCommandPayload::Internal(_) => {
assert_eq!(actual["error"]["code"], -32603);
assert_eq!(actual["error"]["message"], "internal server error");
}
}
assert_eq!(h.domain.as_ref().unwrap().calls.load(SeqCst), 1);
}
for raw in [
json!({"name":"tool","inputSchema":{},"description":null,"_meta":null,"annotations":{},"icons":[]}),
json!({"name":"tool","inputSchema":{},"annotations":{"x-annotation":null},"icons":null,"x-tool":[null,{}]}),
] {
let h = handler(
&state,
ToolsOutcome::List {
tools: vec![raw.clone()],
next_cursor: Some(String::new()),
},
);
let result = ServerHandler::list_tools(
&h,
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
context(&h).await,
)
.await;
let wire = payload(projection::consume_list(result, h.take_extras()), version);
assert_eq!(wire["result"]["tools"], json!([raw]));
assert_eq!(wire["result"]["nextCursor"], "");
}
}
}
#[tokio::test]
async fn rmcp_tools_handler_pending_domain_dropped_with_parent_and_identity_is_local() {
let state = state().await;
for list in [false, true] {
let mut h = Handler::new(&state);
h.domain = Some(Arc::new(Domain {
pending: true,
..Default::default()
}));
let ctx = context(&h).await;
let other = request_context(
&h,
Scope {
agent: "other-agent".into(),
..scope()
},
)
.await
.unwrap();
assert_eq!(Handler::scope(&ctx).unwrap().agent, "agent");
assert_eq!(Handler::scope(&other).unwrap().agent, "other-agent");
let parent = async {
if list {
let _ = ServerHandler::list_tools(
&h,
Some(PaginatedRequestParams::default().with_cursor(Some("cursor".into()))),
ctx,
)
.await;
} else {
let _ = ServerHandler::call_tool(&h, call(), ctx).await;
}
};
let domain = h.domain.as_ref().unwrap();
{
let parent = parent;
tokio::pin!(parent);
tokio::select! { _ = domain.started.notified() => {}, _ = &mut parent => panic!("pending domain completed") }
assert!(!domain.dropped.load(SeqCst));
}
assert!(domain.dropped.load(SeqCst));
assert_eq!(domain.calls.load(SeqCst), 1);
}
}