pub struct McpServer { /* private fields */ }Expand description
Rig agents and tools served over the Model Context Protocol.
Each agent becomes a tool taking a message and an
optional session_id: a call runs the agent with that session’s history
and answers with its text (streamed meanwhile as progress notifications
when the client asks for progress) and any image it made. Each
tool is exposed as itself, run without a model.
Serve it to a local client (Claude Code, Cursor, Zed…) over stdio with
serve_stdio, or over Streamable HTTP with
into_router.
Implementations§
Source§impl McpServer
impl McpServer
Sourcepub fn new(name: impl Into<String>) -> Self
pub fn new(name: impl Into<String>) -> Self
A server introducing itself to clients as name, with nothing to
offer yet.
Sourcepub fn ping_route(self) -> Self
pub fn ping_route(self) -> Self
Also serve GET /ping on the HTTP router, answering
{"status": "Healthy"}, the health route AWS Bedrock AgentCore Runtime
recommends for MCP servers. Off by default: a router that already has
its own /ping would clash with it. The route takes no bearer token and
no Host check; /mcp keeps both. HTTP only.
Sourcepub fn version(self, version: impl Into<String>) -> Self
pub fn version(self, version: impl Into<String>) -> Self
The version clients see. Defaults to this crate’s version.
Sourcepub fn title(self, title: impl Into<String>) -> Self
pub fn title(self, title: impl Into<String>) -> Self
A human-readable title clients may show for the server. Optional: left
out of initialize unless set.
Sourcepub fn icon(self, icon: Icon) -> Self
pub fn icon(self, icon: Icon) -> Self
Add an icon clients may show for the server. Its src must be an
http:// or https:// URL or a data: URI, or serving fails with
BuildError::InvalidIcon. Optional: left out of initialize unless
set. Icons keep the order they were added in.
Sourcepub fn instructions(self, instructions: impl Into<String>) -> Self
pub fn instructions(self, instructions: impl Into<String>) -> Self
Instructions clients may pass to their model about using this server.
Sourcepub fn agent(self, agent: Agent) -> Self
pub fn agent(self, agent: Agent) -> Self
Expose agent as a tool named after it (its name, made provider-safe),
described by its description. It answers with text and any images,
plus {answer, session_id} as structured content; passing that
session_id back continues the conversation.
Another tool with the same name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn typed_agent<T>(self, agent: Agent) -> Self
pub fn typed_agent<T>(self, agent: Agent) -> Self
Expose agent as a tool that answers with a T: each call runs as
Agent::prompt_typed does (two retries when the JSON does not parse)
and the T comes back as structured content matching the tool’s
output schema, the schema of T.
Another tool with the agent’s name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn tool<T: Tool + 'static>(self, tool: T) -> Self
pub fn tool<T: Tool + 'static>(self, tool: T) -> Self
Expose a Rig tool as itself: same name, description, parameters and annotations; called directly, with no model involved.
Another tool with the same name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn tool_presented<T: Tool + 'static>(
self,
tool: T,
presentation: Presentation,
) -> Self
pub fn tool_presented<T: Tool + 'static>( self, tool: T, presentation: Presentation, ) -> Self
Expose a Tool as tool does, with a title and icons
for clients to show; see Presentation.
Another tool with the same name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn dynamic_tool(self, tool: DynamicTool) -> Self
pub fn dynamic_tool(self, tool: DynamicTool) -> Self
Expose a DynamicTool as itself; see tool.
Another tool with the same name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn dynamic_tool_presented(
self,
tool: DynamicTool,
presentation: Presentation,
) -> Self
pub fn dynamic_tool_presented( self, tool: DynamicTool, presentation: Presentation, ) -> Self
Expose a DynamicTool with a title and icons; see
tool_presented.
Another tool with the same name makes serving fail with
BuildError::DuplicateTool.
Sourcepub fn max_sessions(self, max: usize) -> Self
pub fn max_sessions(self, max: usize) -> Self
Keep agent sessions in memory, at most max of them; the oldest one
started is forgotten first. This is the default, with
DEFAULT_MAX_CONTEXTS.
Sourcepub fn history_store<S>(self, store: S) -> Self
pub fn history_store<S>(self, store: S) -> Self
Keep agent sessions in any rig_memory store (DirStore on disk,
rig-sqlite, rig-postgres), so they survive restarts and several
servers can share them.
Sourcepub fn history_window(self, window: impl Recent + 'static) -> Self
pub fn history_window(self, window: impl Recent + 'static) -> Self
Which newest messages of a session each call sends the model.
Defaults to DEFAULT_HISTORY_TOKENS
tokens; a tool result is never sent without its call.
Sourcepub fn max_concurrent_calls(self, max: usize) -> Self
pub fn max_concurrent_calls(self, max: usize) -> Self
Run at most max calls at once (at least one); a call beyond that
gets a “busy” error result before any model call.
Sourcepub fn max_run_duration(self, max: Duration) -> Self
pub fn max_run_duration(self, max: Duration) -> Self
Stop an agent run that takes longer than max.
Sourcepub fn list_ttl(self, ttl: Duration) -> Self
pub fn list_ttl(self, ttl: Duration) -> Self
How long clients may cache what the server offers from its fixed
catalog: the tools/list, prompts/list, resources/list and
resources/templates/list results, and reads of static resources.
Defaults to one minute, so a restarted server is picked up soon.
Only sent to clients on protocol 2026-07-28 or later. Template reads
are never cached: their text comes from a callback. A TTL beyond
u64::MAX milliseconds is sent as u64::MAX.
Sourcepub fn resource(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
text: impl Into<String>,
) -> Self
pub fn resource( self, uri: impl Into<String>, name: impl Into<String>, mime_type: impl Into<String>, text: impl Into<String>, ) -> Self
Offer a text resource at uri, read with resources/read. mime_type
tells the client what the text is, such as text/markdown.
Another resource with the same URI makes serving fail with
BuildError::DuplicateResource. Only fixed contents are offered here;
for URIs with variables see resource_template.
No subscriptions and no list-changed notifications.
Sourcepub fn binary_resource(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
bytes: impl AsRef<[u8]>,
) -> Self
pub fn binary_resource( self, uri: impl Into<String>, name: impl Into<String>, mime_type: impl Into<String>, bytes: impl AsRef<[u8]>, ) -> Self
Offer a binary resource at uri. The bytes travel base64-encoded in
the resources/read result, labelled with mime_type.
Another resource with the same URI makes serving fail with
BuildError::DuplicateResource.
Sourcepub fn prompt<F>(
self,
name: impl Into<String>,
description: impl Into<String>,
arguments: Vec<PromptArgument>,
render: F,
) -> Self
pub fn prompt<F>( self, name: impl Into<String>, description: impl Into<String>, arguments: Vec<PromptArgument>, render: F, ) -> Self
Offer a prompt named name. Its arguments are listed to the client;
a call to prompts/get without a required one is refused with an
invalid-params error. render turns the arguments the client passed
(all strings, keyed by name) into the prompt’s messages.
Another prompt with the same name makes serving fail with
BuildError::DuplicatePrompt. Prompts are fixed: no list-changed
notifications. Their arguments complete through completer.
use std::collections::HashMap;
use rig_mcp_server::{McpServer, rmcp::model::{PromptArgument, PromptMessage, Role}};
let server = McpServer::new("docs").prompt(
"explain",
"Explain a topic for a reader.",
vec![PromptArgument::new("topic").with_required(true)],
|args: &HashMap<String, String>| {
let topic = args.get("topic").map_or("", String::as_str);
vec![PromptMessage::new_text(Role::User, format!("Explain {topic} in plain words."))]
},
);Sourcepub fn resource_presented(
self,
uri: impl Into<String>,
name: impl Into<String>,
mime_type: impl Into<String>,
text: impl Into<String>,
presentation: Presentation,
) -> Self
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
Expose a text resource as resource does, with a title
and icons for clients to show; see Presentation.
Another resource with the same URI makes serving fail with
BuildError::DuplicateResource.
Sourcepub 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
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
Offer a resource template, listed by resources/templates/list. Any URI
that matches uri_template is read with read, which gets the variables
the URI matched and returns the text. description and mime_type are
listed to the client.
uri_template is an RFC 6570 template with simple {name} variables only:
each name is letters, digits or _, used once. A variable matches one path
segment (no literal /) and its value is percent-decoded, so %2F reads
as / inside the value. A URI whose value is not valid UTF-8 after decoding
is not found. For example memo://{id}. When two templates match a URI, the
one registered first is read. A malformed template, or a second one with the
same text, makes serving fail with
BuildError::InvalidResourceTemplate or
BuildError::DuplicateResourceTemplate. A static resource with the same
URI wins over a template.
An error from read reaches the client as an internal JSON-RPC error with
a fixed message; its text is logged by kind only and not sent.
use rig_mcp_server::{McpServer, TemplateVars};
let server = McpServer::new("notes").resource_template(
"memo://{id}",
"memo",
"A memo, by its id.",
"text/plain",
|vars: TemplateVars| async move {
let id = vars.get("id").unwrap_or_default();
Ok::<_, std::io::Error>(format!("memo {id}"))
},
);Sourcepub fn resource_template_presented<F, Fut, E>(
self,
uri_template: impl Into<String>,
name: impl Into<String>,
description: impl Into<String>,
mime_type: impl Into<String>,
presentation: Presentation,
read: F,
) -> Self
pub fn resource_template_presented<F, Fut, E>( self, uri_template: impl Into<String>, name: impl Into<String>, description: impl Into<String>, mime_type: impl Into<String>, presentation: Presentation, read: F, ) -> Self
Offer a resource template as resource_template
does, with a title and icons for clients to show; see Presentation.
Another template with the same text makes serving fail with
BuildError::DuplicateResourceTemplate.
Sourcepub fn prompt_presented<F>(
self,
name: impl Into<String>,
description: impl Into<String>,
arguments: Vec<PromptArgument>,
render: F,
presentation: Presentation,
) -> Self
pub fn prompt_presented<F>( self, name: impl Into<String>, description: impl Into<String>, arguments: Vec<PromptArgument>, render: F, presentation: Presentation, ) -> Self
Offer a prompt as prompt does, with a title and icons
for clients to show; see Presentation.
Another prompt with the same name makes serving fail with
BuildError::DuplicatePrompt.
Sourcepub fn completer<F, Fut, E>(self, complete: F) -> Self
pub fn completer<F, Fut, E>(self, complete: F) -> Self
Answer completion/complete with complete. It gets a
CompletionRequest (the prompt or resource, the argument, the value
typed so far, and the arguments already resolved) and returns the
candidates. The server sends at most 100 and sets hasMore when it cuts
the list. Filtering by the typed value is up to complete.
A request for a prompt, argument, or resource the server does not offer is
refused with invalid params (-32602) before complete runs. Setting a
completer advertises the completions capability. Without one, the
capability is absent and completion/complete is refused as an unknown
method. An error from complete reaches the client as an internal
JSON-RPC error with a fixed message; its text is logged by kind only and
not sent.
use rig_mcp_server::{CompletionRequest, CompletionTarget, McpServer};
let server = McpServer::new("docs").completer(|request: CompletionRequest| async move {
let topics = ["rust", "ruby", "python"];
let matches = match &request.target {
CompletionTarget::Prompt(name) if name == "explain" => topics
.iter()
.filter(|topic| topic.starts_with(request.value.as_str()))
.map(|topic| topic.to_string())
.collect(),
_ => Vec::new(),
};
Ok::<_, std::io::Error>(matches)
});Source§impl McpServer
impl McpServer
Sourcepub fn max_request_bytes(self, bytes: usize) -> Self
pub fn max_request_bytes(self, bytes: usize) -> Self
Refuse HTTP request bodies over bytes with 413 Payload Too Large,
before they are parsed. Defaults to DEFAULT_MAX_REQUEST_BYTES.
HTTP only: over stdio there is no request body to limit.
Sourcepub fn bearer_token(self, token: impl Into<String>) -> Self
pub fn bearer_token(self, token: impl Into<String>) -> Self
Require Authorization: Bearer <token> on the HTTP endpoint; calls
without it get HTTP 401. (Over stdio the client launched the server
itself, so there is nothing to check.)
Sourcepub fn allowed_hosts(
self,
hosts: impl IntoIterator<Item = impl Into<String>>,
) -> Self
pub fn allowed_hosts( self, hosts: impl IntoIterator<Item = impl Into<String>>, ) -> Self
Host names the HTTP endpoint answers to. Defaults to localhost,
127.0.0.1 and ::1 only, which protects a local server from DNS
rebinding; set the public host name when deploying behind one.
Sourcepub async fn serve_stdio(self) -> Result<(), ServeError>
pub async fn serve_stdio(self) -> Result<(), ServeError>
Serve over stdin and stdout until the client disconnects: what a local MCP client (Claude Code, Cursor, Zed) expects of a server it launches. Stdout carries the protocol, so log to stderr only.
§Errors
A BuildError when two tools, resources or prompts clash, or the transport’s error.
Sourcepub async fn serve<T, E, A>(self, transport: T) -> Result<(), ServeError>
pub async fn serve<T, E, A>(self, transport: T) -> Result<(), ServeError>
Serve over any MCP transport (an in-memory duplex, a socket, a custom one) until the client disconnects.
§Errors
A BuildError when two tools, resources or prompts clash, or the transport’s error.
Sourcepub fn into_router(self) -> Result<Router, BuildError>
pub fn into_router(self) -> Result<Router, BuildError>
The Streamable HTTP endpoint at MCP_PATH, as an Axum router.
§Errors
BuildError::DuplicateTool when two tools share a name,
BuildError::DuplicateResource when two resources share a URI, or
BuildError::DuplicatePrompt when two prompts share a name.