#![deny(unsafe_code)]
use async_trait::async_trait;
use causa_kernel::{
ArtifactHint, ArtifactKind, ArtifactStore, CallControl, DynamicToolSource, MediaRef,
SourceError, ToolCallContext, ToolDefinition, ToolExecutionError, ToolOutput,
ToolResultPayload, ToolResultStatus,
};
use rmcp::handler::client::ClientHandler;
use rmcp::model::ContentBlock;
use rmcp::service::{NotificationContext, RoleClient, RunningService, ServiceExt};
use rmcp::transport::StreamableHttpClientTransport;
use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
use std::borrow::Cow;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug, Default)]
struct McpClientHandler {
list_version: Arc<AtomicU64>,
}
impl ClientHandler for McpClientHandler {
async fn on_tool_list_changed(&self, _context: NotificationContext<RoleClient>) {
self.list_version.fetch_add(1, Ordering::SeqCst);
}
}
pub struct McpToolSource {
server_id: String,
namespace: String,
service: RunningService<RoleClient, McpClientHandler>,
list_version: Arc<AtomicU64>,
}
impl std::fmt::Debug for McpToolSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpToolSource")
.field("server_id", &self.server_id)
.field("list_version", &self.list_version.load(Ordering::SeqCst))
.finish()
}
}
impl McpToolSource {
fn build(
server_id: String,
service: RunningService<RoleClient, McpClientHandler>,
list_version: Arc<AtomicU64>,
) -> Self {
debug_assert!(
!server_id.is_empty()
&& server_id
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'),
"server_id must be non-empty [A-Za-z0-9_-], got: {server_id}"
);
Self {
namespace: format!("mcp_{}_", server_id),
server_id,
service,
list_version,
}
}
pub async fn connect_stdio(
server_id: impl Into<String>,
command: tokio::process::Command,
) -> Result<Self, SourceError> {
let server_id = server_id.into();
let list_version = Arc::new(AtomicU64::new(0));
let transport = rmcp::transport::TokioChildProcess::new(command)
.map_err(|e| SourceError::Unavailable(e.to_string()))?;
let handler = McpClientHandler {
list_version: list_version.clone(),
};
let service = handler
.serve(transport)
.await
.map_err(|e| SourceError::Unavailable(e.to_string()))?;
Ok(Self::build(server_id, service, list_version))
}
pub async fn connect_http(
server_id: impl Into<String>,
uri: impl Into<String>,
auth_token: Option<String>,
) -> Result<Self, SourceError> {
let server_id = server_id.into();
let list_version = Arc::new(AtomicU64::new(0));
let mut config = StreamableHttpClientTransportConfig::with_uri(uri.into());
if let Some(token) = auth_token {
config = config.auth_header(token);
}
let transport = StreamableHttpClientTransport::from_config(config);
let handler = McpClientHandler {
list_version: list_version.clone(),
};
let service = handler
.serve(transport)
.await
.map_err(|e| SourceError::Unavailable(e.to_string()))?;
Ok(Self::build(server_id, service, list_version))
}
pub async fn connect_io<I>(server_id: impl Into<String>, io: I) -> Result<Self, SourceError>
where
I: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
{
let server_id = server_id.into();
let list_version = Arc::new(AtomicU64::new(0));
let handler = McpClientHandler {
list_version: list_version.clone(),
};
let service = handler
.serve(io)
.await
.map_err(|e| SourceError::Unavailable(e.to_string()))?;
Ok(Self::build(server_id, service, list_version))
}
pub async fn close(self) -> Result<(), SourceError> {
let server_id = self.server_id.clone();
let service = self.service;
match tokio::time::timeout(std::time::Duration::from_secs(2), service.cancel()).await {
Ok(Ok(_)) => Ok(()),
Ok(Err(e)) => Err(SourceError::Unavailable(e.to_string())),
Err(_) => {
tracing::warn!(server_id = %server_id, "MCP close timed out; dropping service without session cleanup");
Ok(())
}
}
}
pub fn namespaced(&self, tool: &str) -> String {
format!("{}{}", self.namespace, tool)
}
fn denamespace<'a>(&self, tool_name: &'a str) -> Option<&'a str> {
tool_name.strip_prefix(&self.namespace)
}
fn map_service_error(e: rmcp::ServiceError) -> SourceError {
match e {
rmcp::ServiceError::Timeout { .. }
| rmcp::ServiceError::TransportSend(_)
| rmcp::ServiceError::TransportClosed => SourceError::Unavailable(e.to_string()),
_ => SourceError::Protocol(e.to_string()),
}
}
fn map_invoke_error(e: rmcp::ServiceError) -> ToolExecutionError {
match e {
rmcp::ServiceError::Timeout { .. } => ToolExecutionError::TimedOut,
rmcp::ServiceError::Cancelled { .. } => ToolExecutionError::Cancelled,
rmcp::ServiceError::TransportSend(_) | rmcp::ServiceError::TransportClosed => {
ToolExecutionError::Unavailable(e.to_string())
}
_ => ToolExecutionError::Protocol(e.to_string()),
}
}
}
#[async_trait]
impl DynamicToolSource for McpToolSource {
fn id(&self) -> &str {
&self.server_id
}
fn version(&self) -> u64 {
self.list_version.load(Ordering::SeqCst)
}
async fn list(&self) -> Result<Vec<ToolDefinition>, SourceError> {
let listed = self
.service
.list_tools(None)
.await
.map_err(Self::map_service_error)?;
Ok(listed
.tools
.into_iter()
.map(|tool| ToolDefinition {
name: self.namespaced(tool.name.as_ref()),
description: tool.description.map(|d| d.to_string()).unwrap_or_default(),
parameters: serde_json::Value::Object((*tool.input_schema).clone()),
})
.collect())
}
async fn invoke(
&self,
call: &ToolCallContext,
control: &CallControl,
) -> Result<ToolResultPayload, ToolExecutionError> {
Self::invoke_inner(self, call, control, None).await
}
async fn invoke_with_store(
&self,
call: &ToolCallContext,
control: &CallControl,
store: Option<&dyn ArtifactStore>,
) -> Result<ToolResultPayload, ToolExecutionError> {
Self::invoke_inner(self, call, control, store).await
}
}
impl McpToolSource {
async fn invoke_inner(
&self,
call: &ToolCallContext,
control: &CallControl,
store: Option<&dyn ArtifactStore>,
) -> Result<ToolResultPayload, ToolExecutionError> {
let Some(tool_name) = self.denamespace(&call.input.tool_name) else {
return Err(ToolExecutionError::UnknownTool(
call.input.tool_name.clone(),
));
};
let arguments = match &call.input.arguments {
serde_json::Value::Object(map) => Some(map.clone()),
serde_json::Value::Null => None,
other => {
return Err(ToolExecutionError::Protocol(format!(
"MCP tool arguments must be an object, got: {other}"
)));
}
};
let mut params = rmcp::model::CallToolRequestParams::new(Cow::Owned(tool_name.to_string()));
if let Some(args) = arguments {
params = params.with_arguments(args);
}
let deadline = control.deadline();
let token = control.cancellation_token().clone();
let result = tokio::select! {
biased;
_ = token.cancelled() => return Err(ToolExecutionError::Cancelled),
r = async {
match deadline {
Some(deadline) => {
tokio::time::timeout_at(deadline.into(), self.service.call_tool(params))
.await
.map_err(|_| ToolExecutionError::TimedOut)?
.map_err(Self::map_invoke_error)
}
None => self
.service
.call_tool(params)
.await
.map_err(Self::map_invoke_error),
}
} => r?,
};
let mut parts: Vec<String> = Vec::new();
let mut media: Vec<MediaRef> = Vec::new();
for block in result.content {
match block {
ContentBlock::Text(t) => parts.push(t.text),
ContentBlock::Image(image) => match Self::ingest_image(&image, store, call).await {
Some(reference) => {
parts.push(format!(
"[image attached: {} — asset {}]",
image.mime_type, reference.reference
));
media.push(reference);
}
None => parts.push(format!(
"[image: {} mime — no media store available]",
image.mime_type
)),
},
ContentBlock::Audio(audio) => {
parts.push(format!("[audio: {} mime]", audio.mime_type))
}
ContentBlock::Resource(embedded) => match &embedded.resource {
rmcp::model::ResourceContents::TextResourceContents {
uri,
text: inner,
..
} => parts.push(format!("[resource {uri}]\n{inner}")),
other => parts.push(format!("[resource: {other:?}]")),
},
ContentBlock::ResourceLink(link) => parts.push(format!("[link: {}]", link.uri)),
other => parts.push(format!("[unhandled content: {other:?}]")),
}
}
let text = parts.join("\n");
let content = match result.structured_content {
Some(value) => value,
None => serde_json::Value::String(text),
};
let status = if result.is_error.unwrap_or(false) {
ToolResultStatus::Failed
} else {
ToolResultStatus::Succeeded
};
Ok(ToolResultPayload {
call_block_id: call.call_block_id,
status,
output: ToolOutput::new(content),
media,
notes: Vec::new(),
})
}
async fn ingest_image(
image: &rmcp::model::ImageContent,
store: Option<&dyn ArtifactStore>,
call: &ToolCallContext,
) -> Option<MediaRef> {
use base64::Engine as _;
let store = store?;
let bytes = base64::engine::general_purpose::STANDARD
.decode(&image.data)
.ok()?;
let hint = ArtifactHint {
tool_name: call.input.tool_name.clone(),
call_block_id: call.call_block_id,
kind: ArtifactKind::Binary,
};
let artifact = store.persist(&bytes, hint).await.ok()?;
Some(MediaRef::new(image.mime_type.clone(), artifact.id))
}
}