Skip to main content

McpServer

Struct McpServer 

Source
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

Source

pub fn new(name: impl Into<String>) -> Self

A server introducing itself to clients as name, with nothing to offer yet.

Source

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.

Source

pub fn version(self, version: impl Into<String>) -> Self

The version clients see. Defaults to this crate’s version.

Source

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.

Source

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.

Source

pub fn instructions(self, instructions: impl Into<String>) -> Self

Instructions clients may pass to their model about using this server.

Source

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.

Source

pub fn typed_agent<T>(self, agent: Agent) -> Self
where T: JsonSchema + DeserializeOwned + Serialize + Send + Sync + 'static,

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn history_store<S>(self, store: S) -> Self
where S: AsyncStore + Send + Sync + 'static,

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.

Source

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.

Source

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.

Source

pub fn max_run_duration(self, max: Duration) -> Self

Stop an agent run that takes longer than max.

Source

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.

Source

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.

Source

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.

Source

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,

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."))]
    },
);
Source

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.

Source

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: Error + Send + Sync + 'static,

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}"))
    },
);
Source

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
where F: Fn(TemplateVars) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<String, E>> + Send + 'static, E: Error + Send + Sync + 'static,

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.

Source

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,

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.

Source

pub fn completer<F, Fut, E>(self, complete: F) -> Self
where F: Fn(CompletionRequest) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Vec<String>, E>> + Send + 'static, E: Error + Send + Sync + 'static,

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

Source

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.

Source

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.)

Source

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.

Source

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.

Source

pub async fn serve<T, E, A>(self, transport: T) -> Result<(), ServeError>
where T: IntoTransport<RoleServer, E, A>, E: Error + Send + Sync + 'static,

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.

Source

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.

Auto Trait Implementations§

§

impl !RefUnwindSafe for McpServer

§

impl !UnwindSafe for McpServer

§

impl Forget for McpServer

§

impl Freeze for McpServer
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze, PhantomData<Icon>: Freeze, PhantomData<Entry>: Freeze, PhantomData<StaticResource>: Freeze, PhantomData<StaticTemplate>: Freeze, PhantomData<StaticPrompt>: Freeze, *const ArcInner<dyn HistoryStore> is !null: Freeze, PhantomData<ArcInner<dyn HistoryStore>>: Freeze, *const ArcInner<dyn Recent> is !null: Freeze, PhantomData<ArcInner<dyn Recent>>: Freeze, *const ArcInner<Semaphore> is !null: Freeze, PhantomData<ArcInner<Semaphore>>: Freeze, PhantomData<String>: Freeze, *const ArcInner<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send> is !null: Freeze, PhantomData<ArcInner<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>>: Freeze,

§

impl Move for McpServer

§

impl Send for McpServer
where RawVecInner: Send, &'static str: Send, String: Send, Arc<Map<String, Value>>: Send, NodeRef<Owned, String, Value, LeafOrInternal>: Send, BoxRaw<(String, Value)>: Send, Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolExecutionError>> + Send>> + Sync + Send>: Send, BoxRaw<Agent>: Send, Arc<dyn Fn(Agent, Message, Vec<Message>) -> Pin<Box<dyn Future<Output = Result<(Value, Vec<Message>), String>> + Send>> + Sync + Send>: Send, Arc<dyn Fn(TemplateVars) -> Pin<Box<dyn Future<Output = Result<String, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Send, Arc<dyn Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Sync + Send>: Send, Arc<dyn HistoryStore>: Send, Arc<dyn Recent>: Send, Arc<Semaphore>: Send, Arc<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Send,

§

impl Sync for McpServer
where RawVecInner: Sync, String: Sync, Arc<Map<String, Value>>: Sync, NodeRef<Owned, String, Value, LeafOrInternal>: Sync, BoxRaw<(String, Value)>: Sync, Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolExecutionError>> + Send>> + Sync + Send>: Sync, BoxRaw<Agent>: Sync, Arc<dyn Fn(Agent, Message, Vec<Message>) -> Pin<Box<dyn Future<Output = Result<(Value, Vec<Message>), String>> + Send>> + Sync + Send>: Sync, Arc<dyn Fn(TemplateVars) -> Pin<Box<dyn Future<Output = Result<String, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Sync, Arc<dyn Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Sync + Send>: Sync, Arc<dyn HistoryStore>: Sync, Arc<dyn Recent>: Sync, Arc<Semaphore>: Sync, Arc<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Sync,

§

impl Unpin for McpServer
where *const u8 is !null: Unpin, &'static str: Unpin, String: Unpin, Arc<Map<String, Value>>: Unpin, *const LeafNode<String, Value> is !null: Unpin, Box<(String, Value)>: Unpin, Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<ToolOutput, ToolExecutionError>> + Send>> + Sync + Send>: Unpin, Box<Agent>: Unpin, Arc<dyn Fn(Agent, Message, Vec<Message>) -> Pin<Box<dyn Future<Output = Result<(Value, Vec<Message>), String>> + Send>> + Sync + Send>: Unpin, Arc<dyn Fn(TemplateVars) -> Pin<Box<dyn Future<Output = Result<String, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Unpin, Arc<dyn Fn(&HashMap<String, String>) -> Vec<PromptMessage> + Sync + Send>: Unpin, Arc<dyn HistoryStore>: Unpin, Arc<dyn Recent>: Unpin, Arc<Semaphore>: Unpin, Arc<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>: Unpin,

§

impl UnsafeUnpin for McpServer
where *const u8 is !null: UnsafeUnpin, PhantomData<u8>: UnsafeUnpin, PhantomData<Icon>: UnsafeUnpin, PhantomData<Entry>: UnsafeUnpin, PhantomData<StaticResource>: UnsafeUnpin, PhantomData<StaticTemplate>: UnsafeUnpin, PhantomData<StaticPrompt>: UnsafeUnpin, *const ArcInner<dyn HistoryStore> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn HistoryStore>>: UnsafeUnpin, *const ArcInner<dyn Recent> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Recent>>: UnsafeUnpin, *const ArcInner<Semaphore> is !null: UnsafeUnpin, PhantomData<ArcInner<Semaphore>>: UnsafeUnpin, PhantomData<String>: UnsafeUnpin, *const ArcInner<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send> is !null: UnsafeUnpin, PhantomData<ArcInner<dyn Fn(CompletionRequest) -> Pin<Box<dyn Future<Output = Result<Vec<String>, Box<dyn Error + Sync + Send>>> + Send>> + Sync + Send>>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more