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 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| {
        let mut r = Response::new();
        r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
        r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
        r
    });

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

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 handle_request(&self, body: &str) -> Response

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

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