Skip to main content

McpServer

Struct McpServer 

Source
pub struct McpServer { /* private fields */ }
Expand description

An HTTP server that implements the MCP 2024-11-05 protocol.

Register tools, resources, and prompts with the builder methods, then pass the server to [Server::run] (or [Server::run_tls]) as an Application. Requests that do not match the MCP endpoint fall through to the built-in App controller chain.

Implementations§

Source§

impl McpServer

Source

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

Create a new McpServer. The default MCP endpoint is POST /mcp.

Source

pub fn page_size(self, n: usize) -> Self

Cap tools/list, resources/list, and prompts/list to at most n items per response, enabling cursor-based pagination: a response with more items remaining includes "nextCursor", an opaque string the client echoes back as params.cursor on its next call to get the next page. n is clamped to a minimum of 1.

Without calling this, every registered tool/resource/prompt is returned in a single response — the default, and the only behavior before pagination existed.

use rust_web_server::mcp::McpServer;

let server = McpServer::new("my-server", "1.0").page_size(50);
Source

pub fn notify(&self, method: &str, params_json: Option<&str>)

Push a JSON-RPC notification (no id — fire-and-forget, per the spec) to every client currently connected to the GET /mcp SSE stream, framed as an SSE data: event.

params_json, if given, must already be a valid JSON value (usually an object) — it’s spliced in verbatim, not escaped or re-serialized.

Never blocks: a client whose event buffer is full (not reading fast enough) is treated the same as a disconnected one and dropped from the broadcast list, same as notify would drop it anyway.

use rust_web_server::mcp::McpServer;

