use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use futures::StreamExt;
use futures::future::BoxFuture;
use rig_agent::Agent;
use rig_agent::agent::MultiTurnStreamItem;
use rig_agent::completion::{PromptError, StructuredOutputError};
use rig_core::message::Message;
use rig_core::serve::adapters::ToolAdapter;
use rig_core::streaming::{Item, StreamEvent};
use rig_core::tool::{DynamicTool, Tool, ToolExecutionError, ToolOutput, tool_definition};
use rig_memory::AsyncStore;
use rig_memory::recent::{Recent, TokenBudget, view};
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, CompleteRequestMethod,
CompleteRequestParams, CompleteResult, CompletionInfo, ContentBlock, GetPromptRequestParams,
GetPromptResponse, GetPromptResult, Icon, Implementation, InitializeResult, JsonObject,
ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult,
PaginatedRequestParams, ProgressNotificationParam, Prompt, PromptArgument, PromptMessage,
PromptsCapability, ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult,
Reference, Resource, ResourceContents, ResourceTemplate, ResourcesCapability,
ServerCapabilities, ServerConfig, ToolAnnotations,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData as McpError, RoleServer, ServerHandler};
use serde::Deserialize;
use serde_json::{Value, json};
use crate::catalog::{Piece, Render, StaticPrompt, StaticResource, StaticTemplate, TemplateVars};
use crate::completion::{BoxError, Completer, CompletionRequest, CompletionTarget};
use crate::content::{image_blocks, tool_result};
use crate::history::{
DEFAULT_HISTORY_TOKENS, DEFAULT_MAX_CONTEXTS, HistoryStore, InMemory, Persistent,
valid_context_id,
};
use crate::transport::DEFAULT_MAX_REQUEST_BYTES;
pub const DEFAULT_MAX_CONCURRENT_CALLS: usize = 32;
pub const DEFAULT_MAX_RUN_DURATION: Duration = Duration::from_secs(600);
const MAX_TOOL_NAME: usize = 64;
type RunTool =
Arc<dyn Fn(Value) -> BoxFuture<'static, Result<ToolOutput, ToolExecutionError>> + Send + Sync>;
type TypedAnswer = Arc<
dyn Fn(
Agent,
Message,
Vec<Message>,
) -> BoxFuture<'static, Result<(Value, Vec<Message>), String>>
+ Send
+ Sync,
>;
pub struct McpServer {
name: String,
version: String,
instructions: Option<String>,
title: Option<String>,
icons: Vec<Icon>,
tools: Vec<Entry>,
resources: Vec<StaticResource>,
resource_templates: Vec<StaticTemplate>,
prompts: Vec<StaticPrompt>,
history: Arc<dyn HistoryStore>,
window: Arc<dyn Recent>,
slots: Arc<tokio::sync::Semaphore>,
max_run: Duration,
pub(crate) bearer: Option<String>,
pub(crate) allowed_hosts: Option<Vec<String>>,
pub(crate) max_request_bytes: usize,
pub(crate) ping: bool,
completer: Option<Completer>,
}
struct Entry {
tool: rmcp::model::Tool,
kind: Kind,
}
enum Kind {
Tool(RunTool),
Agent(Box<Agent>, Option<TypedAnswer>),
}
impl McpServer {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
version: env!("CARGO_PKG_VERSION").to_owned(),
instructions: None,
title: None,
icons: Vec::new(),
tools: Vec::new(),
resources: Vec::new(),
resource_templates: Vec::new(),
prompts: Vec::new(),
history: Arc::new(InMemory::new(DEFAULT_MAX_CONTEXTS)),
window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
slots: Arc::new(tokio::sync::Semaphore::new(DEFAULT_MAX_CONCURRENT_CALLS)),
max_run: DEFAULT_MAX_RUN_DURATION,
bearer: None,
allowed_hosts: None,
max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
ping: false,
completer: None,
}
}
#[must_use]
pub fn ping_route(mut self) -> Self {
self.ping = true;
self
}
#[must_use]
pub fn version(mut self, version: impl Into<String>) -> Self {
self.version = version.into();
self
}
#[must_use]
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn icon(mut self, icon: Icon) -> Self {
self.icons.push(icon);
self
}
#[must_use]
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
self.instructions = Some(instructions.into());
self
}
#[must_use]
pub fn agent(self, agent: Agent) -> Self {
let (name, description) = agent_identity(&agent);
let output = json!({
"type": "object",
"properties": {
"answer": {"type": "string"},
"session_id": {"type": "string"}
},
"required": ["answer", "session_id"]
});
let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
.with_raw_output_schema(Arc::new(object(output)));
self.add(Entry {
tool,
kind: Kind::Agent(Box::new(agent), None),
})
}
#[must_use]
pub fn typed_agent<T>(self, agent: Agent) -> Self
where
T: schemars::JsonSchema
+ serde::de::DeserializeOwned
+ serde::Serialize
+ Send
+ Sync
+ 'static,
{
let (name, description) = agent_identity(&agent);
let schema = serde_json::to_value(schemars::schema_for!(T)).unwrap_or_default();
let tool = rmcp::model::Tool::new(name, description, Arc::new(agent_input()))
.with_raw_output_schema(Arc::new(object(schema)));
let typed: TypedAnswer = Arc::new(|agent, prompt, history| {
Box::pin(async move {
let response = agent
.prompt_typed::<T>(prompt)
.history(history)
.retries(2)
.await
.map_err(|error| {
let reason = match &error {
StructuredOutputError::Prompt(prompt) => status_message(prompt),
_ => "not a structured answer",
};
tracing::warn!(
kind = "run_failed",
reason = reason,
"typed agent call failed"
);
match &error {
StructuredOutputError::Prompt(prompt) => {
failure_message(prompt).into_owned()
}
_ => "The agent could not produce a structured answer.".to_owned(),
}
})?;
let value =
serde_json::to_value(&response.output).map_err(|error| error.to_string())?;
Ok((value, response.messages))
})
});
self.add(Entry {
tool,
kind: Kind::Agent(Box::new(agent), Some(typed)),
})
}
#[must_use]
pub fn tool<T: Tool + 'static>(self, tool: T) -> Self {
self.tool_presented(tool, Presentation::default())
}
#[must_use]
pub fn tool_presented<T: Tool + 'static>(self, tool: T, presentation: Presentation) -> Self {
let definition = tool_definition(&tool);
let adapter = Arc::new(ToolAdapter::new(tool));
let run: RunTool = Arc::new(move |args| {
let adapter = Arc::clone(&adapter);
Box::pin(async move { adapter.run(args).await })
});
self.add_tool(definition, run, &presentation)
}
#[must_use]
pub fn dynamic_tool(self, tool: DynamicTool) -> Self {
self.dynamic_tool_presented(tool, Presentation::default())
}
#[must_use]
pub fn dynamic_tool_presented(self, tool: DynamicTool, presentation: Presentation) -> Self {
let definition = tool.definition();
let tool = Arc::new(tool);
let run: RunTool = Arc::new(move |args| {
let tool = Arc::clone(&tool);
Box::pin(async move { tool.run(args).await })
});
self.add_tool(definition, run, &presentation)
}
#[must_use]
pub fn max_sessions(mut self, max: usize) -> Self {
self.history = Arc::new(InMemory::new(max));
self
}
#[must_use]
pub fn history_store<S>(mut self, store: S) -> Self
where
S: AsyncStore + Send + Sync + 'static,
{
self.history = Arc::new(Persistent(store));
self
}
#[must_use]
pub fn history_window(mut self, window: impl Recent + 'static) -> Self {
self.window = Arc::new(window);
self
}
#[must_use]
#[doc(alias = "max_concurrent_tasks")]
pub fn max_concurrent_calls(mut self, max: usize) -> Self {
self.slots = Arc::new(tokio::sync::Semaphore::new(max.max(1)));
self
}
#[must_use]
pub fn max_run_duration(mut self, max: Duration) -> Self {
self.max_run = max;
self
}
#[must_use]
pub fn resource(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
text: impl Into<String>,
) -> Self {
self.resource_presented(uri, name, mime_type, text, Presentation::default())
}
#[must_use]
pub fn binary_resource(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
bytes: impl AsRef<[u8]>,
) -> Self {
use base64::Engine;
let uri = uri.into();
let mime_type = mime_type.into();
let resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
let contents = ResourceContents::BlobResourceContents {
uri,
mime_type: Some(mime_type),
blob: base64::engine::general_purpose::STANDARD.encode(bytes.as_ref()),
meta: None,
};
self.add_resource(StaticResource { resource, contents })
}
#[must_use]
pub fn prompt<F>(
self,
name: impl Into<String>,
description: impl Into<String>,
arguments: Vec<PromptArgument>,
render: F,
) -> Self
where
F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
{
self.prompt_presented(
name,
description,
arguments,
render,
Presentation::default(),
)
}
#[must_use]
pub fn resource_presented(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
text: impl Into<String>,
presentation: Presentation,
) -> Self {
let uri = uri.into();
let mime_type = mime_type.into();
let mut resource = Resource::new(uri.clone(), name).with_mime_type(mime_type.clone());
presentation.apply_resource(&mut resource);
let contents = ResourceContents::TextResourceContents {
uri,
mime_type: Some(mime_type),
text: text.into(),
meta: None,
};
self.add_resource(StaticResource { resource, contents })
}
fn add_resource(mut self, resource: StaticResource) -> Self {
self.resources.push(resource);
self
}
#[must_use]
pub fn resource_template<F, Fut, E>(
self,
uri_template: impl Into<String>,
name: impl Into<String>,
description: impl Into<String>,
mime_type: impl Into<String>,
read: F,
) -> Self
where
F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<String, E>> + Send + 'static,
E: std::error::Error + Send + Sync + 'static,
{
self.resource_template_presented(
uri_template,
name,
description,
mime_type,
Presentation::default(),
read,
)
}
#[must_use]
pub fn resource_template_presented<F, Fut, E>(
mut self,
uri_template: impl Into<String>,
name: impl Into<String>,
description: impl Into<String>,
mime_type: impl Into<String>,
presentation: Presentation,
read: F,
) -> Self
where
F: Fn(TemplateVars) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<String, E>> + Send + 'static,
E: std::error::Error + Send + Sync + 'static,
{
let mut template = ResourceTemplate::new(uri_template, name)
.with_description(description)
.with_mime_type(mime_type);
presentation.apply_template(&mut template);
let read = Arc::new(
move |vars: TemplateVars| -> BoxFuture<'static, Result<String, BoxError>> {
let answer = read(vars);
Box::pin(async move {
answer
.await
.map_err(|error| -> BoxError { Box::new(error) })
})
},
);
self.resource_templates
.push(StaticTemplate { template, read });
self
}
#[must_use]
pub fn prompt_presented<F>(
self,
name: impl Into<String>,
description: impl Into<String>,
arguments: Vec<PromptArgument>,
render: F,
presentation: Presentation,
) -> Self
where
F: Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Send + Sync + 'static,
{
let mut prompt = Prompt::new(name, Some(description), Some(arguments));
presentation.apply_prompt(&mut prompt);
let render: Render = Arc::new(render);
self.add_prompt(StaticPrompt { prompt, render })
}
fn add_prompt(mut self, prompt: StaticPrompt) -> Self {
self.prompts.push(prompt);
self
}
#[must_use]
pub fn completer<F, Fut, E>(mut self, complete: F) -> Self
where
F: Fn(CompletionRequest) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Vec<String>, E>> + Send + 'static,
E: std::error::Error + Send + Sync + 'static,
{
self.completer =
Some(
Arc::new(
move |request: CompletionRequest| -> BoxFuture<
'static,
Result<Vec<String>, crate::completion::BoxError>,
> {
let answer = complete(request);
Box::pin(async move {
answer
.await
.map_err(|error| -> crate::completion::BoxError { Box::new(error) })
})
},
),
);
self
}
fn add_tool(
self,
definition: rig_core::completion::ToolDefinition,
run: RunTool,
presentation: &Presentation,
) -> Self {
let mut tool = rmcp::model::Tool::new(
definition.name.to_string(),
definition.description,
Arc::new(object(definition.parameters)),
);
if let Some(annotations) = serde_json::to_value(&definition.annotations)
.ok()
.filter(|value| value.as_object().is_some_and(|fields| !fields.is_empty()))
.and_then(|value| serde_json::from_value::<ToolAnnotations>(value).ok())
{
tool = tool.with_annotations(annotations);
}
presentation.apply_tool(&mut tool);
self.add(Entry {
tool,
kind: Kind::Tool(run),
})
}
fn add(mut self, entry: Entry) -> Self {
self.tools.push(entry);
self
}
}
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct Presentation {
title: Option<String>,
icons: Vec<Icon>,
}
impl Presentation {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn icon(mut self, icon: Icon) -> Self {
self.icons.push(icon);
self
}
fn icon_list(&self) -> Option<Vec<Icon>> {
(!self.icons.is_empty()).then(|| self.icons.clone())
}
fn apply_tool(&self, tool: &mut rmcp::model::Tool) {
tool.title.clone_from(&self.title);
tool.icons = self.icon_list();
}
fn apply_resource(&self, resource: &mut Resource) {
resource.title.clone_from(&self.title);
resource.icons = self.icon_list();
}
fn apply_template(&self, template: &mut ResourceTemplate) {
template.title.clone_from(&self.title);
template.icons = self.icon_list();
}
fn apply_prompt(&self, prompt: &mut Prompt) {
prompt.title.clone_from(&self.title);
prompt.icons = self.icon_list();
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum BuildError {
#[error("two tools are named `{0}`")]
DuplicateTool(String),
#[error("two resources have the URI `{0}`")]
DuplicateResource(String),
#[error("two prompts are named `{0}`")]
DuplicatePrompt(String),
#[error("icon source `{0}` is not an http(s) URL or a data: URI")]
InvalidIcon(String),
#[error(
"resource template `{0}` is malformed: use `{{name}}` once per name, with letters, digits or `_`"
)]
InvalidResourceTemplate(String),
#[error("two resource templates have the URI template `{0}`")]
DuplicateResourceTemplate(String),
}
#[derive(Clone)]
pub(crate) struct Handler(Arc<Inner>);
struct Inner {
server: McpServer,
by_name: HashMap<String, usize>,
templates: Vec<Vec<Piece>>,
}
impl Handler {
pub(crate) fn new(server: McpServer) -> Result<Self, BuildError> {
let mut by_name = HashMap::with_capacity(server.tools.len());
for (index, entry) in server.tools.iter().enumerate() {
let name = entry.tool.name.to_string();
if by_name.contains_key(&name) {
return Err(BuildError::DuplicateTool(name));
}
by_name.insert(name, index);
}
let mut uris = HashSet::with_capacity(server.resources.len());
for resource in &server.resources {
let uri = &resource.resource.uri;
if !uris.insert(uri.clone()) {
return Err(BuildError::DuplicateResource(uri.clone()));
}
}
let mut names = HashSet::with_capacity(server.prompts.len());
for prompt in &server.prompts {
let name = &prompt.prompt.name;
if !names.insert(name.clone()) {
return Err(BuildError::DuplicatePrompt(name.clone()));
}
}
let mut templates = Vec::with_capacity(server.resource_templates.len());
let mut texts = HashSet::with_capacity(server.resource_templates.len());
for template in &server.resource_templates {
let text = &template.template.uri_template;
let pieces = crate::catalog::parse(text)
.ok_or_else(|| BuildError::InvalidResourceTemplate(text.clone()))?;
if !texts.insert(text.clone()) {
return Err(BuildError::DuplicateResourceTemplate(text.clone()));
}
templates.push(pieces);
}
check_icons(server.icons.iter())?;
for entry in &server.tools {
check_icons(entry.tool.icons.iter().flatten())?;
}
for resource in &server.resources {
check_icons(resource.resource.icons.iter().flatten())?;
}
for template in &server.resource_templates {
check_icons(template.template.icons.iter().flatten())?;
}
for prompt in &server.prompts {
check_icons(prompt.prompt.icons.iter().flatten())?;
}
Ok(Self(Arc::new(Inner {
server,
by_name,
templates,
})))
}
fn entry(&self, name: &str) -> Option<&Entry> {
let index = *self.0.by_name.get(name)?;
self.0.server.tools.get(index)
}
}
fn check_icons<'a>(icons: impl IntoIterator<Item = &'a Icon>) -> Result<(), BuildError> {
for icon in icons {
let src = icon.src.to_ascii_lowercase();
if !(src.starts_with("https://") || src.starts_with("http://") || src.starts_with("data:"))
{
return Err(BuildError::InvalidIcon(icon.src.clone()));
}
}
Ok(())
}
impl ServerHandler for Handler {
fn get_info(&self) -> ServerConfig {
let server = &self.0.server;
let mut capabilities = ServerCapabilities::builder().enable_tools().build();
if !server.resources.is_empty() || !server.resource_templates.is_empty() {
capabilities.resources = Some(ResourcesCapability::default());
}
if !server.prompts.is_empty() {
capabilities.prompts = Some(PromptsCapability::default());
}
if server.completer.is_some() {
capabilities.completions = Some(JsonObject::default());
}
let mut implementation = Implementation::new(server.name.clone(), server.version.clone());
implementation.title.clone_from(&server.title);
implementation.icons = (!server.icons.is_empty()).then(|| server.icons.clone());
let mut info = InitializeResult::new(capabilities).with_server_info(implementation);
if let Some(instructions) = &server.instructions {
info = info.with_instructions(instructions.clone());
}
info
}
async fn list_resources(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListResourcesResult, McpError> {
Ok(ListResourcesResult {
resources: self
.0
.server
.resources
.iter()
.map(|entry| entry.resource.clone())
.collect(),
..Default::default()
})
}
async fn list_resource_templates(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListResourceTemplatesResult, McpError> {
Ok(ListResourceTemplatesResult {
resource_templates: self
.0
.server
.resource_templates
.iter()
.map(|entry| entry.template.clone())
.collect(),
..Default::default()
})
}
async fn read_resource(
&self,
request: ReadResourceRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<ReadResourceResponse, McpError> {
if let Some(entry) = self
.0
.server
.resources
.iter()
.find(|entry| entry.resource.uri == request.uri)
{
return Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
vec![entry.contents.clone()],
)));
}
for (template, pieces) in self
.0
.server
.resource_templates
.iter()
.zip(&self.0.templates)
{
let Some(vars) = crate::catalog::matches(pieces, &request.uri) else {
continue;
};
let text = (template.read)(vars).await.map_err(|_| {
tracing::warn!(kind = "resource_template", "resource template read failed");
McpError::internal_error("resource read failed", None)
})?;
let contents = ResourceContents::TextResourceContents {
uri: request.uri,
mime_type: template.template.mime_type.clone(),
text,
meta: None,
};
return Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
vec![contents],
)));
}
Err(McpError::resource_not_found(
format!("no resource at `{}`", request.uri),
None,
))
}
async fn list_prompts(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListPromptsResult, McpError> {
Ok(ListPromptsResult {
prompts: self
.0
.server
.prompts
.iter()
.map(|entry| entry.prompt.clone())
.collect(),
..Default::default()
})
}
async fn get_prompt(
&self,
request: GetPromptRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<GetPromptResponse, McpError> {
let entry = self
.0
.server
.prompts
.iter()
.find(|entry| entry.prompt.name == request.name)
.ok_or_else(|| {
McpError::invalid_params(format!("no prompt named `{}`", request.name), None)
})?;
let mut arguments = HashMap::new();
for (name, value) in request.arguments.unwrap_or_default() {
let Value::String(text) = value else {
return Err(McpError::invalid_params(
format!("argument `{name}` must be a string"),
None,
));
};
arguments.insert(name, text);
}
for declared in entry.prompt.arguments.iter().flatten() {
if declared.required == Some(true) && !arguments.contains_key(&declared.name) {
return Err(McpError::invalid_params(
format!("missing required argument `{}`", declared.name),
None,
));
}
}
let messages = (entry.render)(&arguments);
let mut result = GetPromptResult::new(messages);
if let Some(description) = &entry.prompt.description {
result = result.with_description(description.clone());
}
Ok(GetPromptResponse::Complete(result))
}
async fn complete(
&self,
request: CompleteRequestParams,
_context: RequestContext<RoleServer>,
) -> Result<CompleteResult, McpError> {
let server = &self.0.server;
let Some(completer) = &server.completer else {
return Err(McpError::method_not_found::<CompleteRequestMethod>());
};
let target = match request.r#ref {
Reference::Prompt(prompt) => CompletionTarget::Prompt(prompt.name),
Reference::Resource(resource) => CompletionTarget::Resource(resource.uri),
_ => return Err(McpError::invalid_params("unsupported reference", None)),
};
match &target {
CompletionTarget::Prompt(name) => {
let entry = server
.prompts
.iter()
.find(|entry| entry.prompt.name == *name)
.ok_or_else(|| {
McpError::invalid_params(format!("no prompt named `{name}`"), None)
})?;
let declared = entry
.prompt
.arguments
.iter()
.flatten()
.any(|argument| argument.name == request.argument.name);
if !declared {
return Err(McpError::invalid_params(
format!(
"prompt `{name}` has no argument `{}`",
request.argument.name
),
None,
));
}
}
CompletionTarget::Resource(uri) => {
let served = server
.resources
.iter()
.any(|entry| entry.resource.uri == *uri);
if !served {
let index = server
.resource_templates
.iter()
.position(|entry| entry.template.uri_template == *uri);
let declared = index
.and_then(|index| self.0.templates.get(index))
.is_some_and(|pieces| {
pieces.iter().any(|piece| {
matches!(piece, Piece::Var(name) if *name == request.argument.name)
})
});
if !declared {
return Err(McpError::invalid_params(
format!("no resource at `{uri}`"),
None,
));
}
}
}
}
let context = request
.context
.and_then(|context| context.arguments)
.unwrap_or_default();
let input = CompletionRequest::new(
target,
request.argument.name,
request.argument.value,
context,
);
let values = completer(input).await.map_err(|_| {
tracing::warn!(kind = "completion", "completer failed");
McpError::internal_error("completion failed", None)
})?;
let found = values.len();
let truncated = found > CompletionInfo::MAX_VALUES;
let values: Vec<String> = values
.into_iter()
.take(CompletionInfo::MAX_VALUES)
.collect();
let total = u32::try_from(found).unwrap_or(u32::MAX);
let info = CompletionInfo::with_pagination(values, Some(total), truncated)
.map_err(|_| McpError::internal_error("completion failed", None))?;
Ok(CompleteResult::new(info))
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, McpError> {
Ok(ListToolsResult {
tools: self
.0
.server
.tools
.iter()
.map(|entry| entry.tool.clone())
.collect(),
..Default::default()
})
}
fn get_tool(&self, name: &str) -> Option<rmcp::model::Tool> {
self.entry(name).map(|entry| entry.tool.clone())
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, McpError> {
let entry = self.entry(&request.name).ok_or_else(|| {
McpError::invalid_params(format!("no tool named `{}`", request.name), None)
})?;
let args = Value::Object(request.arguments.unwrap_or_default());
let Ok(_slot) = Arc::clone(&self.0.server.slots).try_acquire_owned() else {
return Ok(CallToolResponse::Complete(error(
"The server is busy; try again shortly.",
)));
};
let result = match &entry.kind {
Kind::Tool(run) => {
let run = run(args);
#[cfg(feature = "otel")]
let run = {
let span = tracing::info_span!("mcp.tool_call", mcp.tool = %request.name);
crate::otel::Incoming::of(&context).continue_in(&span, None);
tracing::Instrument::instrument(run, span)
};
match run.await {
Ok(output) => tool_result(output),
Err(failure) => error(&failure.to_string()),
}
}
Kind::Agent(agent, typed) => {
self.call_agent(agent, typed.as_ref(), args, &context)
.await?
}
};
Ok(CallToolResponse::Complete(result))
}
}
#[derive(Deserialize)]
struct AgentArgs {
message: String,
session_id: Option<String>,
}
impl Handler {
async fn call_agent(
&self,
agent: &Agent,
typed: Option<&TypedAnswer>,
args: Value,
context: &RequestContext<RoleServer>,
) -> Result<CallToolResult, McpError> {
let server = &self.0.server;
let AgentArgs {
message,
session_id,
} = AgentArgs::deserialize(args)
.map_err(|e| McpError::invalid_params(format!("invalid arguments: {e}"), None))?;
let session = session_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
if !valid_context_id(&session) {
return Err(McpError::invalid_params(
"session_id must be 1 to 128 ASCII letters, digits, `-` or `_`",
None,
));
}
let span = tracing::info_span!("mcp.agent_call", mcp.session_id = %session);
#[cfg(feature = "otel")]
crate::otel::Incoming::of(context).continue_in(&span, Some(&session));
let prior = match server.history.load(&session).await {
Ok(messages) => view(&messages, server.window.as_ref())
.iter()
.map(|message| (**message).clone())
.collect::<Vec<_>>(),
Err(_) => {
tracing::warn!(parent: &span, kind = "store_error", "could not load the session");
return Ok(error("The session could not be loaded."));
}
};
let deadline = tokio::time::Instant::now() + server.max_run;
let prompt = Message::user(message);
if let Some(typed) = typed {
let run =
tracing::Instrument::instrument(typed(agent.clone(), prompt, prior), span.clone());
let outcome = tokio::select! {
_ = context.ct.cancelled() => return Ok(error("Cancelled.")),
outcome = tokio::time::timeout_at(deadline, run) => outcome,
};
return Ok(match outcome {
Err(_) => error("The agent run took longer than allowed."),
Ok(Err(message)) => error(&message),
Ok(Ok((value, messages))) => {
self.save(&session, messages, &span).await;
let mut result = CallToolResult::success(vec![
ContentBlock::text(value.to_string()),
ContentBlock::text(format!("session_id: {session}")),
]);
result.structured_content = Some(value);
result
}
});
}
let progress = context.meta.get_progress_token();
let mut stream = span.in_scope(|| agent.prompt(prompt).history(prior).stream());
let mut chunks = 0_u32;
loop {
let item = tokio::select! {
_ = context.ct.cancelled() => return Ok(error("Cancelled.")),
item = tokio::time::timeout_at(deadline, stream.next()) => match item {
Err(_) => return Ok(error("The agent run took longer than allowed.")),
Ok(None) => return Ok(error("The agent run ended without an answer.")),
Ok(Some(item)) => item,
},
};
match item {
Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(StreamEvent::Text {
text,
..
}))) => {
chunks += 1;
if let Some(token) = &progress {
let _ = context
.peer
.notify_progress(
ProgressNotificationParam::new(token.clone(), f64::from(chunks))
.with_message(text),
)
.await;
}
}
Ok(MultiTurnStreamItem::FinalResponse(response)) => {
self.save(&session, response.messages.clone(), &span).await;
let answer = response.output();
let mut blocks = vec![ContentBlock::text(answer.clone())];
blocks.extend(image_blocks(&response.content));
let mut result = CallToolResult::success(blocks);
result.structured_content =
Some(json!({"answer": answer, "session_id": session}));
return Ok(result);
}
Ok(_) => {}
Err(failure) => {
tracing::warn!(parent: &span, kind = "run_failed", reason = status_message(&failure), "agent call failed");
return Ok(error(&failure_message(&failure)));
}
}
}
}
async fn save(&self, session: &str, messages: Vec<Message>, span: &tracing::Span) {
if self
.0
.server
.history
.append(session, messages)
.await
.is_err()
{
tracing::warn!(parent: span, kind = "store_error", "could not save the session");
}
}
}
fn failure_message(failure: &PromptError) -> Cow<'static, str> {
if let PromptError::MaxTurns { max_turns, .. } = failure {
return Cow::Owned(if *max_turns <= 1 {
"The agent reached its turn limit (1); agents with tools usually need AgentBuilder::default_max_turns(n) with n >= 2.".to_owned()
} else {
format!(
"The agent reached its turn limit ({max_turns}); raise AgentBuilder::default_max_turns above {max_turns} if the task needs more steps."
)
});
}
Cow::Borrowed(status_message(failure))
}
fn status_message(failure: &PromptError) -> &'static str {
let (status, retryable) = match failure {
PromptError::Provider(provider) => (
failure
.provider_response_status()
.map(|status| status.as_u16()),
provider.is_retryable(),
),
PromptError::Report(report) => (
report.http_status.or(report
.provider_response_status()
.map(|status| status.as_u16())),
report.retryable,
),
_ => (None, false),
};
match status {
Some(429) => "The model provider is rate limiting this server; try again in a moment.",
Some(401 | 403) => "The model provider rejected this server's credentials.",
Some(500..=599) => "The model provider is unavailable right now; try again shortly.",
Some(_) => "The model provider rejected the request.",
None if retryable => "The model provider could not be reached; try again shortly.",
None => "The agent run failed.",
}
}
fn error(text: &str) -> CallToolResult {
CallToolResult::error(vec![ContentBlock::text(text)])
}
fn object(value: Value) -> JsonObject {
match value {
Value::Object(map) if !map.is_empty() => map,
_ => JsonObject::from_iter([
("type".to_owned(), json!("object")),
("properties".to_owned(), json!({})),
]),
}
}
fn agent_input() -> JsonObject {
object(json!({
"type": "object",
"properties": {
"message": {
"type": "string",
"description": "What to ask or tell the agent, self-contained."
},
"session_id": {
"type": "string",
"description": "The session_id of an earlier answer, to continue that conversation."
}
},
"required": ["message"],
"additionalProperties": false
}))
}
fn agent_identity(agent: &Agent) -> (String, String) {
let name = tool_name(agent.name().unwrap_or("agent"));
let description = format!(
"{} Ask it in plain language; pass the session_id of an earlier answer to continue \
the same conversation.",
agent.description().unwrap_or("A Rig agent.")
);
(name, description)
}
pub(crate) fn tool_name(name: &str) -> String {
let mut safe: String = name
.trim()
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect();
safe.truncate(MAX_TOOL_NAME);
let safe = safe.trim_matches('_');
if safe.is_empty() {
"agent".to_owned()
} else {
safe.to_owned()
}
}
#[cfg(test)]
mod tests;