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
impl McpServer
Sourcepub fn new(name: impl Into<String>, version: impl Into<String>) -> Self
pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self
Create a new McpServer. The default MCP endpoint is POST /mcp.
Sourcepub fn require_bearer(self, token: impl Into<String>) -> Self
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>" }
}}}Sourcepub fn wrap(self, app: impl Application + Send + Sync + 'static) -> Self
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);Sourcepub fn at(self, path: impl Into<String>) -> Self
pub fn at(self, path: impl Into<String>) -> Self
Override the HTTP path for the MCP endpoint (default "/mcp").
Sourcepub fn tool<F>(
self,
name: &str,
description: &str,
input_schema: &str,
handler: F,
) -> Self
pub fn tool<F>( self, name: &str, description: &str, input_schema: &str, handler: F, ) -> Self
Register a callable tool.
name— tool identifier (snake_case recommended)description— human-readable description shown to the AIinput_schema— JSON Schema object for the tool’s argumentshandler— closure receiving the rawargumentsJSON 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.
Sourcepub fn tool_annotated<F>(
self,
name: &str,
description: &str,
input_schema: &str,
annotations: ToolAnnotations,
handler: F,
) -> Self
pub fn tool_annotated<F>( self, name: &str, description: &str, input_schema: &str, annotations: ToolAnnotations, handler: F, ) -> Self
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")),
);Sourcepub fn tool_with_context<F>(
self,
name: &str,
description: &str,
input_schema: &str,
handler: F,
) -> Self
pub fn tool_with_context<F>( self, name: &str, description: &str, input_schema: &str, handler: F, ) -> Self
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}")))
},
);Sourcepub fn resource<F>(
self,
uri_template: &str,
name: &str,
description: &str,
handler: F,
) -> Self
pub fn resource<F>( self, uri_template: &str, name: &str, description: &str, handler: F, ) -> Self
Register a readable resource.
uri_template uses {param} placeholders, e.g. "user://{id}".
The handler receives the full concrete URI string.
Sourcepub fn prompt<F>(self, name: &str, description: &str, handler: F) -> Self
pub fn prompt<F>(self, name: &str, description: &str, handler: F) -> Self
Register a prompt template.
The handler receives the raw arguments JSON string and returns a
list of PromptMessage values.
Sourcepub fn prompt_with_args<F>(
self,
name: &str,
description: &str,
args: Vec<PromptArgDef>,
handler: F,
) -> Self
pub fn prompt_with_args<F>( self, name: &str, description: &str, args: Vec<PromptArgDef>, handler: F, ) -> Self
Register a prompt template with explicit argument definitions.
Sourcepub fn handle_request(&self, body: &str) -> Response
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.
Sourcepub fn handle_request_with_context(
&self,
body: &str,
ctx: McpContext,
) -> Response
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.