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