rust_web_server/mcp/mod.rs
1//! Model Context Protocol (MCP) server — HTTP Streamable HTTP transport.
2//!
3//! [`McpServer`] implements [`Application`] so it can be passed directly to
4//! [`Server::run`]. Unmatched requests fall through to the built-in [`App`]
5//! controller chain (static files, health probes, etc.).
6//!
7//! # Quick start
8//!
9//! ```rust,no_run
10//! use rust_web_server::server::Server;
11//! use rust_web_server::mcp::{McpServer, McpContent, PromptMessage};
12//! # fn main() {
13//! let mcp = McpServer::new("my-server", "1.0")
14//! // A tool: callable by the AI, like a function
15//! .tool(
16//! "echo",
17//! "Echo text back",
18//! r#"{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}"#,
19//! |args| {
20//! let text = rust_web_server::mcp::extract_arg(args, "text")
21//! .unwrap_or_else(|| "(nothing)".to_string());
22//! Ok(McpContent::text(text))
23//! },
24//! )
25//! // A resource: data the AI can read by URI
26//! .resource(
27//! "docs://{topic}",
28//! "Documentation",
29//! "Return documentation for a topic",
30//! |uri| Ok(McpContent::text(format!("Documentation for: {uri}"))),
31//! )
32//! // A prompt template: reusable message structures
33//! .prompt(
34//! "summarize",
35//! "Summarize the given text",
36//! |args| {
37//! let text = rust_web_server::mcp::extract_arg(args, "text")
38//! .unwrap_or_else(|| "some text".to_string());
39//! Ok(vec![PromptMessage::user(format!("Please summarize: {text}"))])
40//! },
41//! );
42//!
43//! // let (listener, pool) = Server::setup().unwrap();
44//! // Server::run(listener, pool, mcp);
45//! # }
46//! ```
47//!
48//! # MCP endpoint
49//!
50//! All JSON-RPC messages are sent as `POST /mcp` (override with [`.at()`](McpServer::at)).
51//! The server implements the [MCP specification](https://modelcontextprotocol.io/specification/2025-11-25)
52//! up to 2025-11-25, negotiating 2024-11-05, 2025-03-26, 2025-06-18 or 2025-11-25.
53//!
54//! `GET /mcp` opens a Server-Sent Events stream for server → client push —
55//! see [`McpServer::notify`] and the module docs' SSE section below.
56//!
57//! # SSE streaming transport
58//!
59//! A client that sends `GET /mcp` (instead of `POST`) gets back a
60//! `text/event-stream` response that stays open indefinitely. Call
61//! [`McpServer::notify`] from anywhere (a background thread, another request's
62//! handler, ...) to push a JSON-RPC notification to every currently-connected
63//! SSE client:
64//!
65//! ```rust,no_run
66//! use rust_web_server::mcp::McpServer;
67//!
68//! let server = McpServer::new("my-server", "1.0");
69//! // Elsewhere, e.g. after some background job finishes:
70//! server.notify("notifications/message", Some(r#"{"level":"info","data":"job done"}"#));
71//! ```
72//!
73//! Idle connections receive a `: keep-alive` SSE comment every 15 seconds so
74//! intermediate proxies don't time them out; this doubles as the mechanism
75//! that detects a client has disconnected (the next write attempt fails and
76//! the connection is dropped). A client whose event buffer fills up (32
77//! pending frames, unconsumed) is treated the same as a disconnected one and
78//! dropped from the broadcast list — [`McpServer::notify`] never blocks the
79//! calling thread waiting on a slow reader.
80//!
81//! This transport is only wired up for the plain HTTP/1.1 path
82//! (`Server::run`/`Server::process`) — same scope as `Response::stream_pipe`
83//! generally, which the HTTP/2 (`h2_server`) and HTTP/3 (`h3_handler`)
84//! handlers don't yet support for *any* response, not just this one.
85//!
86//! # Environment variables
87//!
88//! None — configure the server programmatically via the builder.
89
90pub(crate) mod json_rpc;
91pub mod gateway;
92mod modern;
93mod tasks;
94
95pub use modern::{InputRequired, PromptReply};
96pub use tasks::{TaskContext, TaskError};
97
98#[cfg(test)]
99mod tests;
100
101use std::collections::HashMap;
102#[cfg(feature = "http2")]
103use std::future::Future;
104#[cfg(feature = "http2")]
105use std::pin::Pin;
106use std::sync::mpsc::{self, SyncSender};
107use std::sync::{Arc, Mutex, RwLock};
108use std::time::Duration;
109
110use crate::app::App;
111use crate::application::Application;
112use crate::core::New;
113use crate::header::Header;
114use crate::mime_type::MimeType;
115use crate::range::Range;
116use crate::request::Request;
117use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
118use crate::server::ConnectionInfo;
119
120/// The newest MCP protocol version this server speaks (#3).
121pub(crate) const PROTOCOL_VERSION: &str = "2025-11-25";
122
123/// Every protocol version this server speaks, oldest first.
124pub(crate) const SUPPORTED_PROTOCOL_VERSIONS: [&str; 4] = ["2024-11-05", "2025-03-26", "2025-06-18", "2025-11-25"];
125
126/// The version a request without `MCP-Protocol-Version` is taken to use
127/// (Streamable HTTP transport, 2025-06-18).
128const ASSUMED_PROTOCOL_VERSION: &str = "2025-03-26";
129
130/// The version to answer an `initialize` asking for `requested` with: that
131/// version when this server speaks it, else the newest (the client then
132/// decides whether it can continue).
133pub(crate) fn negotiate_version(requested: Option<&str>) -> &'static str {
134 requested
135 .and_then(|v| SUPPORTED_PROTOCOL_VERSIONS.iter().find(|s| **s == v).copied())
136 .unwrap_or(PROTOCOL_VERSION)
137}
138
139// ── public content types ──────────────────────────────────────────────────────
140
141/// Content returned by tool and resource handlers.
142///
143/// Create with [`McpContent::text`] (plain text or JSON strings),
144/// [`McpContent::json`] (marks MIME type as `application/json`),
145/// [`McpContent::image`] (base64-encoded binary image data), or
146/// [`McpContent::embedded`] (a resource embedded inline in a tool response).
147#[derive(Clone, Debug)]
148pub struct McpContent {
149 /// `"text"`, `"image"`, `"audio"`, `"resource"`, `"blob"`, `"blocks"`
150 /// or `"structured"`.
151 pub kind: &'static str,
152 /// The content string — text for `"text"`, base64 data for `"image"`,
153 /// or the embedded resource's text for `"resource"`.
154 pub text: String,
155 /// Optional MIME type override (default `"text/plain"` for `"text"`;
156 /// required in practice for `"image"`/`"resource"`, set by their
157 /// constructors).
158 pub mime_type: Option<String>,
159 /// The resource URI — only set (and only serialized) for `"resource"`.
160 pub uri: Option<String>,
161}
162
163impl McpContent {
164 /// Plain-text content.
165 pub fn text(s: impl Into<String>) -> Self {
166 McpContent { kind: "text", text: s.into(), mime_type: None, uri: None }
167 }
168
169 /// JSON content — sets `mimeType` to `application/json`.
170 pub fn json(s: impl Into<String>) -> Self {
171 McpContent { kind: "text", text: s.into(), mime_type: Some("application/json".to_string()), uri: None }
172 }
173
174 /// Structured content (MCP 2025-06-18): `json` is a JSON value — usually an
175 /// object matching the tool's [`McpServer::tool_output_schema`] — sent as
176 /// the result's `structuredContent`, and as text for older clients.
177 pub fn structured(json: impl Into<String>) -> Self {
178 McpContent { kind: "structured", text: json.into(), mime_type: Some("application/json".to_string()), uri: None }
179 }
180
181 /// Audio content — `data` is base64-encoded audio and `mime_type` e.g.
182 /// `"audio/wav"` (MCP 2025-03-26).
183 pub fn audio(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
184 McpContent { kind: "audio", text: data.into(), mime_type: Some(mime_type.into()), uri: None }
185 }
186
187 /// A binary resource for `resources/read` — `data` is base64-encoded and
188 /// sent as the contents' `blob` (with `mime_type`) instead of `text`.
189 pub fn blob(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
190 McpContent { kind: "blob", text: data.into(), mime_type: Some(mime_type.into()), uri: None }
191 }
192
193 /// Several content items in one tool result — e.g. a text summary, an
194 /// image and an embedded resource. Each item renders as it would alone.
195 pub fn blocks(items: impl IntoIterator<Item = McpContent>) -> Self {
196 let rendered: Vec<String> = items.into_iter().map(|item| item.to_content_json()).collect();
197 McpContent { kind: "blocks", text: rendered.join(","), mime_type: None, uri: None }
198 }
199
200 /// The tool needs input from the client before it can finish (MCP
201 /// 2026-07-28 multi round-trip requests): the client answers
202 /// `input`'s requests and calls the tool again, with the answers in
203 /// [`McpContext::input_response`] and the state in
204 /// [`McpContext::request_state`]. A client on an earlier protocol
205 /// version gets a tool error instead.
206 pub fn input_required(input: InputRequired) -> Self {
207 McpContent { kind: "input_required", text: input.to_json(), mime_type: None, uri: None }
208 }
209
210 /// A complete `tools/call` result (`{"content":[...],...}`), sent as is —
211 /// how the gateway passes an upstream server's result through.
212 pub(crate) fn raw_result(json: impl Into<String>) -> Self {
213 McpContent { kind: "result", text: json.into(), mime_type: Some("application/json".to_string()), uri: None }
214 }
215
216 /// Image content (screenshot, chart, generated art) — `data` is base64-encoded
217 /// binary and `mime_type` is e.g. `"image/png"`.
218 pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
219 McpContent { kind: "image", text: data.into(), mime_type: Some(mime_type.into()), uri: None }
220 }
221
222 /// A resource embedded inline in a tool response, as opposed to one a
223 /// client fetches separately via `resources/read`.
224 pub fn embedded(uri: impl Into<String>, text: impl Into<String>, mime_type: impl Into<String>) -> Self {
225 McpContent { kind: "resource", text: text.into(), mime_type: Some(mime_type.into()), uri: Some(uri.into()) }
226 }
227
228 fn to_content_json(&self) -> String {
229 match self.kind {
230 "image" | "audio" => format!(
231 r#"{{"type":"{}","data":"{}","mimeType":"{}"}}"#,
232 self.kind,
233 json_escape(&self.text),
234 json_escape(self.mime_type.as_deref().unwrap_or("application/octet-stream")),
235 ),
236 "blob" => format!(
237 r#"{{"type":"resource","resource":{{"uri":"{}","mimeType":"{}","blob":"{}"}}}}"#,
238 json_escape(self.uri.as_deref().unwrap_or("")),
239 json_escape(self.mime()),
240 json_escape(&self.text),
241 ),
242 "blocks" => self.text.clone(),
243 "resource" => format!(
244 r#"{{"type":"resource","resource":{{"uri":"{}","mimeType":"{}","text":"{}"}}}}"#,
245 json_escape(self.uri.as_deref().unwrap_or("")),
246 json_escape(self.mime_type.as_deref().unwrap_or("text/plain")),
247 json_escape(&self.text),
248 ),
249 _ => format!(r#"{{"type":"text","text":"{}"}}"#, json_escape(&self.text)),
250 }
251 }
252
253 fn mime(&self) -> &str {
254 self.mime_type.as_deref().unwrap_or("text/plain")
255 }
256}
257
258/// A single message in a prompt response.
259#[derive(Clone, Debug)]
260pub struct PromptMessage {
261 /// `"user"` or `"assistant"`.
262 pub role: &'static str,
263 /// The message content.
264 pub content: McpContent,
265}
266
267impl PromptMessage {
268 /// Build a user-role message.
269 pub fn user(text: impl Into<String>) -> Self {
270 PromptMessage { role: "user", content: McpContent::text(text) }
271 }
272
273 /// Build an assistant-role message.
274 pub fn assistant(text: impl Into<String>) -> Self {
275 PromptMessage { role: "assistant", content: McpContent::text(text) }
276 }
277
278 fn to_json(&self) -> String {
279 format!(
280 r#"{{"role":"{}","content":{}}}"#,
281 self.role,
282 self.content.to_content_json(),
283 )
284 }
285}
286
287/// Argument definition for a prompt template.
288#[derive(Clone)]
289pub struct PromptArgDef {
290 pub name: String,
291 pub description: String,
292 pub required: bool,
293}
294
295impl PromptArgDef {
296 pub fn required(name: impl Into<String>, description: impl Into<String>) -> Self {
297 PromptArgDef { name: name.into(), description: description.into(), required: true }
298 }
299
300 pub fn optional(name: impl Into<String>, description: impl Into<String>) -> Self {
301 PromptArgDef { name: name.into(), description: description.into(), required: false }
302 }
303}
304
305// ── McpContext ────────────────────────────────────────────────────────────────
306
307/// Per-request context passed to tool handlers registered via
308/// [`McpServer::tool_with_context`] — caller identity and session info that a
309/// plain `Fn(&str) -> ...` tool handler has no way to see.
310///
311/// Constructed in [`McpServer::execute`] from the current request's headers
312/// plus whatever `clientInfo` was recorded for this session at `initialize`
313/// time (see [`McpServer::handle_request_with_context`]).
314#[derive(Debug, Clone, Default)]
315pub struct McpContext {
316 /// `clientInfo.name` sent in this session's `initialize` call, if the
317 /// client sent one and this request carries a recognized `Mcp-Session-Id`.
318 pub client_name: Option<String>,
319 /// `clientInfo.version` sent in this session's `initialize` call, under
320 /// the same conditions as `client_name`.
321 pub client_version: Option<String>,
322 /// The `Mcp-Session-Id` header on this request, if present — the value
323 /// the server minted and returned in the `initialize` response header
324 /// for this session (see the module docs' Sessions section).
325 pub session_id: Option<String>,
326 /// The verified caller's claims as a JSON string: the serialized
327 /// [`crate::sso::OidcClaims`] when [`McpServer::require_oauth`] (`sso`
328 /// feature) is configured and this request's bearer token verified, or
329 /// `{"sub":"<identity>"}` for a token from
330 /// [`McpServer::require_bearer_tokens`]. `None` if OAuth isn't configured, or for a
331 /// hand-built context (e.g. `handle_request` in tests) that bypassed
332 /// `McpServer::execute`'s auth check entirely.
333 pub auth_claims: Option<String>,
334 /// The raw JSON value of `params._meta.progressToken` from the
335 /// triggering `tools/call` request, if the client sent one — a spec
336 /// `string | number`, so this is stored pre-rendered (already correctly
337 /// quoted if it's a string) rather than decoded, and spliced back
338 /// verbatim by [`Self::report_progress`]. `None` for anything other than
339 /// a `tools/call` whose caller asked for progress updates.
340 pub progress_token: Option<String>,
341 /// Shared handle back to the owning [`McpServer`]'s SSE broadcast list,
342 /// used by [`Self::report_progress`]. Not `pub` — this is plumbing, not
343 /// part of the context data a handler reads. `None` for a context built
344 /// by hand (e.g. via [`McpServer::handle_request_with_context`] in a
345 /// test) rather than through [`McpServer::execute`], in which case
346 /// `report_progress` silently no-ops — there's no live server to
347 /// broadcast through.
348 sse_clients: Option<Arc<Mutex<Vec<SseClient>>>>,
349 /// Shared flag flipped by a `notifications/cancelled` referencing this
350 /// `tools/call`'s request id, checked by [`Self::is_cancelled`]. Not
351 /// `pub` — see that method. `None` for anything other than a live
352 /// `tools/call` dispatched through [`McpServer::execute`]/`handle_request_with_context`.
353 cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
354 /// Whether this session's `initialize` call declared
355 /// `params.capabilities.sampling`, checked by [`Self::sample`] before
356 /// sending a request the client never said it could answer.
357 sampling_supported: bool,
358 /// Shared handle to the owning [`McpServer`]'s in-flight
359 /// server-initiated-request registry (`sampling/createMessage`,
360 /// `roots/list`), used by [`Self::sample`]/[`Self::list_roots`]. Not
361 /// `pub` — see `sse_clients` for the same "plumbing, not context data"
362 /// reasoning; `None` under the same conditions.
363 pending_replies: Option<Arc<Mutex<HashMap<String, mpsc::Sender<Result<String, String>>>>>>,
364 /// Whether this session's `initialize` call declared
365 /// `params.capabilities.roots`, checked by [`Self::list_roots`] before
366 /// sending a request the client never said it could answer.
367 roots_supported: bool,
368 /// Shared handle to the owning [`McpServer`]'s session registry, used
369 /// by [`Self::list_roots`] to read/write this session's cached roots
370 /// list. Not `pub` — plumbing, not context data.
371 sessions: Option<Arc<Mutex<HashMap<String, StoredClientInfo>>>>,
372 /// The SSE response of the `tools/call` POST this context serves, when
373 /// the client asked for progress and accepts `text/event-stream`:
374 /// progress notifications go there, ahead of the result.
375 request_stream: Option<SseSender>,
376 /// What an MCP 2026-07-28 request carries per request: the client's
377 /// capabilities, `inputResponses`, the verified `requestState` and the
378 /// log level. `None` on earlier protocol versions.
379 modern: Option<Arc<modern::ModernRequest>>,
380 /// Where [`Self::start_task`] puts tasks — set when the client declared
381 /// the tasks extension on this request (MCP 2026-07-28).
382 tasks: Option<tasks::TaskHandle>,
383}
384
385impl McpContext {
386 /// Push a `notifications/progress` event over the SSE channel for this
387 /// request's `progressToken`, if the client asked for progress updates
388 /// (`params._meta.progressToken` on the triggering `tools/call`) and
389 /// this context was built through a live [`McpServer`] (via `execute()`,
390 /// not a bare `McpContext { .. }` — see the `sse_clients` field doc).
391 ///
392 /// Silently does nothing in either case — a handler doesn't need to
393 /// branch on whether progress reporting is actually wired up before
394 /// calling this; it's always safe to call.
395 ///
396 /// `total` and `message` are both optional, matching the spec's
397 /// `notifications/progress` shape: `{"progressToken":...,"progress":...,
398 /// "total":...,"message":"..."}` (with `total`/`message` omitted when not
399 /// given here).
400 ///
401 /// ```rust,no_run
402 /// use rust_web_server::mcp::{McpContent, McpServer};
403 ///
404 /// let server = McpServer::new("my-server", "1.0")
405 /// .tool_with_context("long_job", "Do something slow", "{}", |ctx, _args| {
406 /// ctx.report_progress(0.0, Some(100.0), Some("starting"));
407 /// // ... do work ...
408 /// ctx.report_progress(100.0, Some(100.0), Some("done"));
409 /// Ok(McpContent::text("done"))
410 /// });
411 /// ```
412 pub fn report_progress(&self, progress: f64, total: Option<f64>, message: Option<&str>) {
413 let (Some(token), Some(sse_clients)) = (&self.progress_token, &self.sse_clients) else {
414 return;
415 };
416
417 let total_field = match total {
418 Some(t) => format!(r#","total":{t}"#),
419 None => String::new(),
420 };
421 let message_field = match message {
422 Some(m) => format!(r#","message":"{}""#, json_escape(m)),
423 None => String::new(),
424 };
425 let params = format!(
426 r#"{{"progressToken":{token},"progress":{progress}{total_field}{message_field}}}"#
427 );
428 let json = render_notification("notifications/progress", Some(¶ms));
429 if let Some(stream) = &self.request_stream {
430 let _ = stream.send(format!("data: {json}\n\n").into_bytes());
431 } else if let Some(session) = &self.session_id {
432 send_sse_to_sessions(sse_clients, std::slice::from_ref(session), &json);
433 } else {
434 broadcast_sse_to(sse_clients, &json);
435 }
436 }
437
438 /// `true` if the client sent `notifications/cancelled` referencing this
439 /// `tools/call`'s request id.
440 ///
441 /// Rust cannot forcibly interrupt a running synchronous closure — same
442 /// limitation [`crate::timeout::with_timeout`] documents — so this is
443 /// *cooperative* cancellation: nothing happens automatically. A handler
444 /// that does its own iterative work (processing a batch of items, say)
445 /// can check this between steps and return early; a handler that never
446 /// checks it runs to completion regardless, exactly as before this
447 /// existed.
448 ///
449 /// Always `false` if the client never sent a cancellation, if this
450 /// wasn't dispatched as a `tools/call` (the only method cancellation
451 /// applies to), or if `ctx` was built without a live server behind it.
452 ///
453 /// ```rust,no_run
454 /// use rust_web_server::mcp::{McpContent, McpServer};
455 ///
456 /// let server = McpServer::new("my-server", "1.0")
457 /// .tool_with_context("process_batch", "Process many items", "{}", |ctx, _args| {
458 /// for i in 0..1_000_000 {
459 /// if ctx.is_cancelled() {
460 /// return Err("cancelled by client".to_string());
461 /// }
462 /// // ... process item i ...
463 /// }
464 /// Ok(McpContent::text("done"))
465 /// });
466 /// ```
467 pub fn is_cancelled(&self) -> bool {
468 self.cancellation.as_ref().is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed))
469 }
470
471 /// **Deprecated by MCP 2026-07-28** (SEP-2577): Sampling keeps working with
472 /// clients that use it, for at least twelve months, but new servers shouldn't
473 /// rely on it.
474 ///
475 /// Ask the connected client to run LLM inference ("sampling") and block
476 /// until it replies or `timeout` elapses — the server-initiated half of
477 /// `sampling/createMessage`. This reverses the usual request direction:
478 /// the server sends a JSON-RPC *request* to the client over the `GET
479 /// /mcp` SSE stream, and the client answers with its own `POST /mcp`
480 /// carrying a JSON-RPC *response* (no `method`) that
481 /// [`McpServer::handle_request_with_context`] recognizes and routes
482 /// back here instead of treating it as an invalid request.
483 ///
484 /// Blocking (not `async fn`) is deliberate: tool handlers in this crate
485 /// are plain synchronous closures — there is no async tool handler
486 /// support yet (MCP_TODO.md's TODO-17) for this to `.await` inside of.
487 /// The calling thread parks on the response channel for up to
488 /// `timeout`; on a thread-pool server this ties up one worker for that
489 /// long, same tradeoff `crate::timeout::with_timeout` already accepts
490 /// for bounding a slow handler's *caller*.
491 ///
492 /// Fails fast, before sending anything, if: the client's `initialize`
493 /// call never declared `capabilities.sampling` (it wouldn't know what
494 /// to do with the request); this request has no session id (nothing to
495 /// address the request to); or `ctx` has no live server behind it.
496 /// Otherwise the request goes out on the session's `GET /mcp` SSE stream
497 /// — waited for, within `timeout`, if the client hasn't opened it yet
498 /// (clients often call a tool right after `initialize`, before their
499 /// stream is up) — and it fails with a timeout error if the stream never
500 /// opens or the client never responds.
501 ///
502 /// ```rust,no_run
503 /// use rust_web_server::mcp::{McpServer, PromptMessage, SamplingRequest};
504 /// use std::time::Duration;
505 ///
506 /// let server = McpServer::new("my-server", "1.0")
507 /// .tool_with_context("ask_llm", "Ask the connected client's model a question", "{}", |ctx, _args| {
508 /// let response = ctx.sample(
509 /// SamplingRequest {
510 /// messages: vec![PromptMessage::user("What is 2+2?")],
511 /// max_tokens: 100,
512 /// system_prompt: None,
513 /// },
514 /// Duration::from_secs(30),
515 /// )?;
516 /// Ok(response.content)
517 /// });
518 /// ```
519 pub fn sample(&self, request: SamplingRequest, timeout: Duration) -> Result<SamplingResponse, String> {
520 if !self.sampling_supported {
521 return Err("the connected client did not declare sampling support in its initialize capabilities".to_string());
522 }
523
524 let messages_json: Vec<String> = request.messages.iter().map(|m| m.to_json()).collect();
525 let system_prompt_field = match &request.system_prompt {
526 Some(s) => format!(r#","systemPrompt":"{}""#, json_escape(s)),
527 None => String::new(),
528 };
529 let params = format!(
530 r#"{{"messages":[{}],"maxTokens":{}{system_prompt_field}}}"#,
531 messages_json.join(","), request.max_tokens,
532 );
533
534 let result_json = self.send_and_wait("sampling/createMessage", Some(¶ms), timeout)?;
535 parse_sampling_response(&result_json)
536 }
537
538 /// **Deprecated by MCP 2026-07-28** (SEP-2577): Roots keeps working with
539 /// clients that use it, for at least twelve months, but new servers shouldn't
540 /// rely on it.
541 ///
542 /// Ask the connected client which filesystem roots (workspace
543 /// directories, mounted volumes, ...) it has access to — useful for a
544 /// file-system-aware tool that should only operate within the client's
545 /// declared workspace rather than the whole filesystem.
546 ///
547 /// Like [`Self::sample`], this reverses the usual request direction (a
548 /// server-initiated `roots/list` request over SSE, answered by the
549 /// client's own `POST /mcp`) and blocks the calling thread for up to
550 /// `timeout` — see `sample`'s docs for why blocking is deliberate here.
551 ///
552 /// The result is cached per session: the first call after `initialize`
553 /// (or after the client sends `notifications/roots/list_changed`, which
554 /// invalidates the cache) does a live round trip; later calls in the
555 /// same session return the cached list without sending anything. A tool
556 /// handler can call this on every invocation without worrying about
557 /// spamming the client with redundant `roots/list` requests.
558 ///
559 /// Fails fast, before sending anything, under the same conditions as
560 /// [`Self::sample`] (translated to roots): the client never declared
561 /// `capabilities.roots`, this request has no session id, or `ctx` has
562 /// no live server behind it.
563 ///
564 /// ```rust,no_run
565 /// use rust_web_server::mcp::McpServer;
566 /// use std::time::Duration;
567 ///
568 /// let server = McpServer::new("my-server", "1.0")
569 /// .tool_with_context("list_workspace_files", "List files in the client's workspace", "{}", |ctx, _args| {
570 /// let roots = ctx.list_roots(Duration::from_secs(10))?;
571 /// let names: Vec<String> = roots.iter().map(|r| r.uri.clone()).collect();
572 /// Ok(rust_web_server::mcp::McpContent::text(names.join(", ")))
573 /// });
574 /// ```
575 pub fn list_roots(&self, timeout: Duration) -> Result<Vec<McpRoot>, String> {
576 if !self.roots_supported {
577 return Err("the connected client did not declare roots support in its initialize capabilities".to_string());
578 }
579
580 if let (Some(session_id), Some(sessions)) = (&self.session_id, &self.sessions) {
581 if let Some(cached) = sessions.lock().unwrap().get(session_id).and_then(|info| info.roots.clone()) {
582 return Ok(cached);
583 }
584 }
585
586 let result_json = self.send_and_wait("roots/list", None, timeout)?;
587 let roots = parse_roots_response(&result_json)?;
588
589 if let (Some(session_id), Some(sessions)) = (&self.session_id, &self.sessions) {
590 if let Some(info) = sessions.lock().unwrap().get_mut(session_id) {
591 info.roots = Some(roots.clone());
592 }
593 }
594
595 Ok(roots)
596 }
597
598 /// Send a JSON-RPC request to the client for this context's session and
599 /// block for the reply — the shared send-and-correlate mechanic behind
600 /// [`Self::sample`] and [`Self::list_roots`]. Returns the raw `result`
601 /// JSON string (not yet parsed into either method's own response type)
602 /// on success.
603 fn send_and_wait(&self, method: &str, params_json: Option<&str>, timeout: Duration) -> Result<String, String> {
604 let session_id = self.session_id.clone()
605 .ok_or_else(|| format!("{method} requires a session (Mcp-Session-Id)"))?;
606 let sse_clients = self.sse_clients.as_ref()
607 .ok_or_else(|| format!("{method} requires a live server (this context has none)"))?;
608 let pending = self.pending_replies.as_ref()
609 .ok_or_else(|| format!("{method} requires a live server (this context has none)"))?;
610
611 let request_id = format!("\"{}\"", crate::request_id::generate_request_id());
612 let (tx, rx) = mpsc::channel::<Result<String, String>>();
613 pending.lock().unwrap().insert(request_id.clone(), tx);
614
615 let params_field = match params_json {
616 Some(p) => format!(r#","params":{p}"#),
617 None => String::new(),
618 };
619 let rpc = format!(r#"{{"jsonrpc":"2.0","id":{request_id},"method":"{method}"{params_field}}}"#);
620
621 // A client may call a tool before its `GET /mcp` stream is open (the
622 // SDK clients open it in the background after `initialize`): wait for
623 // the stream, within the same timeout, instead of sending into nothing.
624 let deadline = std::time::Instant::now() + timeout;
625 let outcome = loop {
626 if send_sse_to_sessions(sse_clients, std::slice::from_ref(&session_id), &rpc) > 0 {
627 break rx.recv_timeout(deadline.saturating_duration_since(std::time::Instant::now()))
628 .map_err(|_| format!("{method} timed out waiting for the client's response"));
629 }
630 let left = deadline.saturating_duration_since(std::time::Instant::now());
631 if left.is_zero() {
632 break Err(format!("{method} timed out: the client has no GET /mcp stream open for this session"));
633 }
634 std::thread::sleep(left.min(SSE_STREAM_WAIT_POLL));
635 };
636 pending.lock().unwrap().remove(&request_id);
637
638 outcome.and_then(|reply| reply)
639 }
640}
641
642/// A request to ask the connected MCP client to run LLM inference
643/// ("sampling") — build one and pass it to [`McpContext::sample`].
644///
645/// `messages` reuses [`PromptMessage`] rather than introducing a near-identical
646/// type — the spec's sampling message shape (`{"role":...,"content":{"type":"text",...}}`)
647/// is exactly what `PromptMessage` already models.
648pub struct SamplingRequest {
649 pub messages: Vec<PromptMessage>,
650 pub max_tokens: u32,
651 /// An optional system prompt to steer the client's model, per the
652 /// spec's `params.systemPrompt`.
653 pub system_prompt: Option<String>,
654}
655
656/// The client's answer to a [`SamplingRequest`], returned by
657/// [`McpContext::sample`].
658pub struct SamplingResponse {
659 /// Almost always `"assistant"`, per spec.
660 pub role: String,
661 pub content: McpContent,
662 /// The model the client actually used to generate this response, e.g.
663 /// `"claude-3-sonnet-20240307"`.
664 pub model: String,
665 /// Why the model stopped, e.g. `"endTurn"`, `"maxTokens"`, `"stopSequence"`.
666 /// `None` if the client didn't report one.
667 pub stop_reason: Option<String>,
668}
669
670/// Parse a `sampling/createMessage` response's `result` object (already
671/// extracted from the enclosing JSON-RPC envelope) into a [`SamplingResponse`].
672fn parse_sampling_response(result_json: &str) -> Result<SamplingResponse, String> {
673 let role = json_rpc::extract_str(result_json, "role").unwrap_or_else(|| "assistant".to_string());
674 let content_json = json_rpc::extract_raw(result_json, "content")
675 .ok_or_else(|| "sampling response missing content".to_string())?;
676 let kind = json_rpc::extract_str(&content_json, "type").unwrap_or_else(|| "text".to_string());
677 let content = match kind.as_str() {
678 "image" => McpContent::image(
679 json_rpc::extract_str(&content_json, "data").unwrap_or_default(),
680 json_rpc::extract_str(&content_json, "mimeType").unwrap_or_default(),
681 ),
682 _ => McpContent::text(json_rpc::extract_str(&content_json, "text").unwrap_or_default()),
683 };
684 let model = json_rpc::extract_str(result_json, "model").unwrap_or_default();
685 let stop_reason = json_rpc::extract_str(result_json, "stopReason");
686 Ok(SamplingResponse { role, content, model, stop_reason })
687}
688
689/// One filesystem root a client has access to, returned by
690/// [`McpContext::list_roots`] — a workspace directory, a mounted volume,
691/// or similar. `uri` is typically a `file://` URI per spec.
692#[derive(Debug, Clone)]
693pub struct McpRoot {
694 pub uri: String,
695 /// A human-readable label for the root, if the client provided one.
696 pub name: Option<String>,
697}
698
699/// Parse a `roots/list` response's `result` object (already extracted from
700/// the enclosing JSON-RPC envelope) into a `Vec<McpRoot>`.
701fn parse_roots_response(result_json: &str) -> Result<Vec<McpRoot>, String> {
702 let roots_array = json_rpc::extract_raw(result_json, "roots")
703 .ok_or_else(|| "roots/list response missing roots".to_string())?;
704 let roots = json_rpc::split_array_elements(&roots_array).iter().map(|elem| {
705 McpRoot {
706 uri: json_rpc::extract_str(elem, "uri").unwrap_or_default(),
707 name: json_rpc::extract_str(elem, "name"),
708 }
709 }).collect();
710 Ok(roots)
711}
712
713/// Configuration installed by [`McpServer::require_oauth`] (`sso` feature).
714/// Reuses [`crate::sso::jwks::JwksCache`] and [`crate::sso::OidcProvider`]
715/// directly rather than re-implementing JWKS fetch/verify — see
716/// `require_oauth`'s doc comment for the full rationale.
717#[cfg(feature = "sso")]
718struct OAuthConfig {
719 jwks: crate::sso::jwks::JwksCache,
720 provider: crate::sso::OidcProvider,
721 audience: String,
722}
723
724/// `clientInfo` recorded for one session at `initialize` time, looked up by
725/// `Mcp-Session-Id` for later requests in the same session. See
726/// `McpServer`'s `sessions` field doc comment for the unbounded-growth caveat.
727#[derive(Debug, Clone)]
728struct StoredClientInfo {
729 /// Last request in this session; idle past the server's session TTL, the
730 /// session is evicted (#4).
731 last_seen: std::time::Instant,
732 /// The protocol version `initialize` settled on.
733 protocol_version: &'static str,
734 name: Option<String>,
735 version: Option<String>,
736 /// Whether this session's `initialize` call declared `params.capabilities.sampling`
737 /// (spec: the client, not the server, declares sampling support — the
738 /// presence of the key is what matters, not its contents, which are
739 /// normally an empty object). Checked by [`McpContext::sample`] before
740 /// sending a `sampling/createMessage` request that the client would
741 /// have no idea how to answer.
742 supports_sampling: bool,
743 /// Whether this session's `initialize` call declared `params.capabilities.roots`,
744 /// checked by [`McpContext::list_roots`] the same way `supports_sampling` gates `sample`.
745 supports_roots: bool,
746 /// Cached result of this session's last `roots/list` round trip, read
747 /// and written by [`McpContext::list_roots`]. `None` means "never
748 /// fetched, or invalidated" — set back to `None` when this session
749 /// sends `notifications/roots/list_changed`, so the next `list_roots`
750 /// call does a fresh round trip instead of serving stale data.
751 roots: Option<Vec<McpRoot>>,
752}
753
754// ── ToolAnnotations ───────────────────────────────────────────────────────────
755
756/// Behavioral hints for a tool, per the MCP 2025-03-26 spec's tool
757/// annotations. Clients (Claude Desktop and others) use these to decide
758/// whether to warn or ask for confirmation before calling a tool — e.g. skip
759/// confirmation for a read-only tool, or warn before a destructive one.
760///
761/// Every field is a *hint*, not something this server enforces or verifies —
762/// nothing stops a handler registered with `read_only_hint: Some(true)` from
763/// actually writing to disk. A well-behaved server sets these accurately;
764/// a client is free to ignore them or ask for confirmation anyway.
765///
766/// Register with [`McpServer::tool_annotated`]. Build one with plain struct
767/// syntax — every field defaults to `None` (no hint given, the client's own
768/// default applies):
769///
770/// ```rust
771/// use rust_web_server::mcp::ToolAnnotations;
772///
773/// let destructive = ToolAnnotations {
774/// destructive_hint: Some(true),
775/// read_only_hint: Some(false),
776/// ..Default::default()
777/// };
778/// ```
779#[derive(Debug, Clone, Copy, Default)]
780pub struct ToolAnnotations {
781 /// The tool does not modify its environment.
782 pub read_only_hint: Option<bool>,
783 /// The tool may perform destructive updates (only meaningful when
784 /// `read_only_hint` is not `Some(true)`).
785 pub destructive_hint: Option<bool>,
786 /// Calling the tool repeatedly with the same arguments has no additional
787 /// effect beyond the first call.
788 pub idempotent_hint: Option<bool>,
789 /// The tool may interact with an open-ended set of external entities
790 /// (e.g. web search), as opposed to a fixed, closed set.
791 pub open_world_hint: Option<bool>,
792}
793
794impl ToolAnnotations {
795 /// Render as a JSON object containing only the hints that are `Some`,
796 /// using the spec's camelCase key names. Returns `"{}"` if every field
797 /// is `None`.
798 fn to_json(self) -> String {
799 let mut fields = Vec::with_capacity(4);
800 if let Some(v) = self.read_only_hint {
801 fields.push(format!(r#""readOnlyHint":{v}"#));
802 }
803 if let Some(v) = self.destructive_hint {
804 fields.push(format!(r#""destructiveHint":{v}"#));
805 }
806 if let Some(v) = self.idempotent_hint {
807 fields.push(format!(r#""idempotentHint":{v}"#));
808 }
809 if let Some(v) = self.open_world_hint {
810 fields.push(format!(r#""openWorldHint":{v}"#));
811 }
812 format!("{{{}}}", fields.join(","))
813 }
814}
815
816// ── LogLevel ──────────────────────────────────────────────────────────────────
817
818/// RFC 5424 syslog severity levels, as used by the MCP `logging/setLevel`
819/// request and `notifications/message` log entries — ordered from most to
820/// least verbose so `level < min_level` comparisons work directly (this
821/// relies on declaration order matching severity order; don't reorder the
822/// variants).
823///
824/// ```rust
825/// use rust_web_server::mcp::LogLevel;
826///
827/// assert!(LogLevel::Debug < LogLevel::Warning);
828/// assert!(LogLevel::Emergency > LogLevel::Error);
829/// assert_eq!(LogLevel::parse("warning"), Some(LogLevel::Warning));
830/// assert_eq!(LogLevel::Warning.as_str(), "warning");
831/// ```
832#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
833pub enum LogLevel {
834 Debug,
835 Info,
836 Notice,
837 Warning,
838 Error,
839 Critical,
840 Alert,
841 Emergency,
842}
843
844impl LogLevel {
845 /// Parse the MCP spec's lowercase level name. Returns `None` for
846 /// anything that isn't one of the eight recognized levels.
847 pub fn parse(s: &str) -> Option<Self> {
848 match s {
849 "debug" => Some(LogLevel::Debug),
850 "info" => Some(LogLevel::Info),
851 "notice" => Some(LogLevel::Notice),
852 "warning" => Some(LogLevel::Warning),
853 "error" => Some(LogLevel::Error),
854 "critical" => Some(LogLevel::Critical),
855 "alert" => Some(LogLevel::Alert),
856 "emergency" => Some(LogLevel::Emergency),
857 _ => None,
858 }
859 }
860
861 /// The MCP spec's lowercase level name, e.g. `"warning"`.
862 pub fn as_str(self) -> &'static str {
863 match self {
864 LogLevel::Debug => "debug",
865 LogLevel::Info => "info",
866 LogLevel::Notice => "notice",
867 LogLevel::Warning => "warning",
868 LogLevel::Error => "error",
869 LogLevel::Critical => "critical",
870 LogLevel::Alert => "alert",
871 LogLevel::Emergency => "emergency",
872 }
873 }
874}
875
876// ── internal handler registrations ───────────────────────────────────────────
877
878type ToolFn = Arc<dyn Fn(McpContext, &str) -> Result<McpContent, String> + Send + Sync>;
879type ResourceFn = Arc<dyn Fn(&str) -> Result<McpContent, String> + Send + Sync>;
880type PromptFn = Arc<dyn Fn(McpContext, &str) -> Result<PromptReply, String> + Send + Sync>;
881/// `Fn(argument_name, partial_value) -> candidate completion strings`.
882type CompletionFn = Arc<dyn Fn(&str, &str) -> Result<Vec<String>, String> + Send + Sync>;
883type ToolFilter = Arc<dyn Fn(&McpContext, &str) -> bool + Send + Sync>;
884/// An async tool handler, boxed so `AsyncToolDef` can store handlers with
885/// different concrete `Future` types uniformly. The `Future` itself doesn't
886/// need `Send` for [`crate::async_bridge::block_on_isolated`] (which drives
887/// it to completion without ever moving it across a thread boundary), but
888/// it's required here anyway for consistency with [`crate::async_state`]'s
889/// equivalent handler type — the common case in practice, and one less
890/// surprise for anyone switching between the two async handler styles.
891#[cfg(feature = "http2")]
892type AsyncToolFn = Arc<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<McpContent, String>> + Send>> + Send + Sync>;
893
894#[derive(Clone)]
895struct ToolDef {
896 name: String,
897 description: String,
898 input_schema: String,
899 annotations: Option<ToolAnnotations>,
900 meta: ToolMeta,
901 handler: ToolFn,
902}
903
904/// Optional `tools/list` fields set after registration, by tool name:
905/// [`McpServer::tool_title`], [`McpServer::tool_icon`],
906/// [`McpServer::tool_output_schema`].
907#[derive(Clone, Default)]
908struct ToolMeta {
909 title: Option<String>,
910 icons: Vec<McpIcon>,
911 output_schema: Option<String>,
912}
913
914/// An icon for the server, a tool, a resource or a prompt (MCP 2025-11-25):
915/// `src` is an `https:` or `data:` URL.
916#[derive(Clone, Debug, PartialEq, Eq)]
917pub struct McpIcon {
918 pub src: String,
919 pub mime_type: Option<String>,
920 /// e.g. `["48x48"]`, `["any"]` for SVG.
921 pub sizes: Vec<String>,
922}
923
924impl McpIcon {
925 /// An icon at `src`, with no MIME type or sizes.
926 pub fn new(src: impl Into<String>) -> Self {
927 McpIcon { src: src.into(), mime_type: None, sizes: Vec::new() }
928 }
929
930 /// Set the MIME type (`image/png`, `image/svg+xml`, …).
931 pub fn mime_type(mut self, mime_type: impl Into<String>) -> Self {
932 self.mime_type = Some(mime_type.into());
933 self
934 }
935
936 /// Add a size (`48x48`, or `any` for scalable formats).
937 pub fn size(mut self, size: impl Into<String>) -> Self {
938 self.sizes.push(size.into());
939 self
940 }
941
942 fn to_json(&self) -> String {
943 let mut out = format!(r#"{{"src":"{}""#, json_escape(&self.src));
944 if let Some(mime) = &self.mime_type {
945 out.push_str(&format!(r#","mimeType":"{}""#, json_escape(mime)));
946 }
947 if !self.sizes.is_empty() {
948 let sizes: Vec<String> = self.sizes.iter().map(|s| format!(r#""{}""#, json_escape(s))).collect();
949 out.push_str(&format!(r#","sizes":[{}]"#, sizes.join(",")));
950 }
951 out.push('}');
952 out
953 }
954}
955
956fn icons_json(icons: &[McpIcon]) -> String {
957 if icons.is_empty() {
958 return String::new();
959 }
960 let icons: Vec<String> = icons.iter().map(McpIcon::to_json).collect();
961 format!(r#","icons":[{}]"#, icons.join(","))
962}
963
964/// A tool registered via [`McpServer::async_tool`]/[`McpServer::register_async_tool`]
965/// — stored separately from [`ToolDef`] rather than unifying the two behind
966/// a handler enum, since sync and async tools are otherwise identical and
967/// keeping them apart touches far less of the existing (already
968/// substantial) tool-handling code. `tools/list` and `tools/call` merge
969/// both collections transparently; from the client's perspective there is
970/// no distinction.
971#[cfg(feature = "http2")]
972#[derive(Clone)]
973struct AsyncToolDef {
974 name: String,
975 description: String,
976 input_schema: String,
977 annotations: Option<ToolAnnotations>,
978 meta: ToolMeta,
979 handler: AsyncToolFn,
980}
981
982#[derive(Clone)]
983struct ResourceDef {
984 uri_template: String,
985 name: String,
986 description: String,
987 handler: ResourceFn,
988}
989
990#[derive(Clone)]
991struct PromptDef {
992 name: String,
993 description: String,
994 arguments: Vec<PromptArgDef>,
995 handler: PromptFn,
996}
997
998/// One `.completion()` registration — completion candidates for a single
999/// named argument of a single tool or prompt. `ref_type` is the short form
1000/// passed to `.completion()` (e.g. `"tool"`, `"prompt"`), matched against the
1001/// request's `ref.type` (e.g. `"ref/tool"`) with the `"ref/"` prefix
1002/// stripped, not the raw wire value.
1003#[derive(Clone)]
1004struct CompletionDef {
1005 ref_type: String,
1006 ref_name: String,
1007 handler: CompletionFn,
1008}
1009
1010// ── McpServer ─────────────────────────────────────────────────────────────────
1011
1012/// An HTTP server that implements the MCP protocol (2024-11-05 to 2025-11-25).
1013///
1014/// Register tools, resources, and prompts with the builder methods, then pass
1015/// the server to [`Server::run`] (or [`Server::run_tls`]) as an [`Application`].
1016/// Requests that do not match the MCP endpoint fall through to the built-in
1017/// [`App`] controller chain.
1018#[derive(Clone)]
1019pub struct McpServer {
1020 server_name: String,
1021 server_version: String,
1022 path: String,
1023 /// `Arc<RwLock<_>>` (not a plain `Vec`) so a running server's tool list
1024 /// can be mutated at runtime — see [`Self::register_tool`]/[`Self::remove_tool`]
1025 /// — and every clone of this `McpServer` (each connection thread gets
1026 /// one) sees the same live list.
1027 tools: Arc<RwLock<Vec<ToolDef>>>,
1028 /// Tools registered via [`Self::async_tool`]/[`Self::register_async_tool`],
1029 /// bridged into synchronous [`Application::execute`] via
1030 /// [`crate::async_bridge::block_on_isolated`] at call time. Kept
1031 /// separate from `tools` rather than merged into one collection — see
1032 /// [`AsyncToolDef`]'s doc comment.
1033 #[cfg(feature = "http2")]
1034 async_tools: Arc<RwLock<Vec<AsyncToolDef>>>,
1035 resources: Arc<RwLock<Vec<ResourceDef>>>,
1036 prompts: Arc<RwLock<Vec<PromptDef>>>,
1037 /// Argument completion providers registered via [`Self::completion`].
1038 /// `initialize` advertises the `completions` capability iff this is
1039 /// non-empty at that moment.
1040 completions: Arc<RwLock<Vec<CompletionDef>>>,
1041 fallback: Option<Arc<dyn Application + Send + Sync>>,
1042 auth_token: Option<String>,
1043 /// `(token, identity)` pairs from [`Self::require_bearer_tokens`].
1044 bearer_tokens: Vec<(String, String)>,
1045 /// Which tools a caller may see and call ([`Self::tool_filter`]).
1046 tool_filter: Option<ToolFilter>,
1047 /// Origins a browser may call the endpoint from (see
1048 /// [`Self::allowed_origins`]); a request with any other `Origin` is
1049 /// refused.
1050 allowed_origins: Vec<String>,
1051 /// Installed by [`Self::require_oauth`] (`sso` feature) — an alternative
1052 /// to `auth_token` that verifies a client-supplied OAuth 2.0 / OIDC
1053 /// bearer JWT via JWKS instead of comparing against one static shared
1054 /// secret. If both are somehow configured, OAuth verification takes
1055 /// precedence and `auth_token` is ignored (see [`Self::require_oauth`]).
1056 #[cfg(feature = "sso")]
1057 oauth: Option<Arc<OAuthConfig>>,
1058 /// Max items per page for `tools/list`/`resources/list`/`prompts/list`,
1059 /// set via [`Self::page_size`]. `None` (the default) means no pagination
1060 /// — every item comes back in one response, same as before pagination
1061 /// existed.
1062 page_size: Option<usize>,
1063 /// `clientInfo` recorded per `Mcp-Session-Id`, minted at `initialize` time.
1064 /// `Arc<Mutex<_>>` so every clone of this `McpServer` shares one map.
1065 /// Bounded (#4): a session idle for `session_ttl` is evicted when next
1066 /// seen or when a new one is created, `max_sessions` caps the map
1067 /// (oldest evicted first), and `DELETE /mcp` ends one. An evicted
1068 /// session's subscriptions and SSE streams go with it.
1069 sessions: Arc<Mutex<HashMap<String, StoredClientInfo>>>,
1070 /// Idle time after which a session is evicted (default 1 hour).
1071 session_ttl: Duration,
1072 /// Most sessions kept (default 10 000).
1073 max_sessions: usize,
1074 /// Most open `GET /mcp` SSE streams (default 1000); past it `503`.
1075 max_sse_clients: usize,
1076 /// `serverInfo.title` and `serverInfo.icons`.
1077 server_title: Option<String>,
1078 server_icons: Vec<McpIcon>,
1079 /// Senders for every currently-connected `GET /mcp` SSE client, pushed to
1080 /// by [`Self::notify`]. `Arc<Mutex<_>>` so every clone of this `McpServer`
1081 /// broadcasts to the same set of listeners.
1082 ///
1083 /// Entries for clients that disconnected (or whose buffer filled up) are
1084 /// only pruned lazily, the next time [`Self::notify`] is called and its
1085 /// `try_send` fails — not proactively, since nothing else observes the
1086 /// underlying `Receiver` closing. A server that never calls `notify`
1087 /// after clients disconnect will accumulate dead entries here.
1088 sse_clients: Arc<Mutex<Vec<SseClient>>>,
1089 /// Whether `initialize`'s advertised `capabilities` includes `"logging":{}`.
1090 /// Set via [`Self::logging_enabled`]. This only controls what's
1091 /// advertised — [`Self::log`] works regardless, same as [`Self::notify`]
1092 /// does; a spec-honest client just wouldn't call `logging/setLevel` in
1093 /// the first place if the capability was never advertised.
1094 logging_enabled: bool,
1095 /// The minimum [`LogLevel`] that [`Self::log`] will actually push,
1096 /// settable at runtime by a client's `logging/setLevel` request. Starts
1097 /// at [`LogLevel::Debug`] (the least restrictive level, i.e. nothing is
1098 /// filtered) until a client requests otherwise.
1099 min_log_level: Arc<Mutex<LogLevel>>,
1100 /// In-flight `tools/call` cancellation flags, keyed by the request's raw
1101 /// `id` JSON token. Populated just before dispatching a `tools/call` and
1102 /// removed again once it returns (success, error, or the flag was never
1103 /// checked) — unlike `sessions`/`sse_clients`, this map's entries are
1104 /// always short-lived by construction, not merely "not evicted."
1105 /// `notifications/cancelled` looks up `params.requestId` here and flips
1106 /// the flag; see [`McpContext::is_cancelled`] for how (and whether) a
1107 /// handler ever observes it.
1108 cancellations: Arc<Mutex<HashMap<String, Arc<std::sync::atomic::AtomicBool>>>>,
1109 /// Resource URI -> session ids subscribed to it via
1110 /// `resources/subscribe`, consulted by [`Self::notify_resource_updated`].
1111 /// A session id is only meaningful if the client also opened `GET /mcp`
1112 /// with the same `Mcp-Session-Id` header (see [`SseClient`]) — a session
1113 /// that only ever calls `resources/subscribe` over POST with no matching
1114 /// SSE connection is subscribed in name only, since there's no channel
1115 /// to push the update over. Entries are removed by explicit
1116 /// `resources/unsubscribe` calls (URIs with zero subscribers are pruned
1117 /// entirely); a session that disconnects without unsubscribing leaves a
1118 /// harmless stale session id behind, same "no proactive eviction"
1119 /// tradeoff already documented for `sessions`.
1120 subscriptions: Arc<Mutex<HashMap<String, Vec<String>>>>,
1121 /// In-flight `sampling/createMessage` requests this server has sent to
1122 /// a client, keyed by the raw (already-quoted) request id token this
1123 /// server minted. A JSON-RPC *response* has no `method` field, so
1124 /// [`Self::handle_request_with_context`]/[`Self::handle_batch`]
1125 /// special-case a method-less body with a recognized `id` as a
1126 /// sampling reply (via [`Self::try_deliver_sampling_response`]) rather
1127 /// than an invalid request. See [`McpContext::sample`] for the
1128 /// send-and-block side.
1129 pending_replies: Arc<Mutex<HashMap<String, mpsc::Sender<Result<String, String>>>>>,
1130 /// Open `subscriptions/listen` streams (MCP 2026-07-28).
1131 listeners: Arc<Mutex<Vec<modern::Listener>>>,
1132 /// The HMAC key protecting `requestState` ([`Self::request_state_key`]).
1133 state_key: Arc<Vec<u8>>,
1134 /// `ttlMs` / `cacheScope` on cacheable results ([`Self::cache_hints`]).
1135 cache_ttl_ms: u64,
1136 cache_scope: &'static str,
1137 /// Tasks started by tools (MCP Tasks extension).
1138 task_store: Arc<tasks::TaskStore>,
1139 task_ttl_ms: u64,
1140 /// Tasks whose work is still running, and the cap
1141 /// ([`Self::max_running_tasks`]).
1142 running_tasks: Arc<std::sync::atomic::AtomicUsize>,
1143 max_running_tasks: usize,
1144 /// Tools usable only as tasks ([`Self::task_required`]).
1145 task_required_tools: Arc<RwLock<Vec<String>>>,
1146}
1147
1148/// One `GET /mcp` SSE client: its outbound channel plus the
1149/// `Mcp-Session-Id` it connected with, if any. Broadcast notifications
1150/// (`.notify()`, `.log()`, `list_changed`) go to every client regardless of
1151/// `session_id`; [`McpServer::notify_resource_updated`] targets only
1152/// clients whose `session_id` is subscribed to the changed URI.
1153#[derive(Debug)]
1154struct SseClient {
1155 session_id: Option<String>,
1156 sender: SseSender,
1157}
1158
1159/// One `GET /mcp` SSE client's outbound channel. Bounded so a slow or stuck
1160/// client can't grow memory without limit; [`McpServer::notify`] uses
1161/// `try_send` (never blocks) and drops any client whose buffer is full.
1162type SseSender = SyncSender<Vec<u8>>;
1163
1164/// Max buffered-but-unread SSE frames per client before it's treated as dead.
1165const SSE_CHANNEL_CAPACITY: usize = 32;
1166
1167/// Default idle time after which an MCP session is evicted.
1168pub const DEFAULT_SESSION_TTL: Duration = Duration::from_secs(3600);
1169/// Default cap on MCP sessions.
1170pub const DEFAULT_MAX_SESSIONS: usize = 10_000;
1171/// Default cap on open `GET /mcp` SSE streams.
1172pub const DEFAULT_MAX_SSE_CLIENTS: usize = 1000;
1173
1174/// How often an idle SSE connection gets a `: keep-alive` comment.
1175const SSE_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
1176
1177/// Max `completion/complete` values returned in one response, per spec
1178/// guidance that servers SHOULD NOT return more than 100. A handler
1179/// returning more has the rest reported via `hasMore`/`total` rather than
1180/// silently included.
1181const MAX_COMPLETION_VALUES: usize = 100;
1182
1183impl McpServer {
1184 /// Create a new `McpServer`. The default MCP endpoint is `POST /mcp`.
1185 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
1186 McpServer {
1187 server_name: name.into(),
1188 server_version: version.into(),
1189 path: "/mcp".to_string(),
1190 tools: Arc::new(RwLock::new(Vec::new())),
1191 #[cfg(feature = "http2")]
1192 async_tools: Arc::new(RwLock::new(Vec::new())),
1193 resources: Arc::new(RwLock::new(Vec::new())),
1194 prompts: Arc::new(RwLock::new(Vec::new())),
1195 completions: Arc::new(RwLock::new(Vec::new())),
1196 fallback: None,
1197 auth_token: None,
1198 bearer_tokens: Vec::new(),
1199 tool_filter: None,
1200 allowed_origins: Vec::new(),
1201 #[cfg(feature = "sso")]
1202 oauth: None,
1203 page_size: None,
1204 sessions: Arc::new(Mutex::new(HashMap::new())),
1205 session_ttl: DEFAULT_SESSION_TTL,
1206 max_sessions: DEFAULT_MAX_SESSIONS,
1207 max_sse_clients: DEFAULT_MAX_SSE_CLIENTS,
1208 server_title: None,
1209 server_icons: Vec::new(),
1210 sse_clients: Arc::new(Mutex::new(Vec::new())),
1211 logging_enabled: false,
1212 min_log_level: Arc::new(Mutex::new(LogLevel::Debug)),
1213 cancellations: Arc::new(Mutex::new(HashMap::new())),
1214 subscriptions: Arc::new(Mutex::new(HashMap::new())),
1215 pending_replies: Arc::new(Mutex::new(HashMap::new())),
1216 listeners: Arc::new(Mutex::new(Vec::new())),
1217 state_key: Arc::new(modern::random_key()),
1218 cache_ttl_ms: 0,
1219 cache_scope: "private",
1220 task_store: Arc::new(tasks::TaskStore::default()),
1221 task_ttl_ms: 3_600_000,
1222 running_tasks: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
1223 max_running_tasks: tasks::DEFAULT_MAX_RUNNING_TASKS,
1224 task_required_tools: Arc::new(RwLock::new(Vec::new())),
1225 }
1226 }
1227
1228 /// Evict a session after it has been idle this long (default 1 hour,
1229 /// [`DEFAULT_SESSION_TTL`]). A request with an evicted session's
1230 /// `Mcp-Session-Id` gets `404`, which tells the client to initialize a
1231 /// new session (MCP Streamable HTTP transport).
1232 pub fn session_ttl(mut self, ttl: Duration) -> Self {
1233 self.session_ttl = ttl;
1234 self
1235 }
1236
1237 /// Keep at most `n` sessions (default [`DEFAULT_MAX_SESSIONS`]); a new
1238 /// one past that evicts the least recently used.
1239 pub fn max_sessions(mut self, n: usize) -> Self {
1240 self.max_sessions = n.max(1);
1241 self
1242 }
1243
1244 /// Accept at most `n` open `GET /mcp` SSE streams (default
1245 /// [`DEFAULT_MAX_SSE_CLIENTS`]); another gets `503 Service Unavailable`.
1246 pub fn max_sse_clients(mut self, n: usize) -> Self {
1247 self.max_sse_clients = n;
1248 self
1249 }
1250
1251 /// A human-readable title for tool `name` (`title` in `tools/list`,
1252 /// MCP 2025-06-18); `name` stays the identifier. No effect for an
1253 /// unknown name — register the tool first.
1254 pub fn tool_title(self, name: &str, title: impl Into<String>) -> Self {
1255 let title = title.into();
1256 self.with_tool_meta(name, |meta| meta.title = Some(title.clone()));
1257 self
1258 }
1259
1260 /// Add an icon to tool `name` (`icons` in `tools/list`, MCP 2025-11-25).
1261 pub fn tool_icon(self, name: &str, icon: McpIcon) -> Self {
1262 self.with_tool_meta(name, |meta| meta.icons.push(icon.clone()));
1263 self
1264 }
1265
1266 /// Declare tool `name`'s result shape: a JSON Schema object (an `object`
1267 /// type at the top). Clients may validate the `structuredContent` the
1268 /// handler returns with [`McpContent::structured`] against it.
1269 pub fn tool_output_schema(self, name: &str, schema: &str) -> Self {
1270 let schema = schema.to_string();
1271 self.with_tool_meta(name, |meta| meta.output_schema = Some(schema.clone()));
1272 self
1273 }
1274
1275 /// Set (or replace) the behaviour hints of tool `name` — e.g. read-only,
1276 /// or destructive — for a tool registered without them.
1277 pub fn tool_annotations(self, name: &str, annotations: ToolAnnotations) -> Self {
1278 for tool in self.tools.write().unwrap().iter_mut().filter(|t| t.name == name) {
1279 tool.annotations = Some(annotations.clone());
1280 }
1281 #[cfg(feature = "http2")]
1282 for tool in self.async_tools.write().unwrap().iter_mut().filter(|t| t.name == name) {
1283 tool.annotations = Some(annotations.clone());
1284 }
1285 self
1286 }
1287
1288 fn with_tool_meta(&self, name: &str, mut change: impl FnMut(&mut ToolMeta)) {
1289 for tool in self.tools.write().unwrap().iter_mut().filter(|t| t.name == name) {
1290 change(&mut tool.meta);
1291 }
1292 #[cfg(feature = "http2")]
1293 for tool in self.async_tools.write().unwrap().iter_mut().filter(|t| t.name == name) {
1294 change(&mut tool.meta);
1295 }
1296 }
1297
1298 /// A human-readable server title (`serverInfo.title`, MCP 2025-06-18).
1299 pub fn title(mut self, title: impl Into<String>) -> Self {
1300 self.server_title = Some(title.into());
1301 self
1302 }
1303
1304 /// Add a server icon (`serverInfo.icons`, MCP 2025-11-25).
1305 pub fn icon(mut self, icon: McpIcon) -> Self {
1306 self.server_icons.push(icon);
1307 self
1308 }
1309
1310 /// Mark a session as used now. `false` when it doesn't exist or has been
1311 /// idle past the TTL (then it's evicted).
1312 fn touch_session(&self, session_id: &str) -> bool {
1313 let expired = {
1314 let mut sessions = self.sessions.lock().unwrap();
1315 match sessions.get_mut(session_id) {
1316 None => return false,
1317 Some(info) if info.last_seen.elapsed() > self.session_ttl => {
1318 sessions.remove(session_id);
1319 true
1320 }
1321 Some(info) => {
1322 info.last_seen = std::time::Instant::now();
1323 false
1324 }
1325 }
1326 };
1327 if expired {
1328 self.forget_sessions(&[session_id.to_string()]);
1329 return false;
1330 }
1331 true
1332 }
1333
1334 /// Before a new session: drop expired ones, then the least recently used
1335 /// until there's room under `max_sessions`.
1336 fn make_room_for_a_session(&self) {
1337 let evicted: Vec<String> = {
1338 let mut sessions = self.sessions.lock().unwrap();
1339 let ttl = self.session_ttl;
1340 let mut evicted: Vec<String> = sessions.iter()
1341 .filter(|(_, info)| info.last_seen.elapsed() > ttl)
1342 .map(|(id, _)| id.clone())
1343 .collect();
1344 for id in &evicted {
1345 sessions.remove(id);
1346 }
1347 if sessions.len() >= self.max_sessions {
1348 let mut by_age: Vec<(std::time::Instant, String)> =
1349 sessions.iter().map(|(id, info)| (info.last_seen, id.clone())).collect();
1350 by_age.sort();
1351 for (_, id) in by_age.into_iter().take(sessions.len() + 1 - self.max_sessions) {
1352 sessions.remove(&id);
1353 evicted.push(id);
1354 }
1355 }
1356 evicted
1357 };
1358 if !evicted.is_empty() {
1359 self.forget_sessions(&evicted);
1360 }
1361 }
1362
1363 /// The rest of an evicted or ended session: its resource subscriptions
1364 /// and its SSE streams (dropping the sender ends the stream).
1365 fn forget_sessions(&self, ids: &[String]) {
1366 let mut subscriptions = self.subscriptions.lock().unwrap();
1367 for subscribers in subscriptions.values_mut() {
1368 subscribers.retain(|sid| !ids.contains(sid));
1369 }
1370 subscriptions.retain(|_, subscribers| !subscribers.is_empty());
1371 drop(subscriptions);
1372 self.sse_clients.lock().unwrap()
1373 .retain(|client| client.session_id.as_ref().is_none_or(|sid| !ids.contains(sid)));
1374 }
1375
1376 /// Number of live sessions (for metrics and tests).
1377 pub fn session_count(&self) -> usize {
1378 self.sessions.lock().unwrap().len()
1379 }
1380
1381 /// Cap `tools/list`, `resources/list`, and `prompts/list` to at most `n`
1382 /// items per response, enabling cursor-based pagination: a response with
1383 /// more items remaining includes `"nextCursor"`, an opaque string the
1384 /// client echoes back as `params.cursor` on its next call to get the next
1385 /// page. `n` is clamped to a minimum of `1`.
1386 ///
1387 /// Without calling this, every registered tool/resource/prompt is
1388 /// returned in a single response — the default, and the only behavior
1389 /// before pagination existed.
1390 ///
1391 /// ```rust
1392 /// use rust_web_server::mcp::McpServer;
1393 ///
1394 /// let server = McpServer::new("my-server", "1.0").page_size(50);
1395 /// ```
1396 pub fn page_size(mut self, n: usize) -> Self {
1397 self.page_size = Some(n.max(1));
1398 self
1399 }
1400
1401 /// Push a JSON-RPC notification (no `id` — fire-and-forget, per the
1402 /// spec) to every client currently connected to the `GET /mcp` SSE
1403 /// stream, framed as an SSE `data:` event.
1404 ///
1405 /// `params_json`, if given, must already be a valid JSON value (usually
1406 /// an object) — it's spliced in verbatim, not escaped or re-serialized.
1407 ///
1408 /// Never blocks: a client whose event buffer is full (not reading fast
1409 /// enough) is treated the same as a disconnected one and dropped from
1410 /// the broadcast list, same as `notify` would drop it anyway.
1411 ///
1412 /// ```rust
1413 /// use rust_web_server::mcp::McpServer;
1414 ///
1415 /// let server = McpServer::new("my-server", "1.0");
1416 /// server.notify("notifications/message", Some(r#"{"level":"info","data":"hello"}"#));
1417 /// ```
1418 pub fn notify(&self, method: &str, params_json: Option<&str>) {
1419 let json = render_notification(method, params_json);
1420 broadcast_sse_to(&self.sse_clients, &json);
1421 self.deliver_to_listeners(method, params_json, None);
1422 }
1423
1424 /// Push `notifications/resources/updated` for `uri` to every session
1425 /// that called `resources/subscribe` for it — the mechanism behind
1426 /// live-updating resource panels (e.g. Claude Desktop watching a
1427 /// config file or a dashboard resource for changes). Call this from
1428 /// wherever your application actually changes the underlying data a
1429 /// resource represents (a file watcher, a webhook handler, a database
1430 /// trigger poll, ...).
1431 ///
1432 /// A no-op if nobody has subscribed to `uri` — including if every
1433 /// subscriber's `GET /mcp` SSE connection has since disconnected
1434 /// (pruned the same way [`Self::notify`] prunes dead broadcast clients,
1435 /// but the `subscriptions` bookkeeping for `uri` itself is untouched
1436 /// either way; only [`Self::do_resource_unsubscribe`] removes that).
1437 ///
1438 /// ```rust
1439 /// use rust_web_server::mcp::McpServer;
1440 ///
1441 /// let server = McpServer::new("my-server", "1.0");
1442 /// // Elsewhere, e.g. after reloading a watched config file:
1443 /// server.notify_resource_updated("config://main");
1444 /// ```
1445 pub fn notify_resource_updated(&self, uri: &str) {
1446 let params = format!(r#"{{"uri":"{}"}}"#, json_escape(uri));
1447 self.deliver_to_listeners("notifications/resources/updated", Some(¶ms), Some(uri));
1448 let session_ids = match self.subscriptions.lock().unwrap().get(uri) {
1449 Some(ids) if !ids.is_empty() => ids.clone(),
1450 _ => return,
1451 };
1452 let params = format!(r#"{{"uri":"{}"}}"#, json_escape(uri));
1453 let json = render_notification("notifications/resources/updated", Some(¶ms));
1454 send_sse_to_sessions(&self.sse_clients, &session_ids, &json);
1455 }
1456
1457 /// Handle `GET /mcp`: register a new SSE client and return a
1458 /// `text/event-stream` response that streams from its channel until the
1459 /// connection closes. See the module docs' SSE section for the wire
1460 /// details (keep-alive interval, backpressure behavior).
1461 ///
1462 /// Tags the client with this request's `Mcp-Session-Id` header, if
1463 /// present, so [`Self::notify_resource_updated`] can route
1464 /// `notifications/resources/updated` to just the sessions that
1465 /// subscribed via `resources/subscribe` — a client that connects
1466 /// without the header can still receive broadcasts (`.notify()`,
1467 /// `.log()`, `list_changed`) but can never be a subscription target.
1468 fn start_sse_stream(&self, request: &Request) -> Response {
1469 let session_id = request.get_header("Mcp-Session-Id".to_string()).map(|h| h.value.clone());
1470 let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(SSE_CHANNEL_CAPACITY);
1471 {
1472 let mut clients = self.sse_clients.lock().unwrap();
1473 if clients.len() >= self.max_sse_clients {
1474 // Disconnected clients are otherwise only noticed on the next
1475 // broadcast: a comment frame finds them now (#4).
1476 clients.retain(|client| !matches!(client.sender.try_send(b": ping\n\n".to_vec()), Err(mpsc::TrySendError::Disconnected(_))));
1477 }
1478 if clients.len() >= self.max_sse_clients {
1479 let mut busy = Response::new();
1480 busy.status_code = *STATUS_CODE_REASON_PHRASE.n503_service_unavailable.status_code;
1481 busy.reason_phrase = STATUS_CODE_REASON_PHRASE.n503_service_unavailable.reason_phrase.to_string();
1482 busy.headers.push(Header { name: "Retry-After".into(), value: "30".into() });
1483 return busy;
1484 }
1485 clients.push(SseClient { session_id: session_id.map(|v| v.into_owned()), sender: tx });
1486 }
1487
1488 let mut response = Response::new();
1489 response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
1490 response.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
1491 response.headers.push(Header {
1492 name: Header::_CONTENT_TYPE.into(),
1493 value: "text/event-stream".into(),
1494 });
1495 response.headers.push(Header {
1496 name: Header::_CACHE_CONTROL.into(),
1497 value: "no-cache".into(),
1498 });
1499 response.headers.push(Header {
1500 name: "X-Accel-Buffering".into(),
1501 value: "no".into(),
1502 });
1503 response.stream_pipe = Some(Box::new(crate::sse::SseReader::new(rx, SSE_KEEPALIVE_INTERVAL)));
1504 response
1505 }
1506
1507 /// **Deprecated by MCP 2026-07-28** (SEP-2577): Logging keeps working with
1508 /// clients that use it, for at least twelve months, but new servers shouldn't
1509 /// rely on it.
1510 ///
1511 /// Advertise the `logging` capability (`"logging":{}`) in `initialize`'s
1512 /// response, so clients know they can call `logging/setLevel` and expect
1513 /// `notifications/message` log entries over the `GET /mcp` SSE stream.
1514 ///
1515 /// This only changes what's *advertised* — [`Self::log`] pushes log
1516 /// entries regardless of whether this was called, same as [`Self::notify`]
1517 /// works unconditionally. A spec-honest client simply wouldn't send
1518 /// `logging/setLevel` in the first place without seeing the capability.
1519 ///
1520 /// ```rust
1521 /// use rust_web_server::mcp::McpServer;
1522 ///
1523 /// let server = McpServer::new("my-server", "1.0").logging_enabled();
1524 /// ```
1525 pub fn logging_enabled(mut self) -> Self {
1526 self.logging_enabled = true;
1527 self
1528 }
1529
1530 /// **Deprecated by MCP 2026-07-28** (SEP-2577): Logging keeps working with
1531 /// clients that use it, for at least twelve months, but new servers shouldn't
1532 /// rely on it.
1533 ///
1534 /// Push a `notifications/message` log entry to every client connected to
1535 /// the `GET /mcp` SSE stream, if `level` is at or above the level most
1536 /// recently set via a client's `logging/setLevel` request (or
1537 /// [`LogLevel::Debug`] — i.e. every level — if none has been set yet).
1538 ///
1539 /// `data_json` must already be a valid JSON value (the spec allows any
1540 /// type here, not just an object — a plain string is fine) — it's
1541 /// spliced in verbatim, not escaped or re-serialized. `logger`, if
1542 /// given, identifies the log's source (e.g. a module or subsystem name)
1543 /// and is escaped automatically.
1544 ///
1545 /// ```rust
1546 /// use rust_web_server::mcp::{LogLevel, McpServer};
1547 ///
1548 /// let server = McpServer::new("my-server", "1.0").logging_enabled();
1549 /// server.log(LogLevel::Warning, Some("database"), r#""connection pool exhausted""#);
1550 /// ```
1551 pub fn log(&self, level: LogLevel, logger: Option<&str>, data_json: &str) {
1552 if level < *self.min_log_level.lock().unwrap() {
1553 return;
1554 }
1555 let logger_field = match logger {
1556 Some(l) => format!(r#","logger":"{}""#, json_escape(l)),
1557 None => String::new(),
1558 };
1559 let params = format!(r#"{{"level":"{}"{logger_field},"data":{data_json}}}"#, level.as_str());
1560 self.notify("notifications/message", Some(¶ms));
1561 }
1562
1563 /// Handle `logging/setLevel`: store the requested minimum level so
1564 /// subsequent [`Self::log`] calls filter against it. Returns
1565 /// `INVALID_PARAMS` for a missing or unrecognized `params.level`.
1566 fn do_set_log_level(&self, body: &str) -> Result<String, (i32, String)> {
1567 let params = json_rpc::extract_raw(body, "params")
1568 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
1569 let level_str = json_rpc::extract_str(¶ms, "level")
1570 .ok_or((json_rpc::INVALID_PARAMS, "Missing level".to_string()))?;
1571 let level = LogLevel::parse(&level_str)
1572 .ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Unknown log level: {level_str}")))?;
1573 *self.min_log_level.lock().unwrap() = level;
1574 Ok("{}".to_string())
1575 }
1576
1577 // ── dynamic registration ──────────────────────────────────────────────────
1578 //
1579 // Unlike `.tool()`/`.resource()`/`.prompt()` (consuming builders, called
1580 // before the server starts serving requests), these take `&self` and can
1581 // be called at any time from any thread holding a clone of this
1582 // `McpServer` — e.g. after discovering a plugin, connecting to a
1583 // database, or reacting to a hot-reloaded config file. Every clone
1584 // shares the same underlying `Arc<RwLock<Vec<_>>>`, so a mutation made
1585 // through one clone is immediately visible to every other clone,
1586 // including the ones handling concurrent requests on other threads.
1587 //
1588 // Each registration/removal pushes the corresponding
1589 // `notifications/{tools,resources,prompts}/list_changed` event (no
1590 // params, per spec) to every `GET /mcp` SSE client via `.notify()`.
1591
1592 /// Register a callable tool at runtime, exactly like [`Self::tool`] but
1593 /// without needing to own the server (and usable after it's already
1594 /// serving requests). Pushes `notifications/tools/list_changed`.
1595 ///
1596 /// ```rust
1597 /// use rust_web_server::mcp::{McpContent, McpServer};
1598 ///
1599 /// let server = McpServer::new("my-server", "1.0");
1600 ///
1601 /// // Later, from any thread holding a clone of `server`:
1602 /// server.register_tool("refresh_cache", "Reload the in-memory cache", "{}", |_args| {
1603 /// Ok(McpContent::text("cache refreshed"))
1604 /// });
1605 /// let existed = server.remove_tool("refresh_cache");
1606 /// assert!(existed);
1607 /// ```
1608 pub fn register_tool<F>(&self, name: &str, description: &str, input_schema: &str, handler: F)
1609 where
1610 F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1611 {
1612 self.tools.write().unwrap().push(ToolDef {
1613 name: name.to_string(),
1614 description: description.to_string(),
1615 input_schema: input_schema.to_string(),
1616 annotations: None,
1617 meta: ToolMeta::default(),
1618 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
1619 });
1620 self.notify("notifications/tools/list_changed", None);
1621 }
1622
1623 /// Register an `async fn` tool handler at runtime, exactly like
1624 /// [`Self::async_tool`] but usable after the server is already serving
1625 /// requests. Requires the `http2` feature — see `async_tool`'s docs for
1626 /// the async-to-sync bridging details.
1627 #[cfg(feature = "http2")]
1628 pub fn register_async_tool<F, Fut>(&self, name: &str, description: &str, input_schema: &str, handler: F)
1629 where
1630 F: Fn(&str) -> Fut + Send + Sync + 'static,
1631 Fut: Future<Output = Result<McpContent, String>> + Send + 'static,
1632 {
1633 self.async_tools.write().unwrap().push(AsyncToolDef {
1634 name: name.to_string(),
1635 description: description.to_string(),
1636 input_schema: input_schema.to_string(),
1637 annotations: None,
1638 meta: ToolMeta::default(),
1639 handler: Arc::new(move |args: String| Box::pin(handler(&args))),
1640 });
1641 self.notify("notifications/tools/list_changed", None);
1642 }
1643
1644 /// Remove a previously-registered tool by name — a sync tool registered
1645 /// via [`Self::tool`]/[`Self::register_tool`], or (with the `http2`
1646 /// feature) an async one via [`Self::async_tool`]/[`Self::register_async_tool`];
1647 /// both collections are checked. Returns `true` if a tool with that name
1648 /// existed in either and was removed. Pushes `notifications/tools/list_changed`
1649 /// only when something was actually removed.
1650 pub fn remove_tool(&self, name: &str) -> bool {
1651 #[cfg_attr(not(feature = "http2"), allow(unused_mut))]
1652 let mut removed = {
1653 let mut tools = self.tools.write().unwrap();
1654 let before = tools.len();
1655 tools.retain(|t| t.name != name);
1656 tools.len() != before
1657 };
1658
1659 #[cfg(feature = "http2")]
1660 {
1661 let mut async_tools = self.async_tools.write().unwrap();
1662 let before = async_tools.len();
1663 async_tools.retain(|t| t.name != name);
1664 removed = removed || async_tools.len() != before;
1665 }
1666
1667 if removed {
1668 self.notify("notifications/tools/list_changed", None);
1669 }
1670 removed
1671 }
1672
1673 /// Register a readable resource at runtime, exactly like [`Self::resource`].
1674 /// Pushes `notifications/resources/list_changed`.
1675 pub fn register_resource<F>(&self, uri_template: &str, name: &str, description: &str, handler: F)
1676 where
1677 F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1678 {
1679 self.resources.write().unwrap().push(ResourceDef {
1680 uri_template: uri_template.to_string(),
1681 name: name.to_string(),
1682 description: description.to_string(),
1683 handler: Arc::new(handler),
1684 });
1685 self.notify("notifications/resources/list_changed", None);
1686 }
1687
1688 /// Remove a previously-registered resource by its exact `uri_template`
1689 /// (the same string passed to [`Self::register_resource`]/[`Self::resource`],
1690 /// not a concrete URI). Returns `true` if it existed. Pushes
1691 /// `notifications/resources/list_changed` only when something was removed.
1692 pub fn remove_resource(&self, uri_template: &str) -> bool {
1693 let removed = {
1694 let mut resources = self.resources.write().unwrap();
1695 let before = resources.len();
1696 resources.retain(|r| r.uri_template != uri_template);
1697 resources.len() != before
1698 };
1699 if removed {
1700 self.notify("notifications/resources/list_changed", None);
1701 }
1702 removed
1703 }
1704
1705 /// Register a prompt template at runtime, exactly like [`Self::prompt`]
1706 /// (no argument definitions — use [`Self::remove_prompt`] +
1707 /// [`Self::register_prompt`] if you need to change a prompt's arguments
1708 /// later; there is no dynamic equivalent of [`Self::prompt_with_args`]).
1709 /// Pushes `notifications/prompts/list_changed`.
1710 pub fn register_prompt<F>(&self, name: &str, description: &str, handler: F)
1711 where
1712 F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
1713 {
1714 self.prompts.write().unwrap().push(PromptDef {
1715 name: name.to_string(),
1716 description: description.to_string(),
1717 arguments: vec![],
1718 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args).map(PromptReply::Messages)),
1719 });
1720 self.notify("notifications/prompts/list_changed", None);
1721 }
1722
1723 /// Remove a previously-registered prompt by name. Returns `true` if it
1724 /// existed. Pushes `notifications/prompts/list_changed` only when
1725 /// something was removed.
1726 pub fn remove_prompt(&self, name: &str) -> bool {
1727 let removed = {
1728 let mut prompts = self.prompts.write().unwrap();
1729 let before = prompts.len();
1730 prompts.retain(|p| p.name != name);
1731 prompts.len() != before
1732 };
1733 if removed {
1734 self.notify("notifications/prompts/list_changed", None);
1735 }
1736 removed
1737 }
1738
1739 /// Require a bearer token on every request to the MCP endpoint.
1740 ///
1741 /// The client must send `Authorization: Bearer <token>`. Requests with a
1742 /// missing or wrong token receive `401 Unauthorized` before any JSON-RPC
1743 /// processing occurs.
1744 ///
1745 /// Store the token in an environment variable — never hard-code it:
1746 ///
1747 /// ```rust,no_run
1748 /// use rust_web_server::app::App;
1749 /// use rust_web_server::core::New;
1750 ///
1751 /// let app = App::new()
1752 /// .mcp("my-server", "1.0")
1753 /// .require_bearer(std::env::var("MCP_TOKEN").expect("MCP_TOKEN not set"));
1754 /// ```
1755 ///
1756 /// Claude Desktop config:
1757 /// ```json
1758 /// { "mcpServers": { "my-server": {
1759 /// "url": "http://localhost:7878/mcp",
1760 /// "headers": { "Authorization": "Bearer <token>" }
1761 /// }}}
1762 /// ```
1763 ///
1764 /// An empty token refuses every request (fails closed) rather than
1765 /// accepting an empty `Authorization: Bearer` (since 17.113.1). Tokens
1766 /// are compared in constant time.
1767 pub fn require_bearer(mut self, token: impl Into<String>) -> Self {
1768 self.auth_token = Some(token.into());
1769 self
1770 }
1771
1772 /// Accept several bearer tokens, each naming a caller: a request with
1773 /// `Authorization: Bearer <token>` is that caller, and handlers see
1774 /// `{"sub":"<identity>"}` as [`McpContext::auth_claims`] — what
1775 /// [`Self::tool_filter`] and the [gateway](gateway::McpGateway) decide
1776 /// by. Any other token gets `401`. Combines with
1777 /// [`Self::require_bearer`] (whose token carries no identity); OAuth
1778 /// ([`Self::require_oauth`]) replaces both. Empty tokens never match;
1779 /// tokens are compared in constant time.
1780 ///
1781 /// ```rust
1782 /// use rust_web_server::mcp::McpServer;
1783 ///
1784 /// let server = McpServer::new("my-server", "1.0")
1785 /// .require_bearer_tokens([("token-for-alice", "alice"), ("token-for-ci", "ci")]);
1786 /// ```
1787 pub fn require_bearer_tokens<I, T, N>(mut self, tokens: I) -> Self
1788 where
1789 I: IntoIterator<Item = (T, N)>,
1790 T: Into<String>,
1791 N: Into<String>,
1792 {
1793 self.bearer_tokens.extend(tokens.into_iter().map(|(token, identity)| (token.into(), identity.into())));
1794 self
1795 }
1796
1797 /// Show and allow only the tools `allow(ctx, tool_name)` accepts for a
1798 /// request: `tools/list` leaves the others out, and `tools/call` answers
1799 /// them as it would an unknown tool. `ctx.auth_claims` identifies the
1800 /// caller ([`Self::require_bearer_tokens`], [`Self::require_oauth`]).
1801 ///
1802 /// ```rust
1803 /// use rust_web_server::mcp::McpServer;
1804 ///
1805 /// let server = McpServer::new("my-server", "1.0")
1806 /// .tool_filter(|ctx, tool| !tool.starts_with("admin_") || ctx.auth_claims.as_deref() == Some(r#"{"sub":"root"}"#));
1807 /// ```
1808 pub fn tool_filter<F>(mut self, allow: F) -> Self
1809 where
1810 F: Fn(&McpContext, &str) -> bool + Send + Sync + 'static,
1811 {
1812 self.tool_filter = Some(Arc::new(allow));
1813 self
1814 }
1815
1816 fn tool_allowed(&self, ctx: &McpContext, name: &str) -> bool {
1817 self.tool_filter.as_ref().is_none_or(|allow| allow(ctx, name))
1818 }
1819
1820 /// Checks a request's bearer token against [`Self::require_bearer`] and
1821 /// [`Self::require_bearer_tokens`]: `Ok(claims)` (`Some` for a named
1822 /// token), or the `401` to send.
1823 fn check_bearer(&self, request: &Request) -> Result<Option<String>, Response> {
1824 if self.auth_token.is_none() && self.bearer_tokens.is_empty() {
1825 return Ok(None);
1826 }
1827 let provided = request.headers.iter()
1828 .find(|h| h.name.eq_ignore_ascii_case("authorization"))
1829 .map(|h| h.value.as_ref())
1830 .unwrap_or("");
1831 let bearer = provided.strip_prefix("Bearer ").unwrap_or("");
1832 // Compare against every token so the time taken doesn't tell which one matched.
1833 let mut identity = None;
1834 for (token, name) in &self.bearer_tokens {
1835 if bearer_matches(token, bearer) && identity.is_none() {
1836 identity = Some(name);
1837 }
1838 }
1839 if let Some(identity) = identity {
1840 return Ok(Some(format!(r#"{{"sub":"{}"}}"#, json_escape(identity))));
1841 }
1842 match &self.auth_token {
1843 Some(expected) if bearer_matches(expected, bearer) => Ok(None),
1844 _ => Err(unauthorized()),
1845 }
1846 }
1847
1848 /// Browser origins allowed to call the MCP endpoint, e.g.
1849 /// `["https://inspector.example.com"]`. A request carrying an `Origin`
1850 /// header that isn't listed gets `403` (the MCP transport spec requires
1851 /// validating `Origin`: without it a web page — or a DNS-rebinding
1852 /// attack — can drive a local MCP server from the visitor's browser).
1853 /// Requests without `Origin` (CLI and agent clients) are unaffected.
1854 /// Empty by default: no browser origin is allowed (since 17.113.1).
1855 pub fn allowed_origins<I, S>(mut self, origins: I) -> Self
1856 where
1857 I: IntoIterator<Item = S>,
1858 S: Into<String>,
1859 {
1860 self.allowed_origins = origins.into_iter().map(Into::into).collect();
1861 self
1862 }
1863
1864 /// Require an OAuth 2.0 / OIDC bearer JWT — verified against a live
1865 /// JWKS endpoint — on every request to the MCP endpoint (MCP
1866 /// 2025-03-26's OAuth 2.0 authorization requirement), instead of one
1867 /// static shared secret. Requires the `sso` feature.
1868 ///
1869 /// Reuses [`crate::sso::jwks::JwksCache`] directly — the "leverage
1870 /// point" this feature was scoped around — rather than reimplementing
1871 /// JWT/JWKS verification. `provider` supplies the issuer, JWKS URI, and
1872 /// (for `GET /.well-known/oauth-protected-resource`, RFC 9728) the
1873 /// authorization server's issuer; `audience` is the value tokens must
1874 /// carry in `aud` — ideally this server's canonical URL
1875 /// (`https://mcp.example.com/mcp`, RFC 8707), which is then also the
1876 /// metadata's `resource`; use a preset
1877 /// (`OidcProvider::google()`, etc.) or `OidcProvider::discover(issuer)?`.
1878 ///
1879 /// A request with a missing, malformed, or invalid-signature bearer
1880 /// token gets `401` with `WWW-Authenticate: Bearer` before any JSON-RPC
1881 /// processing occurs — matching [`Self::require_bearer`]'s behavior. On
1882 /// success, the verified claims are available to `.tool_with_context()`
1883 /// handlers as JSON via [`McpContext::auth_claims`].
1884 ///
1885 /// If both this and [`Self::require_bearer`] are configured, OAuth
1886 /// verification takes precedence and the static token is never checked
1887 /// — configuring both is not a supported combination, just an
1888 /// unambiguous tie-break for an unusual configuration.
1889 ///
1890 /// ```rust,no_run
1891 /// use rust_web_server::app::App;
1892 /// use rust_web_server::core::New;
1893 /// use rust_web_server::sso::OidcProvider;
1894 ///
1895 /// let app = App::new()
1896 /// .mcp("my-server", "1.0")
1897 /// .require_oauth(OidcProvider::google(), "my-mcp-client-id");
1898 /// ```
1899 #[cfg(feature = "sso")]
1900 pub fn require_oauth(mut self, provider: crate::sso::OidcProvider, audience: impl Into<String>) -> Self {
1901 self.oauth = Some(Arc::new(OAuthConfig {
1902 jwks: crate::sso::jwks::JwksCache::new(&provider.jwks_uri),
1903 provider,
1904 audience: audience.into(),
1905 }));
1906 self
1907 }
1908
1909 /// Wrap an existing [`Application`] so that non-MCP requests are forwarded
1910 /// to it instead of the built-in [`App`].
1911 ///
1912 /// Use this when your existing server has custom routes, state, or
1913 /// middleware that you want to keep alongside the MCP endpoint:
1914 ///
1915 /// ```rust,no_run
1916 /// use rust_web_server::app::App;
1917 /// use rust_web_server::mcp::{McpServer, McpContent};
1918 /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
1919 /// use rust_web_server::test_client::TestClient;
1920 ///
1921 /// let existing_app = App::with_state(42u32)
1922 /// .get("/api/hello", |_req, _params, _conn, _state| {
1923 /// Response::get_response(&STATUS_CODE_REASON_PHRASE.n200_ok, None, None)
1924 /// });
1925 ///
1926 /// let server = McpServer::new("my-app", "1.0")
1927 /// .tool("ping", "Ping", "{}", |_| Ok(McpContent::text("pong")))
1928 /// .wrap(existing_app);
1929 ///
1930 /// // Both /mcp and /api/hello are now handled by the same server.
1931 /// let client = TestClient::new(server);
1932 /// ```
1933 pub fn wrap(mut self, app: impl Application + Send + Sync + 'static) -> Self {
1934 self.fallback = Some(Arc::new(app));
1935 self
1936 }
1937
1938 /// Override the HTTP path for the MCP endpoint (default `"/mcp"`).
1939 pub fn at(mut self, path: impl Into<String>) -> Self {
1940 self.path = path.into();
1941 self
1942 }
1943
1944 /// Register a callable tool.
1945 ///
1946 /// - `name` — tool identifier (snake_case recommended)
1947 /// - `description` — human-readable description shown to the AI
1948 /// - `input_schema` — JSON Schema object for the tool's arguments
1949 /// - `handler` — closure receiving the raw `arguments` JSON string
1950 ///
1951 /// The handler returns [`McpContent`] on success or an error string. An
1952 /// error is returned to the client as `isError: true` (not a protocol error).
1953 ///
1954 /// Use [`Self::tool_with_context`] instead if the handler needs the
1955 /// caller's identity, session, or headers.
1956 pub fn tool<F>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
1957 where
1958 F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1959 {
1960 self.tools.write().unwrap().push(ToolDef {
1961 name: name.to_string(),
1962 description: description.to_string(),
1963 input_schema: input_schema.to_string(),
1964 annotations: None,
1965 meta: ToolMeta::default(),
1966 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
1967 });
1968 self
1969 }
1970
1971 /// Register an `async fn` tool handler — for a tool whose work is
1972 /// naturally async (an `AsyncClient` HTTP call, an async database
1973 /// query, awaiting another future) rather than forcing it through a
1974 /// blocking call inside a plain [`Self::tool`] handler.
1975 ///
1976 /// Requires the `http2` feature (tokio). `tools/call` bridges into the
1977 /// handler's future via [`crate::async_bridge::block_on_isolated`] —
1978 /// the same mechanism [`crate::proxy::H2ReverseProxy`] and
1979 /// [`crate::async_state::AsyncAppWithState`] already use to call async
1980 /// code from a synchronous [`Application::execute`] — rather than
1981 /// `tokio::task::block_in_place`, which panics outside a `multi_thread`
1982 /// runtime; `block_on_isolated` works under any runtime flavor,
1983 /// including `current_thread`.
1984 ///
1985 /// Like [`Self::tool`] (not [`Self::tool_with_context`]), the handler
1986 /// only receives `arguments` — there is no async equivalent of
1987 /// `tool_with_context` or `tool_annotated` yet.
1988 ///
1989 /// ```rust,no_run
1990 /// # #[cfg(feature = "http2")]
1991 /// # {
1992 /// use rust_web_server::mcp::{McpContent, McpServer};
1993 ///
1994 /// let server = McpServer::new("my-server", "1.0")
1995 /// .async_tool("call_api", "Call an external API", "{}", |_args: &str| async move {
1996 /// Ok(McpContent::text("response"))
1997 /// });
1998 /// # }
1999 /// ```
2000 #[cfg(feature = "http2")]
2001 pub fn async_tool<F, Fut>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
2002 where
2003 F: Fn(&str) -> Fut + Send + Sync + 'static,
2004 Fut: Future<Output = Result<McpContent, String>> + Send + 'static,
2005 {
2006 self.async_tools.write().unwrap().push(AsyncToolDef {
2007 name: name.to_string(),
2008 description: description.to_string(),
2009 input_schema: input_schema.to_string(),
2010 annotations: None,
2011 meta: ToolMeta::default(),
2012 handler: Arc::new(move |args: String| Box::pin(handler(&args))),
2013 });
2014 self
2015 }
2016
2017 /// Register a callable tool with [`ToolAnnotations`] — behavioral hints
2018 /// (read-only, destructive, idempotent, open-world) that MCP clients use
2019 /// to decide whether to warn or confirm before calling it. Otherwise
2020 /// identical to [`Self::tool`] — the handler still only receives
2021 /// `arguments`, not [`McpContext`] (there is currently no single builder
2022 /// combining annotations with per-request context; call [`Self::tool_with_context`]
2023 /// instead if you need context and don't need annotations).
2024 ///
2025 /// ```rust,no_run
2026 /// use rust_web_server::mcp::{McpContent, McpServer, ToolAnnotations};
2027 ///
2028 /// let server = McpServer::new("my-server", "1.0")
2029 /// .tool_annotated(
2030 /// "delete_file",
2031 /// "Delete a file from disk",
2032 /// r#"{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}"#,
2033 /// ToolAnnotations {
2034 /// destructive_hint: Some(true),
2035 /// read_only_hint: Some(false),
2036 /// idempotent_hint: Some(true), // deleting twice = deleting once
2037 /// ..Default::default()
2038 /// },
2039 /// |_args| Ok(McpContent::text("deleted")),
2040 /// );
2041 /// ```
2042 pub fn tool_annotated<F>(
2043 self,
2044 name: &str,
2045 description: &str,
2046 input_schema: &str,
2047 annotations: ToolAnnotations,
2048 handler: F,
2049 ) -> Self
2050 where
2051 F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
2052 {
2053 self.tools.write().unwrap().push(ToolDef {
2054 name: name.to_string(),
2055 description: description.to_string(),
2056 input_schema: input_schema.to_string(),
2057 annotations: Some(annotations),
2058 meta: ToolMeta::default(),
2059 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
2060 });
2061 self
2062 }
2063
2064 /// Register a callable tool whose handler also receives [`McpContext`] —
2065 /// caller identity/session info derived from this request's headers and
2066 /// whatever `clientInfo` this session sent at `initialize` time.
2067 ///
2068 /// Same `name`/`description`/`input_schema` semantics as [`Self::tool`];
2069 /// the only difference is the handler's first parameter.
2070 ///
2071 /// ```rust,no_run
2072 /// use rust_web_server::mcp::{McpContent, McpServer};
2073 ///
2074 /// let server = McpServer::new("my-server", "1.0")
2075 /// .tool_with_context(
2076 /// "whoami",
2077 /// "Report the caller's client info",
2078 /// "{}",
2079 /// |ctx, _args| {
2080 /// let name = ctx.client_name.as_deref().unwrap_or("unknown client");
2081 /// Ok(McpContent::text(format!("Called by {name}")))
2082 /// },
2083 /// );
2084 /// ```
2085 pub fn tool_with_context<F>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
2086 where
2087 F: Fn(McpContext, &str) -> Result<McpContent, String> + Send + Sync + 'static,
2088 {
2089 self.tools.write().unwrap().push(ToolDef {
2090 name: name.to_string(),
2091 description: description.to_string(),
2092 input_schema: input_schema.to_string(),
2093 annotations: None,
2094 meta: ToolMeta::default(),
2095 handler: Arc::new(handler),
2096 });
2097 self
2098 }
2099
2100 /// Register a tool whose arguments and result are Rust types: the
2101 /// `inputSchema` comes from `In` and the `outputSchema` from `Out`
2102 /// ([`JsonSchema`](crate::schema::JsonSchema), usually
2103 /// `#[derive(JsonSchema)]`), the arguments are deserialized into `In`, and
2104 /// the handler's `Out` is sent as `structuredContent` (and as JSON text
2105 /// for older clients). Requires the `serde` feature.
2106 ///
2107 /// Arguments that don't deserialize come back as an `isError` result
2108 /// naming the problem, as do the handler's errors. MCP requires an
2109 /// `outputSchema` to describe an object, so an `Out` that isn't a struct
2110 /// is sent as JSON text without one.
2111 ///
2112 /// ```rust,ignore
2113 /// use rust_web_server::JsonSchema;
2114 /// use serde::{Deserialize, Serialize};
2115 ///
2116 /// #[derive(Deserialize, JsonSchema)]
2117 /// struct Lookup { sku: String }
2118 ///
2119 /// #[derive(Serialize, JsonSchema)]
2120 /// struct Stock { sku: String, available: u32 }
2121 ///
2122 /// let server = McpServer::new("shop", "1.0")
2123 /// .typed_tool("stock", "Units available for a SKU", |_ctx, args: Lookup| {
2124 /// Ok(Stock { available: 3, sku: args.sku })
2125 /// });
2126 /// ```
2127 #[cfg(feature = "serde")]
2128 pub fn typed_tool<In, Out, F>(self, name: &str, description: &str, handler: F) -> Self
2129 where
2130 In: serde::de::DeserializeOwned + crate::schema::JsonSchema,
2131 Out: serde::Serialize + crate::schema::JsonSchema,
2132 F: Fn(McpContext, In) -> Result<Out, String> + Send + Sync + 'static,
2133 {
2134 let output_schema = Out::json_schema();
2135 let structured = crate::schema::is_object_schema(&output_schema);
2136 let server = self.tool_with_context(name, description, &In::json_schema(), move |ctx, args| {
2137 let args = if args.trim().is_empty() { "{}" } else { args };
2138 let input: In = serde_json::from_str(args).map_err(|e| format!("Invalid arguments: {e}"))?;
2139 let output = handler(ctx, input)?;
2140 let json = serde_json::to_string(&output).map_err(|e| format!("Could not serialize the result: {e}"))?;
2141 Ok(if structured { McpContent::structured(json) } else { McpContent::json(json) })
2142 });
2143 if structured {
2144 server.tool_output_schema(name, &output_schema)
2145 } else {
2146 server
2147 }
2148 }
2149
2150 /// Register a readable resource.
2151 ///
2152 /// `uri_template` uses `{param}` placeholders, e.g. `"user://{id}"`.
2153 /// The handler receives the full concrete URI string.
2154 pub fn resource<F>(self, uri_template: &str, name: &str, description: &str, handler: F) -> Self
2155 where
2156 F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
2157 {
2158 self.resources.write().unwrap().push(ResourceDef {
2159 uri_template: uri_template.to_string(),
2160 name: name.to_string(),
2161 description: description.to_string(),
2162 handler: Arc::new(handler),
2163 });
2164 self
2165 }
2166
2167 /// Register a prompt template.
2168 ///
2169 /// The handler receives the raw `arguments` JSON string and returns a
2170 /// list of [`PromptMessage`] values.
2171 pub fn prompt<F>(self, name: &str, description: &str, handler: F) -> Self
2172 where
2173 F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
2174 {
2175 self.prompts.write().unwrap().push(PromptDef {
2176 name: name.to_string(),
2177 description: description.to_string(),
2178 arguments: vec![],
2179 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args).map(PromptReply::Messages)),
2180 });
2181 self
2182 }
2183
2184 /// Register a prompt template with explicit argument definitions.
2185 pub fn prompt_with_args<F>(
2186 self,
2187 name: &str,
2188 description: &str,
2189 args: Vec<PromptArgDef>,
2190 handler: F,
2191 ) -> Self
2192 where
2193 F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
2194 {
2195 self.prompts.write().unwrap().push(PromptDef {
2196 name: name.to_string(),
2197 description: description.to_string(),
2198 arguments: args,
2199 handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args).map(PromptReply::Messages)),
2200 });
2201 self
2202 }
2203
2204 /// [`Self::prompt_with_args`] whose handler also gets the request's
2205 /// [`McpContext`] and may answer [`PromptReply::InputRequired`] to ask
2206 /// the client for input first (MCP 2026-07-28).
2207 pub fn prompt_with_context<F>(
2208 self,
2209 name: &str,
2210 description: &str,
2211 args: Vec<PromptArgDef>,
2212 handler: F,
2213 ) -> Self
2214 where
2215 F: Fn(McpContext, &str) -> Result<PromptReply, String> + Send + Sync + 'static,
2216 {
2217 self.prompts.write().unwrap().push(PromptDef {
2218 name: name.to_string(),
2219 description: description.to_string(),
2220 arguments: args,
2221 handler: Arc::new(handler),
2222 });
2223 self
2224 }
2225
2226 /// Register an argument-completion provider for one named argument of a
2227 /// tool or prompt, so clients like Cursor and VS Code can offer
2228 /// autocomplete while the user fills in that argument.
2229 ///
2230 /// `ref_type` is `"tool"` or `"prompt"` — matched against the incoming
2231 /// `completion/complete` request's `ref.type` (`"ref/tool"`/`"ref/prompt"`
2232 /// on the wire) with the `"ref/"` prefix stripped. `ref_name` is the
2233 /// tool or prompt name this applies to. The handler receives the
2234 /// argument's name and whatever partial value the user has typed so
2235 /// far, and returns candidate completion strings (or an error, mapped
2236 /// to a JSON-RPC `INVALID_PARAMS` response).
2237 ///
2238 /// `initialize` advertises the `completions` capability automatically
2239 /// once at least one `.completion()` has been registered — there's no
2240 /// separate opt-in flag to remember.
2241 ///
2242 /// ```rust
2243 /// use rust_web_server::mcp::McpServer;
2244 ///
2245 /// let server = McpServer::new("my-server", "1.0")
2246 /// .completion("tool", "deploy", |arg_name, _partial| {
2247 /// match arg_name {
2248 /// "region" => Ok(vec!["us-east-1".to_string(), "eu-west-1".to_string()]),
2249 /// _ => Ok(vec![]),
2250 /// }
2251 /// });
2252 /// ```
2253 pub fn completion<F>(self, ref_type: &str, ref_name: &str, handler: F) -> Self
2254 where
2255 F: Fn(&str, &str) -> Result<Vec<String>, String> + Send + Sync + 'static,
2256 {
2257 self.completions.write().unwrap().push(CompletionDef {
2258 ref_type: ref_type.to_string(),
2259 ref_name: ref_name.to_string(),
2260 handler: Arc::new(handler),
2261 });
2262 self
2263 }
2264
2265 // ── request dispatch ──────────────────────────────────────────────────────
2266
2267 /// Process a raw JSON-RPC body and return an HTTP response.
2268 ///
2269 /// Equivalent to [`Self::handle_request_with_context`] with an empty
2270 /// [`McpContext`] — tool handlers registered via
2271 /// [`Self::tool_with_context`] will see every field as `None`. Prefer
2272 /// calling through [`Application::execute`] (i.e. actually serving HTTP
2273 /// requests) when you need real per-request context; this method exists
2274 /// for calling the JSON-RPC layer directly, e.g. in tests.
2275 pub fn handle_request(&self, body: &str) -> Response {
2276 self.handle_request_with_context(body, McpContext::default())
2277 }
2278
2279 /// Process a raw JSON-RPC body with an explicit [`McpContext`] and return
2280 /// an HTTP response. [`Self::execute`] calls this with a context built
2281 /// from the request's headers and this session's stored `clientInfo`;
2282 /// [`Self::handle_request`] calls this with an empty context.
2283 ///
2284 /// On a successful `initialize`, this mints a new session id (reusing
2285 /// [`crate::request_id::generate_request_id`]'s ID generator), records
2286 /// `params.clientInfo` under it, and returns the id in an
2287 /// `Mcp-Session-Id` response header — the client is expected to echo that
2288 /// header back on subsequent requests so later `tools/call`s in the same
2289 /// session can look their `clientInfo` back up.
2290 pub fn handle_request_with_context(&self, body: &str, ctx: McpContext) -> Response {
2291 let trimmed = body.trim_start();
2292 if trimmed.starts_with('[') {
2293 return self.handle_batch(trimmed, ctx);
2294 }
2295
2296 let id = json_rpc::extract_id(body);
2297
2298 let method = match json_rpc::extract_str(body, "method") {
2299 Some(m) => m,
2300 None => {
2301 // No `method` — either malformed, or a JSON-RPC *response*
2302 // to a sampling/createMessage request this server sent
2303 // earlier (responses never carry `method`).
2304 if let Some(id) = &id {
2305 if self.try_deliver_sampling_response(id, body) {
2306 return no_content();
2307 }
2308 }
2309 return rpc_error(None, json_rpc::INVALID_REQUEST, "Missing method");
2310 }
2311 };
2312
2313 if method == "notifications/cancelled" {
2314 self.handle_cancellation(body);
2315 return no_content();
2316 }
2317
2318 if method == "notifications/roots/list_changed" {
2319 self.invalidate_roots_cache(&ctx.session_id);
2320 return no_content();
2321 }
2322
2323 // Notifications have no `id` — acknowledge with 202 and no body.
2324 if method == "notifications/initialized" || (id.is_none() && method != "ping") {
2325 return no_content();
2326 }
2327
2328 let result = self.dispatch_with_cancellation(&method, body, ctx, &id);
2329 let id_str = id.as_deref().unwrap_or("null");
2330 let is_ok = result.is_ok();
2331
2332 let mut response = json_response(&Self::format_result(id_str, &result));
2333
2334 if method == "initialize" && is_ok {
2335 self.start_session(body, &mut response);
2336 }
2337
2338 response
2339 }
2340
2341 /// Process a JSON-RPC 2.0 batch request — a top-level JSON array of
2342 /// request objects sent in a single `POST /mcp` body, per the JSON-RPC
2343 /// batch spec that MCP inherits. Each element is dispatched exactly as
2344 /// [`Self::handle_request_with_context`] would dispatch it standalone;
2345 /// notifications (no `id`) contribute no entry to the response array,
2346 /// same as they'd get no response body outside a batch.
2347 ///
2348 /// An empty array (`[]`) is itself an invalid request per the JSON-RPC
2349 /// spec, so it gets one `Invalid Request` error object back rather than
2350 /// an empty array. A batch made up entirely of notifications produces no
2351 /// response body at all (`202 Accepted`), matching a single notification.
2352 ///
2353 /// If the batch contains a successful `initialize` call, the *first* one
2354 /// mints a session and attaches `Mcp-Session-Id` to the overall response,
2355 /// same as a standalone `initialize` would — sending more than one
2356 /// `initialize` in a batch is unusual and only the first is honored for
2357 /// session purposes, since one HTTP response can only carry one session id.
2358 fn handle_batch(&self, array_body: &str, ctx: McpContext) -> Response {
2359 let elements = json_rpc::split_array_elements(array_body);
2360 if elements.is_empty() {
2361 return rpc_error(None, json_rpc::INVALID_REQUEST, "Invalid Request");
2362 }
2363
2364 let mut parts: Vec<String> = Vec::new();
2365 let mut session_init_body: Option<String> = None;
2366
2367 for elem in &elements {
2368 let id = json_rpc::extract_id(elem);
2369
2370 let method = match json_rpc::extract_str(elem, "method") {
2371 Some(m) => m,
2372 None => {
2373 if let Some(id) = &id {
2374 if self.try_deliver_sampling_response(id, elem) {
2375 continue; // delivered; no response entry, same as any notification
2376 }
2377 }
2378 parts.push(Self::format_result(
2379 "null",
2380 &Err((json_rpc::INVALID_REQUEST, "Missing method".to_string())),
2381 ));
2382 continue;
2383 }
2384 };
2385
2386 if method == "notifications/cancelled" {
2387 self.handle_cancellation(elem);
2388 continue;
2389 }
2390
2391 if method == "notifications/roots/list_changed" {
2392 self.invalidate_roots_cache(&ctx.session_id);
2393 continue;
2394 }
2395
2396 if method == "notifications/initialized" || (id.is_none() && method != "ping") {
2397 continue;
2398 }
2399
2400 let result = self.dispatch_with_cancellation(&method, elem, ctx.clone(), &id);
2401 let id_str = id.as_deref().unwrap_or("null");
2402 let is_ok = result.is_ok();
2403
2404 if method == "initialize" && is_ok && session_init_body.is_none() {
2405 session_init_body = Some(elem.clone());
2406 }
2407
2408 parts.push(Self::format_result(id_str, &result));
2409 }
2410
2411 if parts.is_empty() {
2412 // Every element was a notification — no response body, same as a
2413 // single standalone notification.
2414 return no_content();
2415 }
2416
2417 let mut response = json_response(&format!("[{}]", parts.join(",")));
2418 if let Some(init_body) = session_init_body {
2419 self.start_session(&init_body, &mut response);
2420 }
2421 response
2422 }
2423
2424 /// Dispatch one already-parsed JSON-RPC `method` against `body` (the raw
2425 /// single-object message, whether it arrived standalone or as one element
2426 /// of a batch) and return the JSON-RPC `result` payload or an error.
2427 /// Shared by [`Self::handle_request_with_context`] and [`Self::handle_batch`]
2428 /// so the method table exists in exactly one place.
2429 fn dispatch(&self, method: &str, body: &str, ctx: McpContext) -> Result<String, (i32, String)> {
2430 match method {
2431 "initialize" => self.do_initialize(body),
2432 "ping" => Ok("{}".to_string()),
2433 "tools/list" => self.do_tools_list(body, &ctx),
2434 "tools/call" => self.do_tools_call(body, ctx),
2435 "resources/list" => self.do_resources_list(body),
2436 "resources/read" => self.do_resources_read(body),
2437 "resources/templates/list" => self.do_resource_templates_list(body),
2438 "resources/subscribe" => self.do_resource_subscribe(body, ctx.session_id),
2439 "resources/unsubscribe" => self.do_resource_unsubscribe(body, ctx.session_id),
2440 "prompts/list" => self.do_prompts_list(body),
2441 "prompts/get" => self.do_prompts_get(body, ctx),
2442 "logging/setLevel" => self.do_set_log_level(body),
2443 "completion/complete" => self.do_completion(body),
2444 _ => Err((json_rpc::METHOD_NOT_FOUND, format!("Unknown method: {method}"))),
2445 }
2446 }
2447
2448 /// Wraps [`Self::dispatch`] for one request, additionally registering a
2449 /// cancellation flag for `tools/call` (keyed by `id`, guaranteed `Some`
2450 /// for `tools/call` — a notification-shaped `tools/call` with no `id`
2451 /// never reaches this far, see the notification checks in
2452 /// [`Self::handle_request_with_context`]/[`Self::handle_batch`]) so a
2453 /// later `notifications/cancelled` referencing this exact request can
2454 /// flip it. The entry is removed again once dispatch returns, whether
2455 /// the handler checked the flag or not — this map never accumulates
2456 /// stale entries the way `sessions`/`sse_clients` can.
2457 fn dispatch_with_cancellation(
2458 &self,
2459 method: &str,
2460 body: &str,
2461 ctx: McpContext,
2462 id: &Option<String>,
2463 ) -> Result<String, (i32, String)> {
2464 let Some(id_str) = (method == "tools/call").then_some(id.as_ref()).flatten() else {
2465 return self.dispatch(method, body, ctx);
2466 };
2467
2468 let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
2469 self.cancellations.lock().unwrap().insert(id_str.clone(), flag.clone());
2470 let ctx = McpContext { cancellation: Some(flag), ..ctx };
2471 let result = self.dispatch(method, body, ctx);
2472 self.cancellations.lock().unwrap().remove(id_str);
2473 result
2474 }
2475
2476 /// Handle `notifications/cancelled`: look up `params.requestId` (the
2477 /// spec allows `string | number`, so this is matched as a raw JSON
2478 /// token, the same way [`McpContext::progress_token`] is) in
2479 /// `cancellations` and flip its flag if the request is still in flight.
2480 /// Silently does nothing for an unknown/already-finished request id —
2481 /// the target call may simply have already completed naturally, which
2482 /// isn't an error.
2483 fn handle_cancellation(&self, body: &str) {
2484 let Some(params) = json_rpc::extract_raw(body, "params") else { return };
2485 let Some(request_id) = json_rpc::extract_raw(¶ms, "requestId") else { return };
2486 if let Some(flag) = self.cancellations.lock().unwrap().get(&request_id) {
2487 flag.store(true, std::sync::atomic::Ordering::Relaxed);
2488 }
2489 }
2490
2491 /// Handle `notifications/roots/list_changed`: clear this session's
2492 /// cached `roots/list` result (if any), so the next
2493 /// [`McpContext::list_roots`] call in this session does a fresh round
2494 /// trip instead of serving stale data. Correlated purely by this
2495 /// request's own `Mcp-Session-Id` (`session_id`) — unlike
2496 /// `notifications/cancelled`, this notification carries no params of
2497 /// its own to key off of; it's about "your cache for *this connection*
2498 /// is stale," not any other request.
2499 fn invalidate_roots_cache(&self, session_id: &Option<String>) {
2500 let Some(sid) = session_id else { return };
2501 if let Some(info) = self.sessions.lock().unwrap().get_mut(sid) {
2502 info.roots = None;
2503 }
2504 }
2505
2506 /// If `body` is a JSON-RPC *response* (no `method`, by definition — see
2507 /// [`Self::handle_request_with_context`]) to a `sampling/createMessage`
2508 /// request this server sent and is still waiting on (`id` found in
2509 /// `pending_replies`), deliver it to the blocked [`McpContext::sample`]
2510 /// call and return `true`. Returns `false` for any `id` this server
2511 /// isn't tracking — the caller still needs to treat that as a genuine
2512 /// malformed/unrecognized message.
2513 fn try_deliver_sampling_response(&self, id: &str, body: &str) -> bool {
2514 let sender = match self.pending_replies.lock().unwrap().remove(id) {
2515 Some(s) => s,
2516 None => return false,
2517 };
2518 let payload = match json_rpc::extract_raw(body, "result") {
2519 Some(result) => Ok(result),
2520 None => {
2521 let message = json_rpc::extract_raw(body, "error")
2522 .and_then(|e| json_rpc::extract_str(&e, "message"))
2523 .unwrap_or_else(|| "sampling/createMessage request failed".to_string());
2524 Err(message)
2525 }
2526 };
2527 let _ = sender.send(payload); // the waiter may have already timed out and dropped rx
2528 true
2529 }
2530
2531 /// Render one JSON-RPC 2.0 response object — `{"jsonrpc":"2.0","result":...,"id":...}`
2532 /// or the `error` shape — from a dispatch result and its request's `id` (already
2533 /// rendered as a raw JSON token, e.g. `"1"`, `"\"abc\""`, or `"null"`).
2534 fn format_result(id_str: &str, result: &Result<String, (i32, String)>) -> String {
2535 match result {
2536 Ok(result_json) => format!(
2537 r#"{{"jsonrpc":"2.0","result":{result_json},"id":{id_str}}}"#
2538 ),
2539 Err((code, msg)) => {
2540 let escaped = json_escape(msg);
2541 format!(
2542 r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"{escaped}"}},"id":{id_str}}}"#
2543 )
2544 }
2545 }
2546 }
2547
2548 /// Mint a new session id, record `body`'s `params.clientInfo` under it
2549 /// (logging the caller's identity), and attach the id to `response` as
2550 /// an `Mcp-Session-Id` header. Called once, from
2551 /// [`Self::handle_request_with_context`], right after a successful
2552 /// `initialize`.
2553 fn start_session(&self, body: &str, response: &mut Response) {
2554 let params = json_rpc::extract_raw(body, "params");
2555 let client_info = params.as_deref().and_then(|p| json_rpc::extract_raw(p, "clientInfo"));
2556 let (name, version) = match &client_info {
2557 Some(info) => (
2558 json_rpc::extract_str(info, "name"),
2559 json_rpc::extract_str(info, "version"),
2560 ),
2561 None => (None, None),
2562 };
2563 let capabilities = params.as_deref().and_then(|p| json_rpc::extract_raw(p, "capabilities"));
2564 let supports_sampling = capabilities.as_deref()
2565 .and_then(|c| json_rpc::extract_raw(c, "sampling"))
2566 .is_some();
2567 let supports_roots = capabilities.as_deref()
2568 .and_then(|c| json_rpc::extract_raw(c, "roots"))
2569 .is_some();
2570
2571 eprintln!(
2572 "[mcp] initialize from client {} v{}",
2573 name.as_deref().unwrap_or("unknown"),
2574 version.as_deref().unwrap_or("unknown"),
2575 );
2576
2577 let session_id = crate::request_id::generate_request_id();
2578 self.make_room_for_a_session();
2579 self.sessions
2580 .lock()
2581 .unwrap()
2582 .insert(session_id.clone(), StoredClientInfo { last_seen: std::time::Instant::now(), protocol_version: negotiate_version(
2583 params.as_deref().and_then(|p| json_rpc::extract_str(p, "protocolVersion")).as_deref()), name, version, supports_sampling, supports_roots, roots: None });
2584
2585 response.headers.push(Header {
2586 name: "Mcp-Session-Id".into(),
2587 value: session_id.into(),
2588 });
2589 }
2590
2591 // ── method handlers ───────────────────────────────────────────────────────
2592
2593 /// Handle `initialize`. Per spec, the server must inspect the client's
2594 /// requested `protocolVersion` and respond with the version it actually
2595 /// supports — allowing the client to abort the session if incompatible —
2596 /// rather than blindly echoing `PROTOCOL_VERSION` regardless of what was
2597 /// asked for.
2598 ///
2599 /// A version in [`SUPPORTED_PROTOCOL_VERSIONS`] is confirmed; any other
2600 /// (older, newer, malformed) gets [`PROTOCOL_VERSION`], the newest. The
2601 /// session remembers the result, which decides e.g. whether JSON-RPC
2602 /// batches are accepted (only up to 2025-03-26).
2603 ///
2604 /// `clientInfo` is *not* handled here — [`Self::handle_request_with_context`]
2605 /// extracts and stores it (under a freshly minted session id) after this
2606 /// returns, so it's only ever parsed out of `body` once per call.
2607 fn do_initialize(&self, body: &str) -> Result<String, (i32, String)> {
2608 let params = json_rpc::extract_raw(body, "params");
2609
2610 let client_version = params.as_deref().and_then(|p| json_rpc::extract_str(p, "protocolVersion"));
2611
2612 let negotiated_version = negotiate_version(client_version.as_deref());
2613
2614 let logging_cap = if self.logging_enabled { r#","logging":{}"# } else { "" };
2615 // completions is advertised iff at least one .completion() has been registered —
2616 // no separate opt-in flag needed, unlike logging: if nothing was registered,
2617 // completion/complete would just return empty results for everything anyway.
2618 let completions_cap = if self.completions.read().unwrap().is_empty() { "" } else { r#","completions":{}"# };
2619 // listChanged is always true: register_tool/remove_tool (and the resource/prompt
2620 // equivalents) are always available, unlike logging which is opt-in via
2621 // .logging_enabled(). resources.subscribe is also always true now that
2622 // resources/subscribe and resources/unsubscribe are implemented (MCP_TODO.md's TODO-14).
2623 let caps = format!(
2624 r#"{{"tools":{{"listChanged":true}},"resources":{{"subscribe":true,"listChanged":true}},"prompts":{{"listChanged":true}}{logging_cap}{completions_cap}}}"#
2625 );
2626 Ok(format!(
2627 r#"{{"protocolVersion":"{}","capabilities":{caps},"serverInfo":{{"name":"{}"{}"version":"{}"{}}}}}"#,
2628 json_escape(negotiated_version),
2629 json_escape(&self.server_name),
2630 self.server_title.as_ref().map(|t| format!(r#","title":"{}","#, json_escape(t))).unwrap_or_else(|| ",".to_string()),
2631 json_escape(&self.server_version),
2632 icons_json(&self.server_icons),
2633 ))
2634 }
2635
2636 fn do_tools_list(&self, body: &str, ctx: &McpContext) -> Result<String, (i32, String)> {
2637 #[cfg_attr(not(feature = "http2"), allow(unused_mut))]
2638 let mut items: Vec<String> = self.tools.read().unwrap().iter()
2639 .filter(|t| self.tool_allowed(ctx, &t.name))
2640 .map(|t| Self::render_tool_list_entry(&t.name, &t.description, &t.input_schema, t.annotations, &t.meta))
2641 .collect();
2642
2643 #[cfg(feature = "http2")]
2644 items.extend(self.async_tools.read().unwrap().iter()
2645 .filter(|t| self.tool_allowed(ctx, &t.name))
2646 .map(|t| Self::render_tool_list_entry(&t.name, &t.description, &t.input_schema, t.annotations, &t.meta)));
2647
2648 let (page, next_cursor) = self.paginate(&items, body)?;
2649 Ok(format!(r#"{{"tools":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2650 }
2651
2652 /// Render one `tools/list` entry — shared by the sync (`tools`) and
2653 /// (with the `http2` feature) async (`async_tools`) collections, which
2654 /// are otherwise identical from the client's point of view.
2655 fn render_tool_list_entry(name: &str, description: &str, input_schema: &str, annotations: Option<ToolAnnotations>, meta: &ToolMeta) -> String {
2656 let annotations_field = match annotations {
2657 Some(a) => format!(r#","annotations":{}"#, a.to_json()),
2658 None => String::new(),
2659 };
2660 let title = meta.title.as_ref().map(|t| format!(r#","title":"{}""#, json_escape(t))).unwrap_or_default();
2661 let output_schema = meta.output_schema.as_ref().map(|schema| format!(r#","outputSchema":{schema}"#)).unwrap_or_default();
2662 format!(
2663 r#"{{"name":"{}"{title},"description":"{}","inputSchema":{}{output_schema}{}{}}}"#,
2664 json_escape(name), json_escape(description), input_schema, annotations_field, icons_json(&meta.icons),
2665 )
2666 }
2667
2668 /// Check a `tools/call`'s `arguments` against the tool's input schema:
2669 /// an object, every `required` property present, and each declared
2670 /// property of the declared `type`. Not a full JSON Schema validator —
2671 /// the checks a model's mistakes actually trip. A failure becomes a tool
2672 /// result with `isError: true` (MCP 2025-11-25, SEP-1303), so the model
2673 /// sees why and can retry, instead of a protocol error it never reads.
2674 pub(crate) fn validate_arguments(schema: &str, args: &str) -> Result<(), String> {
2675 let Some(schema) = json_rpc::object_members(schema) else { return Ok(()) };
2676 let field = |name: &str| schema.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
2677 let Some(arguments) = json_rpc::object_members(args) else {
2678 return Err("Invalid arguments: expected a JSON object".to_string());
2679 };
2680 if let Some(required) = field("required") {
2681 for name in json_rpc::split_array_elements(required) {
2682 let name = name.trim().trim_matches('"');
2683 if !arguments.iter().any(|(k, _)| k == name) {
2684 return Err(format!("Invalid arguments: missing required property \"{name}\""));
2685 }
2686 }
2687 }
2688 let Some(properties) = field("properties").and_then(json_rpc::object_members) else { return Ok(()) };
2689 for (name, value) in &arguments {
2690 let Some((_, property)) = properties.iter().find(|(k, _)| k == name) else { continue };
2691 let Some(declared) = json_rpc::object_members(property)
2692 .and_then(|p| p.into_iter().find(|(k, _)| k == "type").map(|(_, v)| v))
2693 else { continue };
2694 let allowed: Vec<String> = if declared.starts_with('[') {
2695 json_rpc::split_array_elements(&declared).iter().map(|t| t.trim().trim_matches('"').to_string()).collect()
2696 } else {
2697 vec![declared.trim_matches('"').to_string()]
2698 };
2699 let actual = json_type(value);
2700 let fits = allowed.iter().any(|t| t == actual || (t == "number" && actual == "integer"));
2701 if !fits {
2702 return Err(format!("Invalid arguments: property \"{name}\" must be {}, got {actual}", allowed.join(" or ")));
2703 }
2704 }
2705 Ok(())
2706 }
2707
2708 fn do_tools_call(&self, body: &str, ctx: McpContext) -> Result<String, (i32, String)> {
2709 let result = match self.call_tool(body, ctx)? {
2710 // Only an MCP 2026-07-28 request can carry input requests.
2711 Ok(c) if c.kind == "input_required" => Err("this tool needs input from the client, which needs MCP protocol version 2026-07-28".to_string()),
2712 other => other,
2713 };
2714 Ok(Self::format_tool_result(result))
2715 }
2716
2717 /// Run `tools/call`: the handler's result, unformatted; `Err` for a
2718 /// call that never reached a handler (unknown tool, no params).
2719 fn call_tool(&self, body: &str, ctx: McpContext) -> Result<Result<McpContent, String>, (i32, String)> {
2720 let params = json_rpc::extract_raw(body, "params")
2721 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2722 let name = json_rpc::extract_str(¶ms, "name")
2723 .ok_or((json_rpc::INVALID_PARAMS, "Missing tool name".to_string()))?;
2724 let args = json_rpc::extract_raw(¶ms, "arguments")
2725 .unwrap_or_else(|| "{}".to_string());
2726 if !self.tool_allowed(&ctx, &name) {
2727 return Err((json_rpc::INVALID_PARAMS, format!("Unknown tool: {name}")));
2728 }
2729
2730 // `_meta.progressToken` (string or number, per spec) — stored raw so
2731 // `McpContext::report_progress` can splice it back verbatim.
2732 let progress_token = json_rpc::extract_raw(¶ms, "_meta")
2733 .and_then(|meta| json_rpc::extract_raw(&meta, "progressToken"));
2734 let ctx = McpContext { progress_token, ..ctx };
2735
2736 let sync_handler = {
2737 let tools = self.tools.read().unwrap();
2738 tools.iter().find(|t| t.name == name).map(|t| (t.handler.clone(), t.input_schema.clone()))
2739 };
2740 if let Some((handler, schema)) = sync_handler {
2741 if let Err(invalid) = Self::validate_arguments(&schema, &args) {
2742 return Ok(Err(invalid));
2743 }
2744 return Ok(handler(ctx, &args));
2745 }
2746
2747 #[cfg(feature = "http2")]
2748 {
2749 let async_handler = {
2750 let async_tools = self.async_tools.read().unwrap();
2751 async_tools.iter().find(|t| t.name == name).map(|t| (t.handler.clone(), t.input_schema.clone()))
2752 };
2753 if let Some((handler, schema)) = async_handler {
2754 if let Err(invalid) = Self::validate_arguments(&schema, &args) {
2755 return Ok(Err(invalid));
2756 }
2757 let args_owned = args.clone();
2758 return Ok(crate::async_bridge::block_on_isolated(move || handler(args_owned)));
2759 }
2760 }
2761
2762 Err((json_rpc::INVALID_PARAMS, format!("Unknown tool: {name}")))
2763 }
2764
2765 /// Render a tool handler's result as the spec's `tools/call` shape —
2766 /// `{"content":[...],"isError":false}` on success, or `isError:true`
2767 /// with the error message as a text content block. Shared by the sync
2768 /// and (with `http2`) async `tools/call` dispatch paths.
2769 fn format_tool_result(result: Result<McpContent, String>) -> String {
2770 match result {
2771 Ok(c) if c.kind == "result" => c.text,
2772 Ok(c) if c.kind == "blocks" => format!(r#"{{"content":[{}],"isError":false}}"#, c.text),
2773 Ok(c) if c.kind == "structured" => format!(
2774 r#"{{"content":[{{"type":"text","text":"{}"}}],"structuredContent":{},"isError":false}}"#,
2775 json_escape(&c.text),
2776 c.text,
2777 ),
2778 Ok(c) => format!(
2779 r#"{{"content":[{}],"isError":false}}"#,
2780 c.to_content_json(),
2781 ),
2782 Err(e) => {
2783 let escaped = json_escape(&e);
2784 format!(
2785 r#"{{"content":[{{"type":"text","text":"{escaped}"}}],"isError":true}}"#
2786 )
2787 }
2788 }
2789 }
2790
2791 fn do_resources_list(&self, body: &str) -> Result<String, (i32, String)> {
2792 let items: Vec<String> = self.resources.read().unwrap().iter().filter(|r| !r.uri_template.contains('{')).map(|r| {
2793 format!(
2794 r#"{{"uri":"{}","name":"{}","description":"{}","mimeType":"text/plain"}}"#,
2795 json_escape(&r.uri_template),
2796 json_escape(&r.name),
2797 json_escape(&r.description),
2798 )
2799 }).collect();
2800 let (page, next_cursor) = self.paginate(&items, body)?;
2801 Ok(format!(r#"{{"resources":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2802 }
2803
2804 /// `resources/templates/list`: the resources registered with a URI
2805 /// template (`{...}` placeholders), which `resources/list` leaves out.
2806 fn do_resource_templates_list(&self, body: &str) -> Result<String, (i32, String)> {
2807 let items: Vec<String> = self.resources.read().unwrap().iter().filter(|r| r.uri_template.contains('{')).map(|r| {
2808 format!(
2809 r#"{{"uriTemplate":"{}","name":"{}","description":"{}","mimeType":"text/plain"}}"#,
2810 json_escape(&r.uri_template),
2811 json_escape(&r.name),
2812 json_escape(&r.description),
2813 )
2814 }).collect();
2815 let (page, next_cursor) = self.paginate(&items, body)?;
2816 Ok(format!(r#"{{"resourceTemplates":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2817 }
2818
2819 fn do_resources_read(&self, body: &str) -> Result<String, (i32, String)> {
2820 let params = json_rpc::extract_raw(body, "params")
2821 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2822 let uri = json_rpc::extract_str(¶ms, "uri")
2823 .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2824
2825 let handler = {
2826 let resources = self.resources.read().unwrap();
2827 resources.iter().find(|r| uri_matches(&r.uri_template, &uri)).map(|r| r.handler.clone())
2828 }.ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Resource not found: {uri}")))?;
2829
2830 match handler(&uri) {
2831 Ok(c) => {
2832 let text_esc = json_escape(&c.text);
2833 let uri_esc = json_escape(&uri);
2834 let field = if c.kind == "blob" { "blob" } else { "text" };
2835 Ok(format!(
2836 r#"{{"contents":[{{"uri":"{uri_esc}","mimeType":"{}","{field}":"{text_esc}"}}]}}"#,
2837 json_escape(c.mime()),
2838 ))
2839 }
2840 Err(e) => Err((json_rpc::INVALID_PARAMS, e)),
2841 }
2842 }
2843
2844 /// Handle `resources/subscribe`: record that `session_id` (this
2845 /// request's `Mcp-Session-Id`) wants `notifications/resources/updated`
2846 /// pushed whenever [`Self::notify_resource_updated`] is called for
2847 /// `params.uri`. Requires a session id — without one there's no way to
2848 /// later match this subscription to a specific `GET /mcp` SSE
2849 /// connection, so a client that never sent `Mcp-Session-Id` gets
2850 /// `INVALID_PARAMS` rather than a subscription that can never fire.
2851 fn do_resource_subscribe(&self, body: &str, session_id: Option<String>) -> Result<String, (i32, String)> {
2852 let params = json_rpc::extract_raw(body, "params")
2853 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2854 let uri = json_rpc::extract_str(¶ms, "uri")
2855 .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2856 let session_id = session_id.ok_or((
2857 json_rpc::INVALID_PARAMS,
2858 "resources/subscribe requires an Mcp-Session-Id header (call initialize first)".to_string(),
2859 ))?;
2860
2861 let mut subs = self.subscriptions.lock().unwrap();
2862 let subscribers = subs.entry(uri).or_default();
2863 if !subscribers.contains(&session_id) {
2864 subscribers.push(session_id);
2865 }
2866 Ok("{}".to_string())
2867 }
2868
2869 /// Handle `resources/unsubscribe`: the inverse of
2870 /// [`Self::do_resource_subscribe`]. Removing the last subscriber for a
2871 /// URI drops the URI's entry entirely rather than leaving an empty
2872 /// `Vec` behind.
2873 fn do_resource_unsubscribe(&self, body: &str, session_id: Option<String>) -> Result<String, (i32, String)> {
2874 let params = json_rpc::extract_raw(body, "params")
2875 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2876 let uri = json_rpc::extract_str(¶ms, "uri")
2877 .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2878 let session_id = session_id.ok_or((
2879 json_rpc::INVALID_PARAMS,
2880 "resources/unsubscribe requires an Mcp-Session-Id header".to_string(),
2881 ))?;
2882
2883 let mut subs = self.subscriptions.lock().unwrap();
2884 if let Some(subscribers) = subs.get_mut(&uri) {
2885 subscribers.retain(|s| s != &session_id);
2886 if subscribers.is_empty() {
2887 subs.remove(&uri);
2888 }
2889 }
2890 Ok("{}".to_string())
2891 }
2892
2893 fn do_prompts_list(&self, body: &str) -> Result<String, (i32, String)> {
2894 let items: Vec<String> = self.prompts.read().unwrap().iter().map(|p| {
2895 let arg_defs: Vec<String> = p.arguments.iter().map(|a| {
2896 format!(
2897 r#"{{"name":"{}","description":"{}","required":{}}}"#,
2898 json_escape(&a.name),
2899 json_escape(&a.description),
2900 a.required,
2901 )
2902 }).collect();
2903 format!(
2904 r#"{{"name":"{}","description":"{}","arguments":[{}]}}"#,
2905 json_escape(&p.name),
2906 json_escape(&p.description),
2907 arg_defs.join(","),
2908 )
2909 }).collect();
2910 let (page, next_cursor) = self.paginate(&items, body)?;
2911 Ok(format!(r#"{{"prompts":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2912 }
2913
2914 /// Slice `items` (already-rendered JSON object strings for one
2915 /// `*/list` response) according to [`Self::page_size`] and this
2916 /// request's `params.cursor`, returning the page and — if more items
2917 /// remain — the opaque `nextCursor` to embed in the response.
2918 ///
2919 /// Without a configured `page_size`, always returns every item and no
2920 /// cursor, i.e. pagination is fully opt-in.
2921 fn paginate<'a>(&self, items: &'a [String], body: &str) -> Result<(&'a [String], Option<String>), (i32, String)> {
2922 let page_size = match self.page_size {
2923 Some(n) => n,
2924 None => return Ok((items, None)),
2925 };
2926
2927 let cursor = json_rpc::extract_raw(body, "params")
2928 .and_then(|p| json_rpc::extract_str(&p, "cursor"));
2929
2930 let offset = match cursor {
2931 Some(c) => decode_cursor(&c)
2932 .ok_or((json_rpc::INVALID_PARAMS, "Invalid cursor".to_string()))?,
2933 None => 0,
2934 };
2935
2936 if offset >= items.len() {
2937 return Ok((&[], None));
2938 }
2939
2940 let end = (offset + page_size).min(items.len());
2941 let next_cursor = if end < items.len() { Some(encode_cursor(end)) } else { None };
2942 Ok((&items[offset..end], next_cursor))
2943 }
2944
2945 fn do_prompts_get(&self, body: &str, ctx: McpContext) -> Result<String, (i32, String)> {
2946 match self.get_prompt(body, ctx)? {
2947 (description, PromptReply::Messages(msgs)) => {
2948 let msg_jsons: Vec<String> = msgs.iter().map(|m| m.to_json()).collect();
2949 Ok(format!(r#"{{"description":"{}","messages":[{}]}}"#, json_escape(&description), msg_jsons.join(",")))
2950 }
2951 (_, PromptReply::InputRequired(_)) => Err((
2952 json_rpc::INVALID_PARAMS,
2953 "this prompt needs input from the client, which needs MCP protocol version 2026-07-28".to_string(),
2954 )),
2955 }
2956 }
2957
2958 /// Run `prompts/get`: the prompt's description and the handler's reply.
2959 fn get_prompt(&self, body: &str, ctx: McpContext) -> Result<(String, PromptReply), (i32, String)> {
2960 let params = json_rpc::extract_raw(body, "params")
2961 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2962 let name = json_rpc::extract_str(¶ms, "name")
2963 .ok_or((json_rpc::INVALID_PARAMS, "Missing prompt name".to_string()))?;
2964 let args = json_rpc::extract_raw(¶ms, "arguments")
2965 .unwrap_or_else(|| "{}".to_string());
2966
2967 let (description, handler) = {
2968 let prompts = self.prompts.read().unwrap();
2969 prompts.iter().find(|p| p.name == name).map(|p| (p.description.clone(), p.handler.clone()))
2970 }.ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Unknown prompt: {name}")))?;
2971
2972 handler(ctx, &args).map(|reply| (description, reply)).map_err(|e| (json_rpc::INVALID_PARAMS, e))
2973 }
2974
2975 /// Handle `completion/complete`: look up the registered
2976 /// [`CompletionDef`] matching `params.ref.type`/`params.ref.name`, call
2977 /// its handler with `params.argument.name`/`params.argument.value`, and
2978 /// render the spec's `{"completion":{"values":[...],"hasMore":...,
2979 /// "total":...}}` shape. No registered provider for the given ref/name
2980 /// (or an unrecognized `ref.type` not stripped of `"ref/"`) returns an
2981 /// empty `values` list rather than an error — matching the spec's own
2982 /// framing of completion as a best-effort hint, not a required capability
2983 /// per tool/prompt.
2984 fn do_completion(&self, body: &str) -> Result<String, (i32, String)> {
2985 let params = json_rpc::extract_raw(body, "params")
2986 .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2987 let reference = json_rpc::extract_raw(¶ms, "ref")
2988 .ok_or((json_rpc::INVALID_PARAMS, "Missing ref".to_string()))?;
2989 let ref_type_raw = json_rpc::extract_str(&reference, "type")
2990 .ok_or((json_rpc::INVALID_PARAMS, "Missing ref.type".to_string()))?;
2991 let ref_type = ref_type_raw.strip_prefix("ref/").unwrap_or(&ref_type_raw);
2992 let ref_name = json_rpc::extract_str(&reference, "name")
2993 .ok_or((json_rpc::INVALID_PARAMS, "Missing ref.name".to_string()))?;
2994
2995 let argument = json_rpc::extract_raw(¶ms, "argument")
2996 .ok_or((json_rpc::INVALID_PARAMS, "Missing argument".to_string()))?;
2997 let arg_name = json_rpc::extract_str(&argument, "name")
2998 .ok_or((json_rpc::INVALID_PARAMS, "Missing argument.name".to_string()))?;
2999 let partial = json_rpc::extract_str(&argument, "value").unwrap_or_default();
3000
3001 let handler = {
3002 let completions = self.completions.read().unwrap();
3003 completions.iter()
3004 .find(|c| c.ref_type == ref_type && c.ref_name == ref_name)
3005 .map(|c| c.handler.clone())
3006 };
3007
3008 let values = match handler {
3009 Some(h) => h(&arg_name, &partial).map_err(|e| (json_rpc::INVALID_PARAMS, e))?,
3010 None => vec![],
3011 };
3012
3013 let total = values.len();
3014 let has_more = total > MAX_COMPLETION_VALUES;
3015 let page = if has_more { &values[..MAX_COMPLETION_VALUES] } else { &values[..] };
3016 let values_json: Vec<String> = page.iter().map(|v| format!(r#""{}""#, json_escape(v))).collect();
3017
3018 Ok(format!(
3019 r#"{{"completion":{{"values":[{}],"hasMore":{has_more},"total":{total}}}}}"#,
3020 values_json.join(","),
3021 ))
3022 }
3023
3024 /// Answers a `tools/call` as an SSE stream (Streamable HTTP): the
3025 /// handler runs on its own thread, its progress notifications go out as
3026 /// they happen, then the JSON-RPC response, and the stream ends.
3027 fn stream_tool_call(&self, body: &str, mut ctx: McpContext) -> Response {
3028 let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(32);
3029 ctx.request_stream = Some(tx.clone());
3030 let server = self.clone();
3031 let body = body.to_string();
3032 std::thread::spawn(move || {
3033 let response = server.handle_request_with_context(&body, ctx);
3034 let json = response.content_range_list.first().map(|part| String::from_utf8_lossy(&part.body).into_owned()).unwrap_or_default();
3035 let _ = tx.send(format!("data: {json}\n\n").into_bytes());
3036 });
3037 let mut response = Response::new();
3038 response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
3039 response.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
3040 response.headers.push(Header { name: Header::_CONTENT_TYPE.into(), value: "text/event-stream".into() });
3041 response.headers.push(Header { name: Header::_CACHE_CONTROL.into(), value: "no-cache".into() });
3042 response.headers.push(Header { name: "X-Accel-Buffering".into(), value: "no".into() });
3043 response.stream_pipe = Some(Box::new(crate::sse::SseReader::new(rx, SSE_KEEPALIVE_INTERVAL)));
3044 response
3045 }
3046
3047 /// Build the [`McpContext`] for an incoming request: the `Mcp-Session-Id`
3048 /// header, if present, plus whatever `clientInfo` was recorded for that
3049 /// session at `initialize` time (if this session is recognized).
3050 fn context_for(&self, request: &Request) -> McpContext {
3051 let session_id = request
3052 .get_header("Mcp-Session-Id".to_string())
3053 .map(|h| h.value.to_string());
3054
3055 let (client_name, client_version, sampling_supported, roots_supported) = match &session_id {
3056 Some(sid) => match self.sessions.lock().unwrap().get(sid) {
3057 Some(info) => (info.name.clone(), info.version.clone(), info.supports_sampling, info.supports_roots),
3058 None => (None, None, false, false),
3059 },
3060 None => (None, None, false, false),
3061 };
3062
3063 McpContext {
3064 client_name,
3065 client_version,
3066 session_id,
3067 auth_claims: None,
3068 progress_token: None,
3069 sse_clients: Some(self.sse_clients.clone()),
3070 cancellation: None,
3071 sampling_supported,
3072 pending_replies: Some(self.pending_replies.clone()),
3073 roots_supported,
3074 sessions: Some(self.sessions.clone()),
3075 request_stream: None,
3076 modern: None,
3077 tasks: None,
3078 }
3079 }
3080}
3081
3082/// Render one JSON-RPC 2.0 notification (no `id` — fire-and-forget, per
3083/// spec) as an SSE `data:`-ready message body. Shared by [`McpServer::notify`]
3084/// and [`McpContext::report_progress`].
3085/// A single `tools/call` POST that asks for progress (`_meta.progressToken`)
3086/// from a client that accepts an SSE response.
3087fn wants_progress_stream(request: &Request, body: &str) -> bool {
3088 let accepts_sse = request.headers.iter()
3089 .filter(|h| h.name.eq_ignore_ascii_case("accept"))
3090 .any(|h| h.value.to_ascii_lowercase().contains("text/event-stream"));
3091 if !accepts_sse || body.trim_start().starts_with('[') {
3092 return false;
3093 }
3094 let Some(members) = json_rpc::object_members(body) else { return false };
3095 let member = |key: &str| members.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str());
3096 member("method") == Some(r#""tools/call""#)
3097 && member("id").is_some()
3098 && member("params")
3099 .and_then(json_rpc::object_members)
3100 .and_then(|params| params.into_iter().find(|(k, _)| k == "_meta"))
3101 .and_then(|(_, meta)| json_rpc::object_members(&meta))
3102 .is_some_and(|meta| meta.iter().any(|(k, _)| k == "progressToken"))
3103}
3104
3105fn render_notification(method: &str, params_json: Option<&str>) -> String {
3106 let params_field = match params_json {
3107 Some(p) => format!(r#","params":{p}"#),
3108 None => String::new(),
3109 };
3110 format!(r#"{{"jsonrpc":"2.0","method":"{}"{}}}"#, json_escape(method), params_field)
3111}
3112
3113/// Send a raw pre-built JSON-RPC message to every client in `clients`,
3114/// pruning any whose channel is full or disconnected. Shared by
3115/// [`McpServer::notify`] and [`McpContext::report_progress`] — the latter
3116/// only has a clone of the broadcast list, not a whole `McpServer`.
3117fn broadcast_sse_to(clients: &Arc<Mutex<Vec<SseClient>>>, json: &str) {
3118 let frame = format!("data: {json}\n\n").into_bytes();
3119 let mut clients = clients.lock().unwrap();
3120 clients.retain(|c| c.sender.try_send(frame.clone()).is_ok());
3121}
3122
3123/// Send a raw pre-built JSON-RPC message only to clients whose `session_id`
3124/// is in `session_ids`, pruning any of *those* whose channel is full or
3125/// disconnected. A client with no `session_id`, or one not in
3126/// `session_ids`, is left untouched (kept, not sent to) — this is a
3127/// targeted send for [`McpServer::notify_resource_updated`], not a
3128/// broadcast like [`broadcast_sse_to`].
3129/// Sends `json` to every SSE stream of `session_ids`; returns how many took it.
3130fn send_sse_to_sessions(clients: &Arc<Mutex<Vec<SseClient>>>, session_ids: &[String], json: &str) -> usize {
3131 let frame = format!("data: {json}\n\n").into_bytes();
3132 let mut clients = clients.lock().unwrap();
3133 let mut delivered = 0;
3134 clients.retain(|c| {
3135 let is_target = c.session_id.as_deref().is_some_and(|sid| session_ids.iter().any(|s| s == sid));
3136 if is_target {
3137 let sent = c.sender.try_send(frame.clone()).is_ok();
3138 delivered += sent as usize;
3139 sent
3140 } else {
3141 true
3142 }
3143 });
3144 delivered
3145}
3146
3147/// How often a server-to-client request checks for the session's SSE stream
3148/// while waiting for the client to open it.
3149const SSE_STREAM_WAIT_POLL: Duration = Duration::from_millis(20);
3150
3151// ── Application ───────────────────────────────────────────────────────────────
3152
3153impl Application for McpServer {
3154 fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
3155 // RFC 9728 protected-resource metadata (MCP 2025-06-18), at the
3156 // well-known path and at it suffixed with the endpoint's path.
3157 #[cfg(feature = "sso")]
3158 if request.method == "GET" {
3159 if let Some(oauth) = &self.oauth {
3160 let target = request.request_uri.split('?').next().unwrap_or("");
3161 let suffixed = format!("{}{}", PROTECTED_RESOURCE_PATH, self.path);
3162 if target == PROTECTED_RESOURCE_PATH || target == suffixed {
3163 return Ok(protected_resource_document(oauth, request, &self.path));
3164 }
3165 }
3166 }
3167
3168 if request.request_uri == self.path {
3169 // Browser requests (they carry `Origin`) only from listed origins.
3170 if let Some(origin) = request.headers.iter().find(|h| h.name.eq_ignore_ascii_case("origin")) {
3171 let origin = origin.value.trim();
3172 if !self.allowed_origins.iter().any(|o| o.trim_end_matches('/').eq_ignore_ascii_case(origin.trim_end_matches('/'))) {
3173 return Ok(forbidden_origin());
3174 }
3175 }
3176 // JSON-RPC bodies only: a form or text/plain POST is what a web
3177 // page can send cross-site without a CORS preflight.
3178 if request.method == "POST" {
3179 let content_type = request.headers.iter()
3180 .find(|h| h.name.eq_ignore_ascii_case("content-type"))
3181 .map(|h| h.value.as_ref())
3182 .unwrap_or("");
3183 let media_type = content_type.split(';').next().unwrap_or("").trim();
3184 if !media_type.eq_ignore_ascii_case("application/json") {
3185 return Ok(unsupported_media_type());
3186 }
3187 }
3188
3189 #[cfg_attr(not(feature = "sso"), allow(unused_mut))]
3190 let mut auth_claims_json: Option<String> = None;
3191 #[cfg(feature = "sso")]
3192 let oauth_configured = self.oauth.is_some();
3193 #[cfg(not(feature = "sso"))]
3194 let oauth_configured = false;
3195
3196 // OAuth (sso feature) takes precedence over bearer tokens if both
3197 // are somehow configured — see require_oauth's doc comment.
3198 #[cfg(feature = "sso")]
3199 if let Some(oauth) = &self.oauth {
3200 let provided = request.headers.iter()
3201 .find(|h| h.name.eq_ignore_ascii_case("authorization"))
3202 .map(|h| h.value.as_ref())
3203 .unwrap_or("");
3204 let bearer = provided.strip_prefix("Bearer ").unwrap_or("");
3205 if bearer.is_empty() {
3206 return Ok(unauthorized_with_metadata(oauth, request, &self.path));
3207 }
3208 let opts = crate::sso::jwks::VerifyOptions {
3209 audience: &oauth.audience,
3210 issuer: &oauth.provider.issuer,
3211 leeway_secs: 60,
3212 };
3213 match oauth.jwks.verify_jwt(bearer, &opts) {
3214 Ok(claims) => auth_claims_json = serde_json::to_string(&claims).ok(),
3215 Err(_) => return Ok(unauthorized_with_metadata(oauth, request, &self.path)),
3216 }
3217 }
3218 if !oauth_configured {
3219 match self.check_bearer(request) {
3220 Ok(claims) => auth_claims_json = claims,
3221 Err(response) => return Ok(response),
3222 }
3223 }
3224
3225 // MCP 2026-07-28: stateless, every request self-contained (no
3226 // session lookup, `Mcp-Session-Id` ignored).
3227 if request.method == "POST" {
3228 let body = std::str::from_utf8(&request.body).unwrap_or("");
3229 if modern::is_modern(request, body) {
3230 let mut ctx = self.context_for(request);
3231 ctx.session_id = None;
3232 ctx.client_name = None;
3233 ctx.client_version = None;
3234 ctx.auth_claims = auth_claims_json;
3235 return Ok(self.handle_modern(request, body, ctx));
3236 }
3237 }
3238
3239 // A session id this server doesn't know — never minted, ended,
3240 // or evicted — is 404: the client must initialize again
3241 // (Streamable HTTP transport). An `initialize` POST may carry a
3242 // stale one.
3243 let session_id = request.headers.iter()
3244 .find(|h| h.name.eq_ignore_ascii_case("mcp-session-id"))
3245 .map(|h| h.value.to_string());
3246 if let Some(sid) = &session_id {
3247 let initializing = request.method == "POST"
3248 && json_rpc::extract_str(std::str::from_utf8(&request.body).unwrap_or(""), "method").as_deref() == Some("initialize");
3249 if request.method != "OPTIONS" && !initializing && !self.touch_session(sid) {
3250 return Ok(session_not_found());
3251 }
3252 }
3253 // The protocol version in effect: the header (2025-06-18+
3254 // clients send it on every request after initialize), else the
3255 // session's, else 2025-03-26. A version this server doesn't speak
3256 // is 400 (Streamable HTTP transport).
3257 let header_version = request.headers.iter()
3258 .find(|h| h.name.eq_ignore_ascii_case("mcp-protocol-version"))
3259 .map(|h| h.value.trim().to_string());
3260 if let Some(v) = &header_version {
3261 if !SUPPORTED_PROTOCOL_VERSIONS.contains(&v.as_str()) {
3262 return Ok(bad_protocol_version(v));
3263 }
3264 }
3265 if request.method == "POST" && request.body.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'[') {
3266 let version = header_version.clone()
3267 .or_else(|| session_id.as_ref().and_then(|sid| self.sessions.lock().unwrap().get(sid).map(|s| s.protocol_version.to_string())))
3268 .unwrap_or_else(|| ASSUMED_PROTOCOL_VERSION.to_string());
3269 // JSON-RPC batching was removed in 2025-06-18.
3270 if version.as_str() >= "2025-06-18" {
3271 return Ok(rpc_error(None, json_rpc::INVALID_REQUEST,
3272 &format!("JSON-RPC batches are not supported in protocol version {version}")));
3273 }
3274 }
3275 return Ok(match request.method.as_str() {
3276 "DELETE" => match session_id {
3277 // The client ends its session.
3278 Some(sid) => {
3279 self.sessions.lock().unwrap().remove(&sid);
3280 self.forget_sessions(&[sid]);
3281 let mut r = Response::new();
3282 r.status_code = *STATUS_CODE_REASON_PHRASE.n204_no_content.status_code;
3283 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content.reason_phrase.to_string();
3284 r
3285 }
3286 None => {
3287 let mut r = Response::new();
3288 r.status_code = *STATUS_CODE_REASON_PHRASE.n400_bad_request.status_code;
3289 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n400_bad_request.reason_phrase.to_string();
3290 r.content_range_list = vec![Range::get_content_range(
3291 b"DELETE /mcp needs an Mcp-Session-Id".to_vec(),
3292 MimeType::TEXT_PLAIN.to_string(),
3293 )];
3294 r
3295 }
3296 },
3297 "POST" => {
3298 let body = std::str::from_utf8(&request.body).unwrap_or("");
3299 let mut ctx = self.context_for(request);
3300 ctx.auth_claims = auth_claims_json;
3301 if wants_progress_stream(request, body) {
3302 self.stream_tool_call(body, ctx)
3303 } else {
3304 self.handle_request_with_context(body, ctx)
3305 }
3306 }
3307 "GET" => self.start_sse_stream(request),
3308 "OPTIONS" => {
3309 // CORS preflight for browser-based MCP clients
3310 let mut r = Response::new();
3311 r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
3312 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
3313 r.headers.push(Header {
3314 name: "Allow".into(),
3315 value: "GET, POST, DELETE, OPTIONS".into(),
3316 });
3317 r
3318 }
3319 _ => {
3320 let mut r = Response::new();
3321 r.status_code = *STATUS_CODE_REASON_PHRASE.n405_method_not_allowed.status_code;
3322 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n405_method_not_allowed.reason_phrase.to_string();
3323 r.headers.push(Header {
3324 name: "Allow".into(),
3325 value: "GET, POST, DELETE, OPTIONS".into(),
3326 });
3327 r.content_range_list = vec![Range::get_content_range(
3328 b"MCP endpoint only accepts GET (SSE), POST or DELETE".to_vec(),
3329 MimeType::TEXT_PLAIN.to_string(),
3330 )];
3331 r
3332 }
3333 });
3334 }
3335
3336 // Not an MCP path — fall through to the wrapped app (or built-in App).
3337 match &self.fallback {
3338 Some(app) => app.execute(request, connection),
3339 None => App::new().execute(request, connection),
3340 }
3341 }
3342
3343 /// MCP calls run tool handlers (user code): never inline. Other requests
3344 /// go to the fallback app, which decides.
3345 fn runs_inline(&self, request: &Request, connection: &ConnectionInfo) -> bool {
3346 if request.request_uri == self.path || request.request_uri.starts_with("/.well-known/") {
3347 return false;
3348 }
3349 match &self.fallback {
3350 Some(app) => app.runs_inline(request, connection),
3351 None => App::is_inline_request(request),
3352 }
3353 }
3354
3355 /// MCP requests are JSON-RPC read whole; other paths: the wrapped app.
3356 fn streams_body(&self, request: &Request, connection: &ConnectionInfo) -> bool {
3357 if request.request_uri == self.path || request.request_uri.starts_with("/.well-known/") {
3358 return false;
3359 }
3360 self.fallback.as_ref().is_some_and(|app| app.streams_body(request, connection))
3361 }
3362
3363 #[cfg(feature = "http2")]
3364 fn execute_async<'a>(&'a self, request: &'a Request, connection: &'a ConnectionInfo) -> Option<crate::application::AsyncResponse<'a>> {
3365 if request.request_uri == self.path || request.request_uri.starts_with("/.well-known/") {
3366 return None;
3367 }
3368 self.fallback.as_ref()?.execute_async(request, connection)
3369 }
3370}
3371
3372// ── public helper ─────────────────────────────────────────────────────────────
3373
3374/// Extract an argument from a tool/prompt `arguments` JSON object: a
3375/// string's value, or a number's or boolean's literal text (`"3"`,
3376/// `"true"`). Objects, arrays and `null` are `None`. Numbers and booleans
3377/// used to be `None` too, so a tool reading `"enabled": true` saw nothing.
3378///
3379/// ```rust
3380/// use rust_web_server::mcp::extract_arg;
3381/// assert_eq!(extract_arg(r#"{"text":"hello"}"#, "text").as_deref(), Some("hello"));
3382/// assert_eq!(extract_arg(r#"{"enabled":true,"n":3}"#, "enabled").as_deref(), Some("true"));
3383/// assert_eq!(extract_arg(r#"{"enabled":true,"n":3}"#, "n").as_deref(), Some("3"));
3384/// assert_eq!(extract_arg(r#"{}"#, "missing"), None);
3385/// ```
3386pub fn extract_arg(arguments: &str, name: &str) -> Option<String> {
3387 if let Some(members) = json_rpc::object_members(arguments) {
3388 let (_, raw) = members.into_iter().find(|(key, _)| key == name)?;
3389 return match raw.as_bytes().first() {
3390 Some(b'"') => json_rpc::extract_str(&format!(r#"{{"v":{raw}}}"#), "v"),
3391 Some(b'{' | b'[') | None => None,
3392 _ if raw == "null" => None,
3393 _ => Some(raw),
3394 };
3395 }
3396 json_rpc::extract_str(arguments, name)
3397}
3398
3399// ── internal helpers ──────────────────────────────────────────────────────────
3400
3401fn json_response(body: &str) -> Response {
3402 let mut r = Response::new();
3403 r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
3404 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
3405 r.content_range_list = vec![Range::get_content_range(
3406 body.as_bytes().to_vec(),
3407 MimeType::APPLICATION_JSON.to_string(),
3408 )];
3409 r
3410}
3411
3412fn no_content() -> Response {
3413 let mut r = Response::new();
3414 r.status_code = *STATUS_CODE_REASON_PHRASE.n202_accepted.status_code;
3415 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n202_accepted.reason_phrase.to_string();
3416 r
3417}
3418
3419/// A configured static token against the presented one: never matches an
3420/// empty token (fails closed), compared in constant time.
3421fn bearer_matches(expected: &str, provided: &str) -> bool {
3422 !expected.is_empty() && crate::proxy_config::constant_time_eq(expected.as_bytes(), provided.as_bytes())
3423}
3424
3425/// `403` for a browser `Origin` not in [`McpServer::allowed_origins`].
3426fn forbidden_origin() -> Response {
3427 let mut r = Response::new();
3428 r.status_code = *STATUS_CODE_REASON_PHRASE.n403_forbidden.status_code;
3429 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n403_forbidden.reason_phrase.to_string();
3430 r.content_range_list = vec![Range::get_content_range(
3431 b"Origin not allowed".to_vec(),
3432 MimeType::TEXT_PLAIN.to_string(),
3433 )];
3434 r
3435}
3436
3437/// `415` for a POST whose body isn't `application/json`.
3438fn unsupported_media_type() -> Response {
3439 let mut r = Response::new();
3440 r.status_code = *STATUS_CODE_REASON_PHRASE.n415_unsupported_media_type.status_code;
3441 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n415_unsupported_media_type.reason_phrase.to_string();
3442 r.content_range_list = vec![Range::get_content_range(
3443 b"MCP requests must be application/json".to_vec(),
3444 MimeType::TEXT_PLAIN.to_string(),
3445 )];
3446 r
3447}
3448
3449/// `400` for an `MCP-Protocol-Version` this server doesn't speak.
3450fn bad_protocol_version(version: &str) -> Response {
3451 let mut r = Response::new();
3452 r.status_code = *STATUS_CODE_REASON_PHRASE.n400_bad_request.status_code;
3453 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n400_bad_request.reason_phrase.to_string();
3454 r.content_range_list = vec![Range::get_content_range(
3455 format!("Unsupported MCP-Protocol-Version {:?}; supported: {}", version, SUPPORTED_PROTOCOL_VERSIONS.join(", ")).into_bytes(),
3456 MimeType::TEXT_PLAIN.to_string(),
3457 )];
3458 r
3459}
3460
3461/// `404` for a request in a session this server doesn't know (anymore).
3462fn session_not_found() -> Response {
3463 let mut r = Response::new();
3464 r.status_code = *STATUS_CODE_REASON_PHRASE.n404_not_found.status_code;
3465 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n404_not_found.reason_phrase.to_string();
3466 r.content_range_list = vec![Range::get_content_range(
3467 br#"{"jsonrpc":"2.0","error":{"code":-32001,"message":"Session not found: initialize a new one"},"id":null}"#.to_vec(),
3468 MimeType::APPLICATION_JSON.to_string(),
3469 )];
3470 r
3471}
3472
3473fn unauthorized() -> Response {
3474 let mut r = Response::new();
3475 r.status_code = *STATUS_CODE_REASON_PHRASE.n401_unauthorized.status_code;
3476 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n401_unauthorized.reason_phrase.to_string();
3477 r.headers.push(Header {
3478 name: "WWW-Authenticate".into(),
3479 value: "Bearer".into(),
3480 });
3481 r.content_range_list = vec![Range::get_content_range(
3482 b"Unauthorized".to_vec(),
3483 MimeType::TEXT_PLAIN.to_string(),
3484 )];
3485 r
3486}
3487
3488/// RFC 9728's well-known path for protected-resource metadata.
3489#[cfg(feature = "sso")]
3490const PROTECTED_RESOURCE_PATH: &str = "/.well-known/oauth-protected-resource";
3491
3492/// The protected resource's identifier: the configured audience when it is
3493/// an absolute URL (RFC 8707 — the value tokens are minted for), else this
3494/// server's origin from the request plus the MCP path.
3495#[cfg(feature = "sso")]
3496fn resource_identifier(oauth: &OAuthConfig, request: &Request, path: &str) -> String {
3497 if oauth.audience.starts_with("https://") || oauth.audience.starts_with("http://") {
3498 return oauth.audience.clone();
3499 }
3500 format!("{}{}", request_origin(request), path)
3501}
3502
3503/// `scheme://host` this request was sent to (`Host`; `https` unless the
3504/// host is a loopback name).
3505#[cfg(feature = "sso")]
3506fn request_origin(request: &Request) -> String {
3507 let host = request.headers.iter()
3508 .find(|h| h.name.eq_ignore_ascii_case("host"))
3509 .map(|h| h.value.to_string())
3510 .unwrap_or_else(|| "localhost".to_string());
3511 let local = host.starts_with("localhost") || host.starts_with("127.") || host.starts_with("[::1]");
3512 format!("{}://{}", if local { "http" } else { "https" }, host)
3513}
3514
3515/// The metadata document's URL, for `WWW-Authenticate`.
3516#[cfg(feature = "sso")]
3517fn metadata_url(oauth: &OAuthConfig, request: &Request, path: &str) -> String {
3518 let resource = resource_identifier(oauth, request, path);
3519 let origin = match resource.find("://").and_then(|i| resource[i + 3..].find('/').map(|j| i + 3 + j)) {
3520 Some(end) => resource[..end].to_string(),
3521 None => resource,
3522 };
3523 format!("{origin}{PROTECTED_RESOURCE_PATH}")
3524}
3525
3526/// `GET /.well-known/oauth-protected-resource` (RFC 9728): which
3527/// authorization server issues tokens for this MCP server, and the resource
3528/// identifier a client asks it for (RFC 8707). Served whenever
3529/// [`McpServer::require_oauth`] is configured; it replaced the
3530/// authorization-server-style document earlier versions served.
3531#[cfg(feature = "sso")]
3532fn protected_resource_document(oauth: &OAuthConfig, request: &Request, path: &str) -> Response {
3533 let body = format!(
3534 r#"{{"resource":"{}","authorization_servers":["{}"],"bearer_methods_supported":["header"]}}"#,
3535 json_escape(&resource_identifier(oauth, request, path)),
3536 json_escape(&oauth.provider.issuer),
3537 );
3538 let mut r = Response::new();
3539 r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
3540 r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
3541 r.content_range_list = vec![Range::get_content_range(
3542 body.into_bytes(),
3543 MimeType::APPLICATION_JSON.to_string(),
3544 )];
3545 r
3546}
3547
3548/// `401` whose `WWW-Authenticate` points at the protected-resource
3549/// metadata, so a client can discover the authorization server.
3550#[cfg(feature = "sso")]
3551fn unauthorized_with_metadata(oauth: &OAuthConfig, request: &Request, path: &str) -> Response {
3552 let mut r = unauthorized();
3553 if let Some(header) = r.headers.iter_mut().find(|h| h.name.eq_ignore_ascii_case("www-authenticate")) {
3554 header.value = format!(r#"Bearer resource_metadata="{}""#, metadata_url(oauth, request, path)).into();
3555 }
3556 r
3557}
3558
3559fn rpc_error(id: Option<&str>, code: i32, message: &str) -> Response {
3560 let id_str = id.unwrap_or("null");
3561 let escaped = json_escape(message);
3562 json_response(&format!(
3563 r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"{escaped}"}},"id":{id_str}}}"#
3564 ))
3565}
3566
3567/// The JSON Schema type of a raw JSON value (`integer` for whole numbers).
3568fn json_type(raw: &str) -> &'static str {
3569 let raw = raw.trim();
3570 match raw.as_bytes().first() {
3571 Some(b'"') => "string",
3572 Some(b'{') => "object",
3573 Some(b'[') => "array",
3574 Some(b't' | b'f') => "boolean",
3575 Some(b'n') => "null",
3576 _ if raw.bytes().all(|b| b.is_ascii_digit() || b == b'-') => "integer",
3577 _ => "number",
3578 }
3579}
3580
3581pub(crate) fn json_escape(s: &str) -> String {
3582 let mut out = String::with_capacity(s.len() + 4);
3583 for ch in s.chars() {
3584 match ch {
3585 '"' => out.push_str("\\\""),
3586 '\\' => out.push_str("\\\\"),
3587 '\n' => out.push_str("\\n"),
3588 '\r' => out.push_str("\\r"),
3589 '\t' => out.push_str("\\t"),
3590 c if (c as u32) < 0x20 => { let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32)); }
3591 c => out.push(c),
3592 }
3593 }
3594 out
3595}
3596
3597// ── pagination cursors ─────────────────────────────────────────────────────────
3598
3599/// Render `,"nextCursor":"..."` for a `*/list` response, or `""` if there's
3600/// no next page — spliced directly after the closing `]` of the items array.
3601fn next_cursor_json(next_cursor: &Option<String>) -> String {
3602 match next_cursor {
3603 Some(c) => format!(r#","nextCursor":"{}""#, json_escape(c)),
3604 None => String::new(),
3605 }
3606}
3607
3608/// Encode a `tools/list`/`resources/list`/`prompts/list` offset as the
3609/// opaque `nextCursor`/`params.cursor` string the MCP spec expects — just
3610/// base64 of the decimal offset, e.g. `50` → `"NTA="`. Callers only ever
3611/// treat this as opaque; the encoding is a private implementation detail of
3612/// this module, not a client-facing contract.
3613fn encode_cursor(offset: usize) -> String {
3614 base64_encode(offset.to_string().as_bytes())
3615}
3616
3617/// Decode a cursor produced by [`encode_cursor`]. Returns `None` for
3618/// anything that isn't valid base64 of a decimal `usize` — a malformed or
3619/// tampered cursor, not a crash.
3620fn decode_cursor(cursor: &str) -> Option<usize> {
3621 String::from_utf8(base64_decode(cursor)?).ok()?.parse().ok()
3622}
3623
3624const BASE64_TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3625
3626fn base64_encode(data: &[u8]) -> String {
3627 let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
3628 for chunk in data.chunks(3) {
3629 let b0 = chunk[0] as u32;
3630 let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
3631 let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
3632 let n = (b0 << 16) | (b1 << 8) | b2;
3633 out.push(BASE64_TABLE[((n >> 18) & 0x3F) as usize] as char);
3634 out.push(BASE64_TABLE[((n >> 12) & 0x3F) as usize] as char);
3635 out.push(if chunk.len() > 1 { BASE64_TABLE[((n >> 6) & 0x3F) as usize] as char } else { '=' });
3636 out.push(if chunk.len() > 2 { BASE64_TABLE[(n & 0x3F) as usize] as char } else { '=' });
3637 }
3638 out
3639}
3640
3641fn base64_decode(s: &str) -> Option<Vec<u8>> {
3642 fn sextet(c: u8) -> Option<u32> {
3643 match c {
3644 b'A'..=b'Z' => Some((c - b'A') as u32),
3645 b'a'..=b'z' => Some((c - b'a' + 26) as u32),
3646 b'0'..=b'9' => Some((c - b'0' + 52) as u32),
3647 b'+' => Some(62),
3648 b'/' => Some(63),
3649 _ => None,
3650 }
3651 }
3652
3653 let trimmed = s.trim_end_matches('=');
3654 let bytes = trimmed.as_bytes();
3655 let mut out = Vec::with_capacity(bytes.len() * 3 / 4 + 3);
3656 for chunk in bytes.chunks(4) {
3657 if chunk.len() == 1 {
3658 return None; // not a valid base64 length
3659 }
3660 let vals: Vec<u32> = chunk.iter().map(|&b| sextet(b)).collect::<Option<Vec<_>>>()?;
3661 let n = vals.iter().enumerate().fold(0u32, |acc, (i, &v)| acc | (v << (18 - 6 * i)));
3662 out.push(((n >> 16) & 0xFF) as u8);
3663 if vals.len() > 2 { out.push(((n >> 8) & 0xFF) as u8); }
3664 if vals.len() > 3 { out.push((n & 0xFF) as u8); }
3665 }
3666 Some(out)
3667}
3668
3669fn uri_matches(template: &str, uri: &str) -> bool {
3670 // Template `"user://{id}"` matches any URI starting with `"user://"`.
3671 match template.find('{') {
3672 Some(pos) => uri.starts_with(&template[..pos]),
3673 None => template == uri,
3674 }
3675}