let server = McpServer::new("my-server", "1.0");
server.notify("notifications/message", Some(r#"{"level":"info","data":"hello"}"#));
Source

pub fn notify_resource_updated(&self, uri: &str)

Push notifications/resources/updated for uri to every session that called resources/subscribe for it — the mechanism behind live-updating resource panels (e.g. Claude Desktop watching a config file or a dashboard resource for changes). Call this from wherever your application actually changes the underlying data a resource represents (a file watcher, a webhook handler, a database trigger poll, …).

A no-op if nobody has subscribed to uri — including if every subscriber’s GET /mcp SSE connection has since disconnected (pruned the same way Self::notify prunes dead broadcast clients, but the subscriptions bookkeeping for uri itself is untouched either way; only Self::do_resource_unsubscribe removes that).

use rust_web_server::mcp::McpServer;

let server = McpServer::new("my-server", "1.0");
// Elsewhere, e.g. after reloading a watched config file:
server.notify_resource_updated("config://main");
Source

pub fn logging_enabled(self) -> Self

Advertise the logging capability ("logging":{}) in initialize’s response, so clients know they can call logging/setLevel and expect notifications/message log entries over the GET /mcp SSE stream.

This only changes what’s advertisedSelf::log pushes log entries regardless of whether this was called, same as Self::notify works unconditionally. A spec-honest client simply wouldn’t send logging/setLevel in the first place without seeing the capability.

use rust_web_server::mcp::McpServer;

let server = McpServer::new("my-server", "1.0").logging_enabled();
Source

pub fn log(&self, level: LogLevel, logger: Option<&str>, data_json: &str)

Push a notifications/message log entry to every client connected to the GET /mcp SSE stream, if level is at or above the level most recently set via a client’s logging/setLevel request (or LogLevel::Debug — i.e. every level — if none has been set yet).

data_json must already be a valid JSON value (the spec allows any type here, not just an object — a plain string is fine) — it’s spliced in verbatim, not escaped or re-serialized. logger, if given, identifies the log’s source (e.g. a module or subsystem name) and is escaped automatically.

use rust_web_server::mcp::{LogLevel, McpServer};

let server = McpServer::new("my-server", "1.0").logging_enabled();
server.log(LogLevel::Warning, Some("database"), r#""connection pool exhausted""#);
Source

pub fn register_tool<F>( &self, name: &str, description: &str, input_schema: &str, handler: F, )
where F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a callable tool at runtime, exactly like Self::tool but without needing to own the server (and usable after it’s already serving requests). Pushes notifications/tools/list_changed.

use rust_web_server::mcp::{McpContent, McpServer};

let server = McpServer::new("my-server", "1.0");

// Later, from any thread holding a clone of `server`:
server.register_tool("refresh_cache", "Reload the in-memory cache", "{}", |_args| {
    Ok(McpContent::text("cache refreshed"))
});
let existed = server.remove_tool("refresh_cache");
assert!(existed);
Source

pub fn register_async_tool<F, Fut>( &self, name: &str, description: &str, input_schema: &str, handler: F, )
where F: Fn(&str) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<McpContent, String>> + Send + 'static,

Register an async fn tool handler at runtime, exactly like Self::async_tool but usable after the server is already serving requests. Requires the http2 feature — see async_tool’s docs for the async-to-sync bridging details.

Source

pub fn remove_tool(&self, name: &str) -> bool

Remove a previously-registered tool by name — a sync tool registered via Self::tool/Self::register_tool, or (with the http2 feature) an async one via Self::async_tool/Self::register_async_tool; both collections are checked. Returns true if a tool with that name existed in either and was removed. Pushes notifications/tools/list_changed only when something was actually removed.

Source

pub fn register_resource<F>( &self, uri_template: &str, name: &str, description: &str, handler: F, )
where F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a readable resource at runtime, exactly like Self::resource. Pushes notifications/resources/list_changed.

Source

pub fn remove_resource(&self, uri_template: &str) -> bool

Remove a previously-registered resource by its exact uri_template (the same string passed to Self::register_resource/Self::resource, not a concrete URI). Returns true if it existed. Pushes notifications/resources/list_changed only when something was removed.

Source

pub fn register_prompt<F>(&self, name: &str, description: &str, handler: F)
where F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,

Register a prompt template at runtime, exactly like Self::prompt (no argument definitions — use Self::remove_prompt + Self::register_prompt if you need to change a prompt’s arguments later; there is no dynamic equivalent of Self::prompt_with_args). Pushes notifications/prompts/list_changed.

Source

pub fn remove_prompt(&self, name: &str) -> bool

Remove a previously-registered prompt by name. Returns true if it existed. Pushes notifications/prompts/list_changed only when something was removed.

Source

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

Require a bearer token on every request to the MCP endpoint.

The client must send Authorization: Bearer <token>. Requests with a missing or wrong token receive 401 Unauthorized before any JSON-RPC processing occurs.

Store the token in an environment variable — never hard-code it:

use rust_web_server::app::App;
use rust_web_server::core::New;

let app = App::new()
    .mcp("my-server", "1.0")
    .require_bearer(std::env::var("MCP_TOKEN").expect("MCP_TOKEN not set"));

Claude Desktop config:

{ "mcpServers": { "my-server": {
    "url": "http://localhost:7878/mcp",
    "headers": { "Authorization": "Bearer <token>" }
}}}
Source

pub fn wrap(self, app: impl Application + Send + Sync + 'static) -> Self

Wrap an existing Application so that non-MCP requests are forwarded to it instead of the built-in App.

Use this when your existing server has custom routes, state, or middleware that you want to keep alongside the MCP endpoint:

use rust_web_server::app::App;
use rust_web_server::mcp::{McpServer, McpContent};
use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
use rust_web_server::test_client::TestClient;

let existing_app = App::with_state(42u32)
    .get("/api/hello", |_req, _params, _conn, _state| {
        Response::get_response(&STATUS_CODE_REASON_PHRASE.n200_ok, None, None)
    });

let server = McpServer::new("my-app", "1.0")
    .tool("ping", "Ping", "{}", |_| Ok(McpContent::text("pong")))
    .wrap(existing_app);

// Both /mcp and /api/hello are now handled by the same server.
let client = TestClient::new(server);
Source

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

Override the HTTP path for the MCP endpoint (default "/mcp").

Source

pub fn tool<F>( self, name: &str, description: &str, input_schema: &str, handler: F, ) -> Self
where F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a callable tool.

  • name — tool identifier (snake_case recommended)
  • description — human-readable description shown to the AI
  • input_schema — JSON Schema object for the tool’s arguments
  • handler — closure receiving the raw arguments JSON string

The handler returns McpContent on success or an error string. An error is returned to the client as isError: true (not a protocol error).

Use Self::tool_with_context instead if the handler needs the caller’s identity, session, or headers.

Source

pub fn async_tool<F, Fut>( self, name: &str, description: &str, input_schema: &str, handler: F, ) -> Self
where F: Fn(&str) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<McpContent, String>> + Send + 'static,

Register an async fn tool handler — for a tool whose work is naturally async (an AsyncClient HTTP call, an async database query, awaiting another future) rather than forcing it through a blocking call inside a plain Self::tool handler.

Requires the http2 feature (tokio). tools/call bridges into the handler’s future via [crate::async_bridge::block_on_isolated] — the same mechanism crate::proxy::H2ReverseProxy and crate::async_state::AsyncAppWithState already use to call async code from a synchronous Application::execute — rather than tokio::task::block_in_place, which panics outside a multi_thread runtime; block_on_isolated works under any runtime flavor, including current_thread.

Like Self::tool (not Self::tool_with_context), the handler only receives arguments — there is no async equivalent of tool_with_context or tool_annotated yet.

use rust_web_server::mcp::{McpContent, McpServer};

let server = McpServer::new("my-server", "1.0")
    .async_tool("call_api", "Call an external API", "{}", |_args: &str| async move {
        Ok(McpContent::text("response"))
    });
Source

pub fn tool_annotated<F>( self, name: &str, description: &str, input_schema: &str, annotations: ToolAnnotations, handler: F, ) -> Self
where F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a callable tool with ToolAnnotations — behavioral hints (read-only, destructive, idempotent, open-world) that MCP clients use to decide whether to warn or confirm before calling it. Otherwise identical to Self::tool — the handler still only receives arguments, not McpContext (there is currently no single builder combining annotations with per-request context; call Self::tool_with_context instead if you need context and don’t need annotations).

use rust_web_server::mcp::{McpContent, McpServer, ToolAnnotations};

let server = McpServer::new("my-server", "1.0")
    .tool_annotated(
        "delete_file",
        "Delete a file from disk",
        r#"{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}"#,
        ToolAnnotations {
            destructive_hint: Some(true),
            read_only_hint: Some(false),
            idempotent_hint: Some(true), // deleting twice = deleting once
            ..Default::default()
        },
        |_args| Ok(McpContent::text("deleted")),
    );
Source

pub fn tool_with_context<F>( self, name: &str, description: &str, input_schema: &str, handler: F, ) -> Self
where F: Fn(McpContext, &str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a callable tool whose handler also receives McpContext — caller identity/session info derived from this request’s headers and whatever clientInfo this session sent at initialize time.

Same name/description/input_schema semantics as Self::tool; the only difference is the handler’s first parameter.

use rust_web_server::mcp::{McpContent, McpServer};

let server = McpServer::new("my-server", "1.0")
    .tool_with_context(
        "whoami",
        "Report the caller's client info",
        "{}",
        |ctx, _args| {
            let name = ctx.client_name.as_deref().unwrap_or("unknown client");
            Ok(McpContent::text(format!("Called by {name}")))
        },
    );
Source

pub fn resource<F>( self, uri_template: &str, name: &str, description: &str, handler: F, ) -> Self
where F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,

Register a readable resource.

uri_template uses {param} placeholders, e.g. "user://{id}". The handler receives the full concrete URI string.

Source

pub fn prompt<F>(self, name: &str, description: &str, handler: F) -> Self
where F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,

Register a prompt template.

The handler receives the raw arguments JSON string and returns a list of PromptMessage values.

Source

pub fn prompt_with_args<F>( self, name: &str, description: &str, args: Vec<PromptArgDef>, handler: F, ) -> Self
where F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,

Register a prompt template with explicit argument definitions.

Source

pub fn completion<F>(self, ref_type: &str, ref_name: &str, handler: F) -> Self
where F: Fn(&str, &str) -> Result<Vec<String>, String> + Send + Sync + 'static,

Register an argument-completion provider for one named argument of a tool or prompt, so clients like Cursor and VS Code can offer autocomplete while the user fills in that argument.

ref_type is "tool" or "prompt" — matched against the incoming completion/complete request’s ref.type ("ref/tool"/"ref/prompt" on the wire) with the "ref/" prefix stripped. ref_name is the tool or prompt name this applies to. The handler receives the argument’s name and whatever partial value the user has typed so far, and returns candidate completion strings (or an error, mapped to a JSON-RPC INVALID_PARAMS response).

initialize advertises the completions capability automatically once at least one .completion() has been registered — there’s no separate opt-in flag to remember.

use rust_web_server::mcp::McpServer;

let server = McpServer::new("my-server", "1.0")
    .completion("tool", "deploy", |arg_name, _partial| {
        match arg_name {
            "region" => Ok(vec!["us-east-1".to_string(), "eu-west-1".to_string()]),
            _ => Ok(vec![]),
        }
    });
Source

pub fn handle_request(&self, body: &str) -> Response

Process a raw JSON-RPC body and return an HTTP response.

Equivalent to Self::handle_request_with_context with an empty McpContext — tool handlers registered via Self::tool_with_context will see every field as None. Prefer calling through Application::execute (i.e. actually serving HTTP requests) when you need real per-request context; this method exists for calling the JSON-RPC layer directly, e.g. in tests.

Source

pub fn handle_request_with_context( &self, body: &str, ctx: McpContext, ) -> Response

Process a raw JSON-RPC body with an explicit McpContext and return an HTTP response. Self::execute calls this with a context built from the request’s headers and this session’s stored clientInfo; Self::handle_request calls this with an empty context.

On a successful initialize, this mints a new session id (reusing crate::request_id::generate_request_id’s ID generator), records params.clientInfo under it, and returns the id in an Mcp-Session-Id response header — the client is expected to echo that header back on subsequent requests so later tools/calls in the same session can look their clientInfo back up.

Trait Implementations§

Source§

impl Application for McpServer

Source§

fn execute( &self, request: &Request, connection: &ConnectionInfo, ) -> Result<Response, String>

Receives a parsed request and returns a fully-built response. Walk your controller list with is_matching / process and return the first match.
Source§

impl Clone for McpServer

Source§

fn clone(&self) -> McpServer

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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