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
242 lines
9.5 KiB
Rust
242 lines
9.5 KiB
Rust
//! 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<AppState>,
|
|
pub(super) active: Arc<std::sync::atomic::AtomicUsize>,
|
|
}
|
|
|
|
struct ActiveCall(Arc<std::sync::atomic::AtomicUsize>);
|
|
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<String>,
|
|
pub(super) progress_meta: Option<serde_json::Value>,
|
|
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<ToolCallLifecycle>,
|
|
) -> 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<ToolCallLifecycle>,
|
|
) -> ToolsOutcome {
|
|
self.handle(identity, ToolsCommand::List(command), lifecycle)
|
|
.await
|
|
}
|
|
|
|
pub(super) async fn call_tool(
|
|
&self,
|
|
identity: &RmcpRequestIdentity,
|
|
command: ToolCallCommand,
|
|
lifecycle: Option<ToolCallLifecycle>,
|
|
) -> ToolsOutcome {
|
|
self.handle(identity, ToolsCommand::Call(command), lifecycle)
|
|
.await
|
|
}
|
|
}
|
|
use rmcp::ErrorData as McpError;
|
|
use rmcp::model::{CallToolRequestParams, ListToolsResult, PaginatedRequestParams};
|
|
use rmcp::service::RequestContext;
|
|
use rmcp::{RoleServer, ServerHandler};
|
|
|
|
fn request_identity(context: &RequestContext<RoleServer>) -> Result<RmcpRequestIdentity, McpError> {
|
|
context
|
|
.extensions
|
|
.get::<axum::http::request::Parts>()
|
|
.and_then(|parts| parts.extensions.get::<RmcpRequestIdentity>())
|
|
.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<PaginatedRequestParams>,
|
|
context: RequestContext<RoleServer>,
|
|
) -> impl std::future::Future<Output = Result<ListToolsResult, McpError>> + 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 } => {
|
|
super::response::sdk_tools_list_result(&tools, next_cursor)
|
|
.map_err(|_| McpError::internal_error("invalid tool catalog entry", None))
|
|
}
|
|
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<RoleServer>,
|
|
) -> Result<rmcp::model::CallToolResponse, McpError> {
|
|
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 _ = context.peer.notify_progress(event.sdk_params(token)).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) => {
|
|
Ok(super::response::sdk_success_tool_result(value).into())
|
|
}
|
|
crate::protocol::ToolCallOutcome::ApprovalUnavailable(error) => {
|
|
Ok(super::response::sdk_error_tool_result(
|
|
crate::tool_error::control_tool_error_contract(
|
|
error,
|
|
identity.correlation.request_id().as_str(),
|
|
identity.correlation.trace_id().as_str(),
|
|
identity.locale,
|
|
),
|
|
)
|
|
.into())
|
|
}
|
|
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
|
|
Err(McpError::invalid_params(message, None))
|
|
}
|
|
crate::protocol::ToolCallOutcome::Error(contract) => {
|
|
Ok(super::response::sdk_error_tool_result(contract).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)),
|
|
}
|
|
}
|
|
}
|