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