//! Isolated rmcp 3.7.0 Tools adapter over Crank's existing typed Tools service. //! //! This module deliberately does not provide a second command engine. It owns only //! the verified request identity (`ServiceContext` data) and delegates both //! `tools/list` and `tools/call` to `handle_tools_command` via rmcp's //! `ServerHandler` trait. HTTP admission must supply identity for each request. use std::sync::Arc; use crank_core::{CorrelationContext, ExecutionLocale}; use crate::app::{AppState, lifecycle::ToolCallLifecycle}; use crate::auth::VerifiedMachineCredential; use crate::protocol::{ ContinuationSupport, ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_tools_command, }; /// Long-lived handler: never stores credentials obtained on initialization. #[derive(Clone)] pub(super) struct RmcpTools { pub(super) state: Arc, pub(super) active: Arc, } struct ActiveCall(Arc); impl Drop for ActiveCall { fn drop(&mut self) { self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst); } } /// Server-created identity attached to the individual admitted HTTP request. #[derive(Clone)] pub(super) struct RmcpRequestIdentity { pub(super) workspace_slug: String, pub(super) agent_slug: String, pub(super) credential: VerifiedMachineCredential, pub(super) correlation: CorrelationContext, pub(super) continuation: ContinuationSupport, pub(super) locale: ExecutionLocale, pub(super) session_id: Option, pub(super) progress_meta: Option, pub(super) sse_acceptable: bool, } impl RmcpRequestIdentity { /// Build the neutral `ServiceContext` borrowed from this adapter's owned data. pub(super) fn service_context(&self) -> ServiceContext<'_> { ServiceContext { workspace_slug: &self.workspace_slug, agent_slug: &self.agent_slug, credential: &self.credential, correlation: &self.correlation, continuation: self.continuation, locale: self.locale, } } } impl RmcpTools { /// Delegate one neutral Tools command to the existing shared service. pub(super) async fn handle( &self, identity: &RmcpRequestIdentity, command: ToolsCommand, lifecycle: Option, ) -> ToolsOutcome { handle_tools_command(&self.state, identity.service_context(), command, lifecycle).await } pub(super) async fn list_tools( &self, identity: &RmcpRequestIdentity, command: ToolsListCommand, lifecycle: Option, ) -> ToolsOutcome { self.handle(identity, ToolsCommand::List(command), lifecycle) .await } pub(super) async fn call_tool( &self, identity: &RmcpRequestIdentity, command: ToolCallCommand, lifecycle: Option, ) -> ToolsOutcome { self.handle(identity, ToolsCommand::Call(command), lifecycle) .await } } use rmcp::ErrorData as McpError; use rmcp::model::{ CallToolRequestParams, CallToolResult, ContentBlock, ListToolsResult, PaginatedRequestParams, Tool, }; use rmcp::service::RequestContext; use rmcp::{RoleServer, ServerHandler}; fn request_identity(context: &RequestContext) -> Result { context .extensions .get::() .and_then(|parts| parts.extensions.get::()) .cloned() .ok_or_else(|| McpError::internal_error("missing authenticated request context", None)) } impl ServerHandler for RmcpTools { fn supported_protocol_versions( &self, ) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> { std::borrow::Cow::Borrowed(&[ rmcp::model::ProtocolVersion::V_2025_11_25, rmcp::model::ProtocolVersion::V_2026_07_28, ]) } fn get_info(&self) -> rmcp::model::ServerConfig { let mut info = rmcp::model::ServerConfig::default(); info.capabilities = rmcp::model::ServerCapabilities::builder() .enable_tools() .build(); info } fn list_tools( &self, request: Option, context: RequestContext, ) -> impl std::future::Future> + Send + '_ { let request = request.unwrap_or_default(); async move { let identity = request_identity(&context)?; let cursor = request.cursor; let command = crate::protocol::ToolsListCommand { cursor, limit: None, }; match self.list_tools(&identity, command, None).await { crate::protocol::ToolsOutcome::List { tools, next_cursor } => { let tools = tools .into_iter() .map(serde_json::from_value::) .collect::, _>>() .map_err(|_| { McpError::internal_error("invalid tool catalog entry", None) })?; Ok(ListToolsResult { tools, next_cursor, ..Default::default() }) } crate::protocol::ToolsOutcome::InvalidParams(message) => { Err(McpError::invalid_params(message, None)) } _ => Err(McpError::internal_error("crate catalog unavailable", None)), } } } async fn call_tool( &self, request: CallToolRequestParams, context: RequestContext, ) -> Result { let identity = request_identity(&context)?; let arguments = request .arguments .map(serde_json::Value::Object) .unwrap_or_else(|| serde_json::json!({})); let command = crate::protocol::ToolCallCommand { tool_name: request.name.to_string(), arguments, confirmation_token: None, }; let token = identity .sse_acceptable .then(|| super::lifecycle::token_from_meta(identity.progress_meta.as_ref())) .flatten(); // Observe future cleanup directly in the isolated loopback oracle. self.active .fetch_add(1, std::sync::atomic::Ordering::SeqCst); let _active = ActiveCall(self.active.clone()); let (mut lifecycle, mut events) = ToolCallLifecycle::new(token.clone()); let entry = identity.session_id.as_ref().and_then(|session_id| { self.state.in_flight.register( &super::lifecycle::InFlightScope { session_id: session_id.clone(), owner: identity .credential .platform_api_key_id .as_ref() .map(|id| id.as_str()) .unwrap_or("") .to_owned(), }, &serde_json::to_value(&context.id).expect("request id serializes"), ) }); if let Some(entry) = &entry { lifecycle = lifecycle.with_cancel(entry.cancel_signal()); } let call = self.call_tool(&identity, command, Some(lifecycle.clone())); tokio::pin!(call); let outcome = loop { tokio::select! { biased; event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => { if let Some(event) = event { if let Some(token) = &token { let params = serde_json::from_value(super::lifecycle::progress_frame(token, &event)["params"].clone()).map_err(|_| McpError::internal_error("invalid progress event", None))?; let _ = context.peer.notify_progress(params).await; } } else { events = None; } } outcome = &mut call => break outcome, _ = lifecycle.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); }, _ = context.ct.cancelled() => { return Err(McpError::internal_error("request cancelled", None)); }, } }; match outcome { crate::protocol::ToolsOutcome::Call(outcome) => match outcome { crate::protocol::ToolCallOutcome::Completed(value) | crate::protocol::ToolCallOutcome::ApprovalPending(value) => { let text = value.to_string(); let mut result = CallToolResult::default(); result.content = vec![ContentBlock::text(text)]; result.structured_content = if value.is_null() { None } else { Some(value) }; Ok(result.into()) } crate::protocol::ToolCallOutcome::ApprovalUnavailable(_) => { let mut result = CallToolResult::default(); result.is_error = Some(true); result.content = vec![ContentBlock::text("approval elicitation not supported")]; Ok(result.into()) } crate::protocol::ToolCallOutcome::InvalidParams(message) => { Err(McpError::invalid_params(message, None)) } crate::protocol::ToolCallOutcome::Error(contract) => { let text = serde_json::to_string(&contract).unwrap_or_default(); let mut result = CallToolResult::default(); result.is_error = Some(true); result.content = vec![ContentBlock::text(text)]; Ok(result.into()) } crate::protocol::ToolCallOutcome::InternalFailure => { Err(McpError::internal_error("tool execution failed", None)) } }, crate::protocol::ToolsOutcome::InvalidParams(message) => { Err(McpError::invalid_params(message, None)) } _ => Err(McpError::internal_error("crate catalog unavailable", None)), } } }