Expand description
Model Context Protocol (MCP) server — HTTP Streamable HTTP transport.
McpServer implements Application so it can be passed directly to
[Server::run]. Unmatched requests fall through to the built-in App
controller chain (static files, health probes, etc.).
§Quick start
use rust_web_server::server::Server;
use rust_web_server::mcp::{McpServer, McpContent, PromptMessage};
let mcp = McpServer::new("my-server", "1.0")
// A tool: callable by the AI, like a function
.tool(
"echo",
"Echo text back",
r#"{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}"#,
|args| {
let text = rust_web_server::mcp::extract_arg(args, "text")
.unwrap_or_else(|| "(nothing)".to_string());
Ok(McpContent::text(text))
},
)
// A resource: data the AI can read by URI
.resource(
"docs://{topic}",
"Documentation",
"Return documentation for a topic",
|uri| Ok(McpContent::text(format!("Documentation for: {uri}"))),
)
// A prompt template: reusable message structures
.prompt(
"summarize",
"Summarize the given text",
|args| {
let text = rust_web_server::mcp::extract_arg(args, "text")
.unwrap_or_else(|| "some text".to_string());
Ok(vec![PromptMessage::user(format!("Please summarize: {text}"))])
},
);
// let (listener, pool) = Server::setup().unwrap();
// Server::run(listener, pool, mcp);§MCP endpoint
All JSON-RPC messages are sent as POST /mcp (override with .at()).
The server implements the MCP specification
up to 2025-11-25, negotiating 2024-11-05, 2025-03-26, 2025-06-18 or 2025-11-25.
GET /mcp opens a Server-Sent Events stream for server → client push —
see McpServer::notify and the module docs’ SSE section below.
§SSE streaming transport
A client that sends GET /mcp (instead of POST) gets back a
text/event-stream response that stays open indefinitely. Call
McpServer::notify from anywhere (a background thread, another request’s
handler, …) to push a JSON-RPC notification to every currently-connected
SSE client:
use rust_web_server::mcp::McpServer;
let server = McpServer::new("my-server", "1.0");
// Elsewhere, e.g. after some background job finishes:
server.notify("notifications/message", Some(r#"{"level":"info","data":"job done"}"#));Idle connections receive a : keep-alive SSE comment every 15 seconds so
intermediate proxies don’t time them out; this doubles as the mechanism
that detects a client has disconnected (the next write attempt fails and
the connection is dropped). A client whose event buffer fills up (32
pending frames, unconsumed) is treated the same as a disconnected one and
dropped from the broadcast list — McpServer::notify never blocks the
calling thread waiting on a slow reader.
This transport is only wired up for the plain HTTP/1.1 path
(Server::run/Server::process) — same scope as Response::stream_pipe
generally, which the HTTP/2 (h2_server) and HTTP/3 (h3_handler)
handlers don’t yet support for any response, not just this one.
§Environment variables
None — configure the server programmatically via the builder.
Modules§
- gateway
- A minimal MCP gateway: one endpoint in front of several upstream MCP servers.
Structs§
- Input
Required - A handler’s request for input from the client (MCP 2026-07-28 multi
round-trip requests): the client answers each request and calls again,
the answers then in
McpContext::input_responseunder the same keys, andstateinMcpContext::request_state. - McpContent
- Content returned by tool and resource handlers.
- McpContext
- Per-request context passed to tool handlers registered via
McpServer::tool_with_context— caller identity and session info that a plainFn(&str) -> ...tool handler has no way to see. - McpIcon
- An icon for the server, a tool, a resource or a prompt (MCP 2025-11-25):
srcis anhttps:ordata:URL. - McpRoot
- One filesystem root a client has access to, returned by
McpContext::list_roots— a workspace directory, a mounted volume, or similar.uriis typically afile://URI per spec. - McpServer
- An HTTP server that implements the MCP protocol (2024-11-05 to 2025-11-25).
- Prompt
ArgDef - Argument definition for a prompt template.
- Prompt
Message - A single message in a prompt response.
- Sampling
Request - A request to ask the connected MCP client to run LLM inference
(“sampling”) — build one and pass it to
McpContext::sample. - Sampling
Response - The client’s answer to a
SamplingRequest, returned byMcpContext::sample. - Task
Context - What a task’s work runs with: input from the client through
tasks/update, cancellation, a status message. - Tool
Annotations - Behavioral hints for a tool, per the MCP 2025-03-26 spec’s tool annotations. Clients (Claude Desktop and others) use these to decide whether to warn or ask for confirmation before calling a tool — e.g. skip confirmation for a read-only tool, or warn before a destructive one.
Enums§
- LogLevel
- RFC 5424 syslog severity levels, as used by the MCP
logging/setLevelrequest andnotifications/messagelog entries — ordered from most to least verbose solevel < min_levelcomparisons work directly (this relies on declaration order matching severity order; don’t reorder the variants). - Prompt
Reply - What a prompt handler registered with
McpServer::prompt_with_contextanswers. - Task
Error - Why a task’s work ended without a result.
Constants§
- DEFAULT_
MAX_ SESSIONS - Default cap on MCP sessions.
- DEFAULT_
MAX_ SSE_ CLIENTS - Default cap on open
GET /mcpSSE streams. - DEFAULT_
SESSION_ TTL - Default idle time after which an MCP session is evicted.
Functions§
- extract_
arg - Extract an argument from a tool/prompt
argumentsJSON object: a string’s value, or a number’s or boolean’s literal text ("3","true"). Objects, arrays andnullareNone. Numbers and booleans used to beNonetoo, so a tool reading"enabled": truesaw nothing.