Skip to main content

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