//! 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;