diff --git a/crates/crank-community-mcp/src/app.rs b/crates/crank-community-mcp/src/app.rs index 9809e2f..b055bd7 100644 --- a/crates/crank-community-mcp/src/app.rs +++ b/crates/crank-community-mcp/src/app.rs @@ -50,6 +50,8 @@ mod rmcp_resources_projection; mod rmcp_session_tests; #[cfg(test)] mod rmcp_tools; +mod rmcp_tools_projection; +mod rmcp_tools_runtime; #[cfg(test)] #[path = "rmcp_tools_tests.rs"] mod rmcp_tools_tests; diff --git a/crates/crank-community-mcp/src/app/dispatch.rs b/crates/crank-community-mcp/src/app/dispatch.rs index 389cec4..0df9bdf 100644 --- a/crates/crank-community-mcp/src/app/dispatch.rs +++ b/crates/crank-community-mcp/src/app/dispatch.rs @@ -17,8 +17,8 @@ use crate::{ CompletionCommand, CompletionOutcome, ContinuationSupport, DispatchDecision, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome, - ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, - declared_mcp_method, discover_result, validate_modern_request_name, + ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, declared_mcp_method, + discover_result, validate_modern_request_name, }, session::SessionState, tool_error::execution_locale, @@ -38,7 +38,7 @@ use time::OffsetDateTime; use super::response::{ completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result, prompts_list_result, resource_error_response, resource_read_result, - resource_templates_list_result, resources_list_result, tools_list_result, + resource_templates_list_result, resources_list_result, }; use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS}; use crate::protocol::ResourceTemplatesListError; @@ -170,36 +170,7 @@ pub(super) async fn handle_modern_request( None, ) .await; - match outcome { - ToolsOutcome::List { tools, next_cursor } => { - match tools_list_result(tools, next_cursor, version) { - Ok(result) => transport_response( - StatusCode::OK, - jsonrpc_result(request_id(message), result), - response_mode, - None, - Some(version), - ), - Err(error) => internal_jsonrpc_error(message, error), - } - } - ToolsOutcome::InvalidParams(message_text) => transport_response( - StatusCode::OK, - jsonrpc_error(request_id(message), -32602, message_text), - response_mode, - None, - Some(version), - ), - ToolsOutcome::CatalogUnavailable => { - internal_jsonrpc_error(message, "published catalog is unavailable") - } - // A list command never produces a call outcome; it is answered with the adapter's - // internal error instead of being silently ignored. - ToolsOutcome::Call(_) => internal_jsonrpc_error( - message, - "unexpected shared tools outcome for a tools/list", - ), - } + super::response::sdk_tools_response(message, response_mode, version, outcome) } DispatchDecision::Allowed { handler: MethodHandler::ToolCall, diff --git a/crates/crank-community-mcp/src/app/dispatch_observer.rs b/crates/crank-community-mcp/src/app/dispatch_observer.rs index e16971c..c15a6d5 100644 --- a/crates/crank-community-mcp/src/app/dispatch_observer.rs +++ b/crates/crank-community-mcp/src/app/dispatch_observer.rs @@ -54,6 +54,10 @@ pub(crate) struct CounterSet { sdk_tools_dispatch: AtomicUsize, sdk_tools_list_result: AtomicUsize, sdk_tools_call_result: AtomicUsize, + sdk_tools_list_handler_completed: AtomicUsize, + sdk_tools_list_handler_consumed: AtomicUsize, + sdk_tools_call_handler_completed: AtomicUsize, + sdk_tools_call_handler_consumed: AtomicUsize, sdk_resources_dispatch: AtomicUsize, sdk_resources_list_handler_completed: AtomicUsize, sdk_resources_read_handler_completed: AtomicUsize, @@ -101,6 +105,18 @@ pub(crate) struct CounterSet { } impl CounterSet { + pub(crate) fn sdk_tools_list_handler_completed(&self) -> usize { + self.sdk_tools_list_handler_completed.load(Ordering::SeqCst) + } + pub(crate) fn sdk_tools_list_handler_consumed(&self) -> usize { + self.sdk_tools_list_handler_consumed.load(Ordering::SeqCst) + } + pub(crate) fn sdk_tools_call_handler_completed(&self) -> usize { + self.sdk_tools_call_handler_completed.load(Ordering::SeqCst) + } + pub(crate) fn sdk_tools_call_handler_consumed(&self) -> usize { + self.sdk_tools_call_handler_consumed.load(Ordering::SeqCst) + } pub(crate) fn sdk_prompts_list_handler_completed(&self) -> usize { self.sdk_prompts_list_handler_completed .load(Ordering::SeqCst) @@ -366,6 +382,23 @@ pub(crate) fn sdk_tools_call_result_serialized() { increment(|counters| &counters.sdk_tools_call_result); } +/// Mark after the SDK Tools handler awaits the domain operation and builds its typed result. +pub(crate) fn sdk_tools_list_handler_completed() { + increment(|counters| &counters.sdk_tools_list_handler_completed); +} +/// Mark only after the caller consumes the actual SDK handler result. +pub(crate) fn sdk_tools_list_handler_consumed() { + increment(|counters| &counters.sdk_tools_list_handler_consumed); +} +/// Mark after the SDK Tools handler awaits the domain operation and builds its typed result. +pub(crate) fn sdk_tools_call_handler_completed() { + increment(|counters| &counters.sdk_tools_call_handler_completed); +} +/// Mark only after the caller consumes the actual SDK handler result. +pub(crate) fn sdk_tools_call_handler_consumed() { + increment(|counters| &counters.sdk_tools_call_handler_consumed); +} + /// Mark inside the ServerHandler override after domain await and typed result/error construction. pub(crate) fn sdk_resources_list_handler_completed() { increment(|c| &c.sdk_resources_list_handler_completed); diff --git a/crates/crank-community-mcp/src/app/legacy_dispatch.rs b/crates/crank-community-mcp/src/app/legacy_dispatch.rs index 22cde24..119ad2e 100644 --- a/crates/crank-community-mcp/src/app/legacy_dispatch.rs +++ b/crates/crank-community-mcp/src/app/legacy_dispatch.rs @@ -22,7 +22,6 @@ use super::response::{ completion_result, internal_jsonrpc_error, prompt_arguments_error_response, prompt_get_result, prompts_list_result, resource_error_response, resource_read_result, resource_templates_list_result, resources_list_result, take_confirmation_token, - tools_list_result, }; use super::rmcp_dispatch::{ handle_resources_command, handle_tools_command, list_resource_templates, @@ -36,7 +35,7 @@ use crate::{ EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand, - ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_logging_command, + ToolCallCommand, ToolsCommand, ToolsListCommand, handle_logging_command, }, tool_error::execution_locale, transport::{ResponseMode, session_id_from_headers, transport_response}, @@ -159,36 +158,12 @@ pub(super) async fn handle_legacy_request( None, ) .await; - match outcome { - ToolsOutcome::List { tools, next_cursor } => { - match tools_list_result(tools, next_cursor, &session.protocol_version) { - Ok(result) => transport_response( - StatusCode::OK, - jsonrpc_result(request_id(message), result), - response_mode, - None, - Some(&session.protocol_version), - ), - Err(error) => internal_jsonrpc_error(message, error), - } - } - ToolsOutcome::InvalidParams(message_text) => transport_response( - StatusCode::OK, - jsonrpc_error(request_id(message), -32602, message_text), - response_mode, - None, - Some(&session.protocol_version), - ), - ToolsOutcome::CatalogUnavailable => { - internal_jsonrpc_error(message, "published catalog is unavailable") - } - // A list command never produces a call outcome; it is answered with the adapter's - // internal error instead of being silently ignored. - ToolsOutcome::Call(_) => internal_jsonrpc_error( - message, - "unexpected shared tools outcome for a tools/list", - ), - } + super::response::sdk_tools_response( + message, + response_mode, + &session.protocol_version, + outcome, + ) } DispatchDecision::Allowed { handler: MethodHandler::ToolCall, diff --git a/crates/crank-community-mcp/src/app/lifecycle.rs b/crates/crank-community-mcp/src/app/lifecycle.rs index 459b386..72fd36d 100644 --- a/crates/crank-community-mcp/src/app/lifecycle.rs +++ b/crates/crank-community-mcp/src/app/lifecycle.rs @@ -41,11 +41,11 @@ use tokio::sync::{mpsc, watch}; use super::rmcp_dispatch::handle_tools_command; use super::{ AppState, - response::{ToolCommandPayload, tool_command_payload, tool_command_response}, + response::{ToolCommandPayload, sdk_tools_payload, sdk_tools_response}, }; use crate::{ jsonrpc::request_id, - protocol::{ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsOutcome}, + protocol::{ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand}, transport::{ResponseMode, sse_response}, }; @@ -393,7 +393,7 @@ pub(crate) async fn run_tool_call( }); let message = wire.message.clone(); - let correlation = request.correlation.clone(); + let protocol_version = wire.protocol_version.clone(); let response_mode = wire.response_mode; @@ -411,13 +411,7 @@ pub(crate) async fn run_tool_call( outcome = &mut call => outcome, _ = lifecycle.cancelled() => return cancelled_response(), }; - return tool_command_response( - &message, - response_mode, - &protocol_version, - &correlation, - outcome, - ); + return sdk_tools_response(&message, response_mode, &protocol_version, outcome); }; debug_assert!(matches!(response_mode, ResponseMode::Sse)); @@ -430,7 +424,6 @@ pub(crate) async fn run_tool_call( token, message, protocol_version: protocol_version.clone(), - correlation, pending: VecDeque::new(), finished: false, logging: crate::protocol::carry_scope(), @@ -451,7 +444,7 @@ async fn call_future( request: ToolCallRequest, lifecycle: ToolCallLifecycle, command: ToolCallCommand, -) -> ToolsOutcome { +) -> super::rmcp_tools_runtime::Outcome { handle_tools_command( &state, ServiceContext { @@ -478,13 +471,12 @@ fn cancelled_response() -> Response { } struct CallStream { - call: Pin + Send>>, + call: Pin + Send>>, events: mpsc::Receiver, cancel: CancelSignal, token: ProgressToken, message: Value, protocol_version: String, - correlation: CorrelationContext, pending: VecDeque, finished: bool, /// The request's logging context, so the terminal event of the stream is projected exactly as the @@ -496,7 +488,7 @@ struct CallStream { enum Step { Progress(ProgressEvent), - Outcome(ToolsOutcome), + Outcome(super::rmcp_tools_runtime::Outcome), Cancelled, } @@ -541,12 +533,7 @@ async fn next_event_in_scope( } Step::Outcome(outcome) => { call.finished = true; - let payload = match tool_command_payload( - &call.message, - &call.protocol_version, - &call.correlation, - outcome, - ) { + let payload = match sdk_tools_payload(&call.message, &call.protocol_version, outcome) { ToolCommandPayload::Ok(payload) => payload, ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message), }; diff --git a/crates/crank-community-mcp/src/app/response.rs b/crates/crank-community-mcp/src/app/response.rs index 747dc38..0ab9733 100644 --- a/crates/crank-community-mcp/src/app/response.rs +++ b/crates/crank-community-mcp/src/app/response.rs @@ -1,5 +1,7 @@ use axum::{http::StatusCode, response::Response}; -use rmcp::model::{CacheScope, CallToolResult, ContentBlock, ListToolsResult, ResultType, Tool}; +#[cfg(test)] +use rmcp::model::{CacheScope, ListToolsResult, Tool}; +use rmcp::model::{CallToolResult, ContentBlock, ResultType}; use serde_json::{Value, json}; use crate::{ @@ -9,8 +11,11 @@ use crate::{ }; use crate::jsonrpc::jsonrpc_error; +#[cfg(test)] use crate::protocol::{ToolCallOutcome, ToolsOutcome}; +#[cfg(test)] use crate::tool_error::{control_tool_error_contract, execution_locale}; +#[cfg(test)] use crank_core::CorrelationContext; pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option { @@ -25,6 +30,7 @@ pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option { /// The era-neutral success payload of one `tools/call` (Story 3.4: the streamed response needs the /// payload itself, because the terminal response is the last event of the request's stream). +#[cfg(test)] pub(super) fn success_tool_payload( message: &Value, protocol_version: &str, @@ -49,6 +55,7 @@ pub(crate) fn tool_error_response( ) } +#[cfg(test)] pub(super) fn tool_error_payload( message: &Value, protocol_version: &str, @@ -79,6 +86,7 @@ fn call_result_payload(message: &Value, version: &str, mut result: CallToolResul jsonrpc_result(request_id(message), result) } +#[cfg(test)] pub(super) fn sdk_tools_list_result( tools: &[Value], next_cursor: Option, @@ -95,6 +103,7 @@ pub(super) fn sdk_tools_list_result( } /// Serialize the SDK model, preserving catalog extensions that pinned Tool serde cannot represent. +#[cfg(test)] pub(super) fn tools_list_result( tools: Vec, next_cursor: Option, @@ -256,6 +265,7 @@ pub(super) enum ToolCommandPayload { /// service never sees `ResponseMode`, the protocol revision, the request envelope or an /// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while /// an unavailable elicitation and a failing call keep their era-correct tool-error shape. +#[cfg(test)] pub(super) fn tool_command_payload( message: &Value, protocol_version: &str, @@ -300,22 +310,53 @@ pub(super) fn tool_command_payload( } } -/// The single-response form of [`tool_command_payload`]. -pub(super) fn tool_command_response( +pub(super) fn sdk_tools_payload( message: &Value, - response_mode: ResponseMode, - protocol_version: &str, - correlation: &CorrelationContext, - outcome: ToolsOutcome, + version: &str, + outcome: super::rmcp_tools_runtime::Outcome, +) -> ToolCommandPayload { + use super::rmcp_tools_runtime::Outcome; + let payload = match outcome { + Outcome::List { result, extras } => { + match super::rmcp_tools_projection::serialize_list(result, extras, version) { + Ok(result) => jsonrpc_result(request_id(message), result), + Err(_) => return ToolCommandPayload::Internal("invalid tool catalog"), + } + } + Outcome::Call(result) => call_result_payload(message, version, result), + Outcome::Error(error) => sdk_tools_error_payload(message, error), + }; + ToolCommandPayload::Ok(payload) +} +pub(super) fn sdk_tools_error_payload(message: &Value, error: rmcp::ErrorData) -> Value { + let mut payload = jsonrpc_error( + request_id(message), + i64::from(error.code.0), + error.message.to_string(), + ); + if let Some(data) = error.data { + payload["error"]["data"] = data; + } + payload +} +pub(super) fn sdk_tools_response( + message: &Value, + mode: ResponseMode, + version: &str, + outcome: super::rmcp_tools_runtime::Outcome, ) -> Response { - match tool_command_payload(message, protocol_version, correlation, outcome) { - ToolCommandPayload::Ok(payload) => transport_response( - StatusCode::OK, + let internal = matches!(&outcome, super::rmcp_tools_runtime::Outcome::Error(error) if error.code == rmcp::model::ErrorCode::INTERNAL_ERROR); + match sdk_tools_payload(message, version, outcome) { + ToolCommandPayload::Ok(payload) if internal => transport_response( + StatusCode::INTERNAL_SERVER_ERROR, payload, - response_mode, + ResponseMode::Json, + None, None, - Some(protocol_version), ), + ToolCommandPayload::Ok(payload) => { + transport_response(StatusCode::OK, payload, mode, None, Some(version)) + } ToolCommandPayload::Internal(detail) => internal_jsonrpc_error(message, detail), } } diff --git a/crates/crank-community-mcp/src/app/rmcp_dispatch.rs b/crates/crank-community-mcp/src/app/rmcp_dispatch.rs index 76d5808..d95e760 100644 --- a/crates/crank-community-mcp/src/app/rmcp_dispatch.rs +++ b/crates/crank-community-mcp/src/app/rmcp_dispatch.rs @@ -2,68 +2,18 @@ use std::sync::Arc; -use rmcp::model::{CallToolRequestParams, PaginatedRequestParams}; use serde_json::Value; use super::{AppState, lifecycle::ToolCallLifecycle}; -use crate::protocol::{ - ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand, ToolsListCommand, ToolsOutcome, -}; - -// Crank extensions are not SDK fields and must survive the typed request boundary unchanged. -enum SdkToolsCommand { - List { - params: PaginatedRequestParams, - limit: Option, - }, - Call { - params: CallToolRequestParams, - confirmation_token: Option, - }, -} +use crate::protocol::{ServiceContext, ToolsCommand}; pub(super) async fn handle_tools_command( state: &Arc, context: ServiceContext<'_>, command: ToolsCommand, lifecycle: Option, -) -> ToolsOutcome { - let request = match command { - ToolsCommand::List(list) => SdkToolsCommand::List { - params: PaginatedRequestParams::default().with_cursor(list.cursor), - limit: list.limit, - }, - ToolsCommand::Call(call) => { - let Value::Object(arguments) = call.arguments else { - return ToolsOutcome::Call(ToolCallOutcome::InvalidParams( - "tool arguments must be an object".to_owned(), - )); - }; - SdkToolsCommand::Call { - params: CallToolRequestParams::new(call.tool_name).with_arguments(arguments), - confirmation_token: call.confirmation_token, - } - } - }; - - #[cfg(test)] - super::dispatch_observer::sdk_tools_dispatch_enter(); - - let command = match request { - SdkToolsCommand::List { params, limit } => ToolsCommand::List(ToolsListCommand { - cursor: params.cursor, - limit, - }), - SdkToolsCommand::Call { - params, - confirmation_token, - } => ToolsCommand::Call(ToolCallCommand { - tool_name: params.name.into_owned(), - arguments: Value::Object(params.arguments.unwrap_or_default()), - confirmation_token, - }), - }; - crate::protocol::handle_tools_command(state, context, command, lifecycle).await +) -> super::rmcp_tools_runtime::Outcome { + super::rmcp_tools_runtime::handle(state, context, command, lifecycle).await } pub(super) async fn handle_prompts_command( diff --git a/crates/crank-community-mcp/src/app/rmcp_tools_projection.rs b/crates/crank-community-mcp/src/app/rmcp_tools_projection.rs new file mode 100644 index 0000000..839ec73 --- /dev/null +++ b/crates/crank-community-mcp/src/app/rmcp_tools_projection.rs @@ -0,0 +1,85 @@ +//! Lossless catalog extras only; represented SDK fields remain authoritative. +use rmcp::{ErrorData, model::*}; +use serde_json::{Map, Value}; + +pub(super) type Extras = Vec>; +pub(super) enum Outcome { + List { + result: ListToolsResult, + extras: Extras, + }, + Call(CallToolResult), + Error(ErrorData), +} +pub(super) fn internal() -> ErrorData { + ErrorData::internal_error("internal server error", None) +} +pub(super) fn list( + tools: Vec, + next_cursor: Option, +) -> Result<(ListToolsResult, Extras), ErrorData> { + let mut extras = Vec::with_capacity(tools.len()); + let mut typed = Vec::with_capacity(tools.len()); + for tool in tools { + let mut raw = tool.as_object().cloned().ok_or_else(internal)?; + let mut extra = Map::new(); + for key in raw.keys().cloned().collect::>() { + if !matches!( + key.as_str(), + "name" | "title" | "description" | "inputSchema" | "outputSchema" | "_meta" + ) || raw[&key].is_null() + { + extra.insert(key.clone(), raw.remove(&key).expect("existing field")); + } + } + typed.push(serde_json::from_value(Value::Object(raw)).map_err(|_| internal())?); + extras.push(extra); + } + Ok(( + ListToolsResult { + tools: typed, + next_cursor, + ..Default::default() + }, + extras, + )) +} +pub(super) fn consume_list(result: Result, extras: Extras) -> Outcome { + match result { + Ok(result) => Outcome::List { result, extras }, + Err(error) => Outcome::Error(error), + } +} +pub(super) fn serialize_list( + mut result: ListToolsResult, + extras: Extras, + version: &str, +) -> Result { + let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION; + result.result_type = modern.then_some(ResultType::COMPLETE); + result.ttl_ms = modern.then_some(0); + result.cache_scope = modern.then_some(CacheScope::Private); + let mut result = serde_json::to_value(result)?; + for (tool, extras) in result["tools"] + .as_array_mut() + .expect("SDK tools array") + .iter_mut() + .zip(extras) + { + let tool = tool.as_object_mut().expect("SDK Tool object"); + for (key, value) in extras { + tool.entry(key).or_insert(value); + } + } + #[cfg(test)] + super::dispatch_observer::sdk_tools_list_result_serialized(); + Ok(result) +} + +pub(super) fn consume_call(result: Result) -> Outcome { + match result { + Ok(CallToolResponse::Complete(result)) => Outcome::Call(result), + Ok(_) => Outcome::Error(internal()), + Err(error) => Outcome::Error(error), + } +} diff --git a/crates/crank-community-mcp/src/app/rmcp_tools_runtime.rs b/crates/crank-community-mcp/src/app/rmcp_tools_runtime.rs new file mode 100644 index 0000000..2e2c0ff --- /dev/null +++ b/crates/crank-community-mcp/src/app/rmcp_tools_runtime.rs @@ -0,0 +1,237 @@ +//! Request-owned Tools trait execution. The caller retains admission and lifecycle ownership. +use super::{AppState, lifecycle::ToolCallLifecycle, rmcp_tools_projection as projection}; +use crate::{ + auth::VerifiedMachineCredential, + protocol::{self, *}, +}; +use crank_core::{CorrelationContext, ExecutionLocale}; +pub(super) use projection::Outcome; +use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext}; +use serde_json::Value; +use std::sync::{Arc, Mutex}; + +#[derive(Clone)] +struct Scope { + workspace: String, + agent: String, + credential: VerifiedMachineCredential, + correlation: CorrelationContext, + continuation: ContinuationSupport, + locale: ExecutionLocale, + limit: Option, + confirmation: Option, + lifecycle: Option, +} +impl Scope { + fn context(&self) -> ServiceContext<'_> { + ServiceContext { + workspace_slug: &self.workspace, + agent_slug: &self.agent, + credential: &self.credential, + correlation: &self.correlation, + continuation: self.continuation, + locale: self.locale, + } + } +} +#[derive(Clone)] +struct Handler { + state: Arc, + extras: Arc>, + #[cfg(test)] + domain: Option>, +} +impl Handler { + fn new(state: &Arc) -> Self { + Self { + state: state.clone(), + extras: Arc::new(Mutex::new(Vec::new())), + #[cfg(test)] + domain: None, + } + } + async fn execute(&self, scope: &Scope, command: ToolsCommand) -> ToolsOutcome { + #[cfg(test)] + if let Some(domain) = &self.domain { + return domain.execute(scope, command).await; + } + protocol::handle_tools_command( + &self.state, + scope.context(), + command, + scope.lifecycle.clone(), + ) + .await + } + fn scope(context: &RequestContext) -> Result { + context + .extensions + .get::() + .cloned() + .ok_or_else(projection::internal) + } + fn take_extras(&self) -> projection::Extras { + self.extras + .lock() + .expect("request-local extras") + .drain(..) + .collect() + } +} +impl ServerHandler for Handler { + async fn list_tools( + &self, + request: Option, + context: RequestContext, + ) -> Result { + let scope = Self::scope(&context)?; + let outcome = self + .execute( + &scope, + ToolsCommand::List(ToolsListCommand { + cursor: request.unwrap_or_default().cursor, + limit: scope.limit, + }), + ) + .await; + let result = match outcome { + ToolsOutcome::List { tools, next_cursor } => projection::list(tools, next_cursor) + .and_then(|(result, extras)| { + *self.extras.lock().map_err(|_| projection::internal())? = extras; + Ok(result) + }), + ToolsOutcome::InvalidParams(detail) => Err(ErrorData::invalid_params(detail, None)), + _ => Err(projection::internal()), + }; + #[cfg(test)] + super::dispatch_observer::sdk_tools_list_handler_completed(); + result + } + async fn call_tool( + &self, + request: CallToolRequestParams, + context: RequestContext, + ) -> Result { + let scope = Self::scope(&context)?; + let outcome = self + .execute( + &scope, + ToolsCommand::Call(ToolCallCommand { + tool_name: request.name.into_owned(), + arguments: Value::Object(request.arguments.unwrap_or_default()), + confirmation_token: scope.confirmation.clone(), + }), + ) + .await; + let result = match outcome { + ToolsOutcome::Call( + ToolCallOutcome::Completed(output) | ToolCallOutcome::ApprovalPending(output), + ) => Ok(super::response::sdk_success_tool_result(output).into()), + ToolsOutcome::Call(ToolCallOutcome::Error(error)) => { + Ok(super::response::sdk_error_tool_result(error).into()) + } + ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(error)) => { + Ok(super::response::sdk_error_tool_result( + crate::tool_error::control_tool_error_contract( + error, + scope.correlation.request_id().as_str(), + scope.correlation.trace_id().as_str(), + scope.locale, + ), + ) + .into()) + } + ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) + | ToolsOutcome::InvalidParams(detail) => Err(ErrorData::invalid_params(detail, None)), + _ => Err(projection::internal()), + }; + #[cfg(test)] + super::dispatch_observer::sdk_tools_call_handler_completed(); + result + } +} +// Context seed only: close the inert transport before running domain code. No Peer callbacks. +async fn request_context( + handler: &Handler, + scope: Scope, +) -> Result, ErrorData> { + let ping = serde_json::from_value(serde_json::json!({"jsonrpc":"2.0","id":1,"method":"ping"})) + .map_err(|_| projection::internal())?; + let (transport, receiver) = rmcp::transport::OneshotTransport::::new(ping); + let info = InitializeRequestParams::new( + ClientCapabilities::default(), + Implementation::new("crank-tools-context", "1"), + ) + .with_protocol_version(ProtocolVersion::V_2025_11_25); + let mut running = rmcp::service::serve_directly(handler.clone(), transport, Some(info)); + let peer = running.peer().clone(); + running.close().await.map_err(|_| projection::internal())?; + drop(receiver); + let mut context = RequestContext::new(RequestId::Number(1), peer); + context.extensions.insert(scope); + Ok(context) +} +pub(super) async fn handle( + state: &Arc, + context: ServiceContext<'_>, + command: ToolsCommand, + lifecycle: Option, +) -> Outcome { + let (limit, confirmation) = match &command { + ToolsCommand::List(list) => (list.limit, None), + ToolsCommand::Call(call) => (None, call.confirmation_token.clone()), + }; + let scope = Scope { + workspace: context.workspace_slug.to_owned(), + agent: context.agent_slug.to_owned(), + credential: context.credential.clone(), + correlation: context.correlation.clone(), + continuation: context.continuation, + locale: context.locale, + limit, + confirmation, + lifecycle, + }; + let handler = Handler::new(state); + let context = match request_context(&handler, scope).await { + Ok(context) => context, + Err(error) => return Outcome::Error(error), + }; + #[cfg(test)] + super::dispatch_observer::sdk_tools_dispatch_enter(); + match command { + ToolsCommand::List(list) => { + let result = ServerHandler::list_tools( + &handler, + Some(PaginatedRequestParams::default().with_cursor(list.cursor)), + context, + ) + .await; + let outcome = projection::consume_list(result, handler.take_extras()); + #[cfg(test)] + super::dispatch_observer::sdk_tools_list_handler_consumed(); + outcome + } + ToolsCommand::Call(call) => { + let Value::Object(arguments) = call.arguments else { + return Outcome::Error(ErrorData::invalid_params( + "tool arguments must be an object", + None, + )); + }; + let result = ServerHandler::call_tool( + &handler, + CallToolRequestParams::new(call.tool_name).with_arguments(arguments), + context, + ) + .await; + let outcome = projection::consume_call(result); + #[cfg(test)] + super::dispatch_observer::sdk_tools_call_handler_consumed(); + outcome + } + } +} +#[cfg(test)] +#[path = "../rmcp_tools_handler_tests.rs"] +mod tests; diff --git a/crates/crank-community-mcp/src/rmcp_runtime_tests.rs b/crates/crank-community-mcp/src/rmcp_runtime_tests.rs index c190e08..3b0513a 100644 --- a/crates/crank-community-mcp/src/rmcp_runtime_tests.rs +++ b/crates/crank-community-mcp/src/rmcp_runtime_tests.rs @@ -365,6 +365,45 @@ async fn rmcp_runtime_sdk_dispatch_legacy() { ); } +async fn handler_execution_control(revision: &str) { + let h = Endpoint::started().await; + let session = h.session(revision).await; + let session = session.as_deref(); + h.list(revision, session, TOOL_NAME).await; + h.call( + revision, + session, + TOOL_NAME, + &format!("{revision}@handler.test"), + ) + .await; + assert_eq!( + h.calls.load(Ordering::SeqCst), + 1, + "one domain call expected" + ); + assert_eq!( + [ + h.counters.sdk_tools_list_handler_completed(), + h.counters.sdk_tools_list_handler_consumed(), + h.counters.sdk_tools_call_handler_completed(), + h.counters.sdk_tools_call_handler_consumed(), + ], + [1, 1, 1, 1], + "real build_app HTTP tools/list and tools/call must execute and consume SDK handler results ({revision})" + ); +} + +#[tokio::test] +async fn rmcp_tools_handler_http_modern() { + handler_execution_control(MODERN_REVISION).await; +} + +#[tokio::test] +async fn rmcp_tools_handler_http_legacy() { + handler_execution_control(LEGACY_REVISION).await; +} + #[tokio::test] async fn rmcp_runtime_observer_is_request_scoped() { let counters = Arc::new(CounterSet::default()); diff --git a/crates/crank-community-mcp/src/rmcp_tools_handler_tests.rs b/crates/crank-community-mcp/src/rmcp_tools_handler_tests.rs new file mode 100644 index 0000000..7c96fcd --- /dev/null +++ b/crates/crank-community-mcp/src/rmcp_tools_handler_tests.rs @@ -0,0 +1,325 @@ +//! 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>, + 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 { + 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, 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 { + 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); + } +} diff --git a/docs/development/rmcp-migration-plan.md b/docs/development/rmcp-migration-plan.md index a5203c3..407195f 100644 --- a/docs/development/rmcp-migration-plan.md +++ b/docs/development/rmcp-migration-plan.md @@ -61,6 +61,8 @@ Prompts handler-срез #107 на базе rc.33 заменяет прежни Completion handler-срез #107 на базе rc.34 заменяет DTO-only completion shim настоящим `ServerHandler::complete` в `app/rmcp_completion.rs`. Подключённый потребитель — обе штатные HTTP dispatch-ветки через `rmcp_dispatch::handle_completion_command`. Override напрямую await-ит прежний domain service один раз; caller потребляет возвращённый SDK `CompleteResult`/`ErrorData`, сохраняя прежнюю JSON/SSE проекцию. Исходный JSON context передаётся request-local без сужения до SDK string map. Инертный ping-bootstrap закрывается до domain execution; drop parent future отменяет незавершённый domain future, закрытый Peer не поддерживает callbacks. Отдельные HTTP handler-completed/caller-consumed oracles и trait mutation/drop/error regressions проверяют этот переход, а wire controls сохраняют refs, published/archive binding, bounded/empty/omitted totals, safe errors и revocation. Domain/auth/storage/session/transport/capabilities не меняются. Полный #107, нагрузочная квалификация, #108/4.7 и production не завершены и не запускаются. +Tools handler-срез #107 на базе rc.35 заменяет DTO-only Tools shim настоящими `ServerHandler::list_tools/call_tool` в `app/rmcp_tools_runtime.rs`. Подключённый потребитель — `build_app` → modern/legacy list dispatch и `lifecycle::call_future` → `rmcp_dispatch::handle_tools_command`. Overrides напрямую await-ят прежний shared service один раз; HTTP JSON/SSE consumers сериализуют actual SDK `ListToolsResult`/`CallToolResult`/`ErrorData`, сохраняя локально только непредставимые catalog extras. Request-local context переносит identity/locale/limit/confirmation и существующий lifecycle без повторной in-flight регистрации. Инертный ping-bootstrap закрыт до domain execution, closed Peer не используется для callbacks; progress/cancel/deadline остаются у прежнего lifecycle, drop parent отменяет domain future. HTTP handler-completed/caller-consumed oracles обеих revisions и typed mutation/error/single-call/drop controls отделены от existing wire GREEN. Affected проверки сохраняют pagination, Search/proxy binding, published catalog, access/revocation и approval semantics. Domain/auth/storage/session/transport/capabilities не меняются. Это не завершение #107, не нагрузочная/feature qualification и не разрешение #108/4.7/production. + Проверяемый результат: - Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.