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 2024-11-05 specification](https://spec.modelcontextprotocol.io).
52//!
53//! `GET /mcp` opens a Server-Sent Events stream for server → client push —
54//! see [`McpServer::notify`] and the module docs' SSE section below.
55//!
56//! # SSE streaming transport
57//!
58//! A client that sends `GET /mcp` (instead of `POST`) gets back a
59//! `text/event-stream` response that stays open indefinitely. Call
60//! [`McpServer::notify`] from anywhere (a background thread, another request's
61//! handler, ...) to push a JSON-RPC notification to every currently-connected
62//! SSE client:
63//!
64//! ```rust,no_run
65//! use rust_web_server::mcp::McpServer;
66//!
67//! let server = McpServer::new("my-server", "1.0");
68//! // Elsewhere, e.g. after some background job finishes:
69//! server.notify("notifications/message", Some(r#"{"level":"info","data":"job done"}"#));
70//! ```
71//!
72//! Idle connections receive a `: keep-alive` SSE comment every 15 seconds so
73//! intermediate proxies don't time them out; this doubles as the mechanism
74//! that detects a client has disconnected (the next write attempt fails and
75//! the connection is dropped). A client whose event buffer fills up (32
76//! pending frames, unconsumed) is treated the same as a disconnected one and
77//! dropped from the broadcast list — [`McpServer::notify`] never blocks the
78//! calling thread waiting on a slow reader.
79//!
80//! This transport is only wired up for the plain HTTP/1.1 path
81//! (`Server::run`/`Server::process`) — same scope as `Response::stream_pipe`
82//! generally, which the HTTP/2 (`h2_handler`) and HTTP/3 (`h3_handler`)
83//! handlers don't yet support for *any* response, not just this one.
84//!
85//! # Environment variables
86//!
87//! None — configure the server programmatically via the builder.
88
89mod json_rpc;
90
91#[cfg(test)]
92mod tests;
93
94use std::collections::HashMap;
95#[cfg(feature = "http2")]
96use std::future::Future;
97#[cfg(feature = "http2")]
98use std::pin::Pin;
99use std::sync::mpsc::{self, SyncSender};
100use std::sync::{Arc, Mutex, RwLock};
101use std::time::Duration;
102
103use crate::app::App;
104use crate::application::Application;
105use crate::core::New;
106use crate::header::Header;
107use crate::mime_type::MimeType;
108use crate::range::Range;
109use crate::request::Request;
110use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
111use crate::server::ConnectionInfo;
112
113const PROTOCOL_VERSION: &str = "2024-11-05";
114
115// ── public content types ──────────────────────────────────────────────────────
116
117/// Content returned by tool and resource handlers.
118///
119/// Create with [`McpContent::text`] (plain text or JSON strings),
120/// [`McpContent::json`] (marks MIME type as `application/json`),
121/// [`McpContent::image`] (base64-encoded binary image data), or
122/// [`McpContent::embedded`] (a resource embedded inline in a tool response).
123#[derive(Clone, Debug)]
124pub struct McpContent {
125    /// `"text"`, `"image"`, or `"resource"`.
126    pub kind: &'static str,
127    /// The content string — text for `"text"`, base64 data for `"image"`,
128    /// or the embedded resource's text for `"resource"`.
129    pub text: String,
130    /// Optional MIME type override (default `"text/plain"` for `"text"`;
131    /// required in practice for `"image"`/`"resource"`, set by their
132    /// constructors).
133    pub mime_type: Option<String>,
134    /// The resource URI — only set (and only serialized) for `"resource"`.
135    pub uri: Option<String>,
136}
137
138impl McpContent {
139    /// Plain-text content.
140    pub fn text(s: impl Into<String>) -> Self {
141        McpContent { kind: "text", text: s.into(), mime_type: None, uri: None }
142    }
143
144    /// JSON content — sets `mimeType` to `application/json`.
145    pub fn json(s: impl Into<String>) -> Self {
146        McpContent { kind: "text", text: s.into(), mime_type: Some("application/json".to_string()), uri: None }
147    }
148
149    /// Image content (screenshot, chart, generated art) — `data` is base64-encoded
150    /// binary and `mime_type` is e.g. `"image/png"`.
151    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
152        McpContent { kind: "image", text: data.into(), mime_type: Some(mime_type.into()), uri: None }
153    }
154
155    /// A resource embedded inline in a tool response, as opposed to one a
156    /// client fetches separately via `resources/read`.
157    pub fn embedded(uri: impl Into<String>, text: impl Into<String>, mime_type: impl Into<String>) -> Self {
158        McpContent { kind: "resource", text: text.into(), mime_type: Some(mime_type.into()), uri: Some(uri.into()) }
159    }
160
161    fn to_content_json(&self) -> String {
162        match self.kind {
163            "image" => format!(
164                r#"{{"type":"image","data":"{}","mimeType":"{}"}}"#,
165                json_escape(&self.text),
166                json_escape(self.mime_type.as_deref().unwrap_or("application/octet-stream")),
167            ),
168            "resource" => format!(
169                r#"{{"type":"resource","resource":{{"uri":"{}","mimeType":"{}","text":"{}"}}}}"#,
170                json_escape(self.uri.as_deref().unwrap_or("")),
171                json_escape(self.mime_type.as_deref().unwrap_or("text/plain")),
172                json_escape(&self.text),
173            ),
174            _ => format!(r#"{{"type":"text","text":"{}"}}"#, json_escape(&self.text)),
175        }
176    }
177
178    fn mime(&self) -> &str {
179        self.mime_type.as_deref().unwrap_or("text/plain")
180    }
181}
182
183/// A single message in a prompt response.
184#[derive(Clone, Debug)]
185pub struct PromptMessage {
186    /// `"user"` or `"assistant"`.
187    pub role: &'static str,
188    /// The message content.
189    pub content: McpContent,
190}
191
192impl PromptMessage {
193    /// Build a user-role message.
194    pub fn user(text: impl Into<String>) -> Self {
195        PromptMessage { role: "user", content: McpContent::text(text) }
196    }
197
198    /// Build an assistant-role message.
199    pub fn assistant(text: impl Into<String>) -> Self {
200        PromptMessage { role: "assistant", content: McpContent::text(text) }
201    }
202
203    fn to_json(&self) -> String {
204        format!(
205            r#"{{"role":"{}","content":{}}}"#,
206            self.role,
207            self.content.to_content_json(),
208        )
209    }
210}
211
212/// Argument definition for a prompt template.
213#[derive(Clone)]
214pub struct PromptArgDef {
215    pub name: String,
216    pub description: String,
217    pub required: bool,
218}
219
220impl PromptArgDef {
221    pub fn required(name: impl Into<String>, description: impl Into<String>) -> Self {
222        PromptArgDef { name: name.into(), description: description.into(), required: true }
223    }
224
225    pub fn optional(name: impl Into<String>, description: impl Into<String>) -> Self {
226        PromptArgDef { name: name.into(), description: description.into(), required: false }
227    }
228}
229
230// ── McpContext ────────────────────────────────────────────────────────────────
231
232/// Per-request context passed to tool handlers registered via
233/// [`McpServer::tool_with_context`] — caller identity and session info that a
234/// plain `Fn(&str) -> ...` tool handler has no way to see.
235///
236/// Constructed in [`McpServer::execute`] from the current request's headers
237/// plus whatever `clientInfo` was recorded for this session at `initialize`
238/// time (see [`McpServer::handle_request_with_context`]).
239#[derive(Debug, Clone, Default)]
240pub struct McpContext {
241    /// `clientInfo.name` sent in this session's `initialize` call, if the
242    /// client sent one and this request carries a recognized `Mcp-Session-Id`.
243    pub client_name: Option<String>,
244    /// `clientInfo.version` sent in this session's `initialize` call, under
245    /// the same conditions as `client_name`.
246    pub client_version: Option<String>,
247    /// The `Mcp-Session-Id` header on this request, if present — the value
248    /// the server minted and returned in the `initialize` response header
249    /// for this session (see the module docs' Sessions section).
250    pub session_id: Option<String>,
251    /// Verified JWT claims as a JSON string. Not populated by anything in
252    /// this crate yet — reserved for a future JWT-auth integration
253    /// (MCP_TODO.md TODO-11/TODO-13); always `None` today.
254    pub auth_claims: Option<String>,
255    /// The raw JSON value of `params._meta.progressToken` from the
256    /// triggering `tools/call` request, if the client sent one — a spec
257    /// `string | number`, so this is stored pre-rendered (already correctly
258    /// quoted if it's a string) rather than decoded, and spliced back
259    /// verbatim by [`Self::report_progress`]. `None` for anything other than
260    /// a `tools/call` whose caller asked for progress updates.
261    pub progress_token: Option<String>,
262    /// Shared handle back to the owning [`McpServer`]'s SSE broadcast list,
263    /// used by [`Self::report_progress`]. Not `pub` — this is plumbing, not
264    /// part of the context data a handler reads. `None` for a context built
265    /// by hand (e.g. via [`McpServer::handle_request_with_context`] in a
266    /// test) rather than through [`McpServer::execute`], in which case
267    /// `report_progress` silently no-ops — there's no live server to
268    /// broadcast through.
269    sse_clients: Option<Arc<Mutex<Vec<SseClient>>>>,
270    /// Shared flag flipped by a `notifications/cancelled` referencing this
271    /// `tools/call`'s request id, checked by [`Self::is_cancelled`]. Not
272    /// `pub` — see that method. `None` for anything other than a live
273    /// `tools/call` dispatched through [`McpServer::execute`]/`handle_request_with_context`.
274    cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
275    /// Whether this session's `initialize` call declared
276    /// `params.capabilities.sampling`, checked by [`Self::sample`] before
277    /// sending a request the client never said it could answer.
278    sampling_supported: bool,
279    /// Shared handle to the owning [`McpServer`]'s in-flight
280    /// server-initiated-request registry (`sampling/createMessage`,
281    /// `roots/list`), used by [`Self::sample`]/[`Self::list_roots`]. Not
282    /// `pub` — see `sse_clients` for the same "plumbing, not context data"
283    /// reasoning; `None` under the same conditions.
284    pending_replies: Option<Arc<Mutex<HashMap<String, mpsc::Sender<Result<String, String>>>>>>,
285    /// Whether this session's `initialize` call declared
286    /// `params.capabilities.roots`, checked by [`Self::list_roots`] before
287    /// sending a request the client never said it could answer.
288    roots_supported: bool,
289    /// Shared handle to the owning [`McpServer`]'s session registry, used
290    /// by [`Self::list_roots`] to read/write this session's cached roots
291    /// list. Not `pub` — plumbing, not context data.
292    sessions: Option<Arc<Mutex<HashMap<String, StoredClientInfo>>>>,
293}
294
295impl McpContext {
296    /// Push a `notifications/progress` event over the SSE channel for this
297    /// request's `progressToken`, if the client asked for progress updates
298    /// (`params._meta.progressToken` on the triggering `tools/call`) and
299    /// this context was built through a live [`McpServer`] (via `execute()`,
300    /// not a bare `McpContext { .. }` — see the `sse_clients` field doc).
301    ///
302    /// Silently does nothing in either case — a handler doesn't need to
303    /// branch on whether progress reporting is actually wired up before
304    /// calling this; it's always safe to call.
305    ///
306    /// `total` and `message` are both optional, matching the spec's
307    /// `notifications/progress` shape: `{"progressToken":...,"progress":...,
308    /// "total":...,"message":"..."}` (with `total`/`message` omitted when not
309    /// given here).
310    ///
311    /// ```rust,no_run
312    /// use rust_web_server::mcp::{McpContent, McpServer};
313    ///
314    /// let server = McpServer::new("my-server", "1.0")
315    ///     .tool_with_context("long_job", "Do something slow", "{}", |ctx, _args| {
316    ///         ctx.report_progress(0.0, Some(100.0), Some("starting"));
317    ///         // ... do work ...
318    ///         ctx.report_progress(100.0, Some(100.0), Some("done"));
319    ///         Ok(McpContent::text("done"))
320    ///     });
321    /// ```
322    pub fn report_progress(&self, progress: f64, total: Option<f64>, message: Option<&str>) {
323        let (Some(token), Some(sse_clients)) = (&self.progress_token, &self.sse_clients) else {
324            return;
325        };
326
327        let total_field = match total {
328            Some(t) => format!(r#","total":{t}"#),
329            None => String::new(),
330        };
331        let message_field = match message {
332            Some(m) => format!(r#","message":"{}""#, json_escape(m)),
333            None => String::new(),
334        };
335        let params = format!(
336            r#"{{"progressToken":{token},"progress":{progress}{total_field}{message_field}}}"#
337        );
338        let json = render_notification("notifications/progress", Some(&params));
339        broadcast_sse_to(sse_clients, &json);
340    }
341
342    /// `true` if the client sent `notifications/cancelled` referencing this
343    /// `tools/call`'s request id.
344    ///
345    /// Rust cannot forcibly interrupt a running synchronous closure — same
346    /// limitation [`crate::timeout::with_timeout`] documents — so this is
347    /// *cooperative* cancellation: nothing happens automatically. A handler
348    /// that does its own iterative work (processing a batch of items, say)
349    /// can check this between steps and return early; a handler that never
350    /// checks it runs to completion regardless, exactly as before this
351    /// existed.
352    ///
353    /// Always `false` if the client never sent a cancellation, if this
354    /// wasn't dispatched as a `tools/call` (the only method cancellation
355    /// applies to), or if `ctx` was built without a live server behind it.
356    ///
357    /// ```rust,no_run
358    /// use rust_web_server::mcp::{McpContent, McpServer};
359    ///
360    /// let server = McpServer::new("my-server", "1.0")
361    ///     .tool_with_context("process_batch", "Process many items", "{}", |ctx, _args| {
362    ///         for i in 0..1_000_000 {
363    ///             if ctx.is_cancelled() {
364    ///                 return Err("cancelled by client".to_string());
365    ///             }
366    ///             // ... process item i ...
367    ///         }
368    ///         Ok(McpContent::text("done"))
369    ///     });
370    /// ```
371    pub fn is_cancelled(&self) -> bool {
372        self.cancellation.as_ref().is_some_and(|c| c.load(std::sync::atomic::Ordering::Relaxed))
373    }
374
375    /// Ask the connected client to run LLM inference ("sampling") and block
376    /// until it replies or `timeout` elapses — the server-initiated half of
377    /// `sampling/createMessage`. This reverses the usual request direction:
378    /// the server sends a JSON-RPC *request* to the client over the `GET
379    /// /mcp` SSE stream, and the client answers with its own `POST /mcp`
380    /// carrying a JSON-RPC *response* (no `method`) that
381    /// [`McpServer::handle_request_with_context`] recognizes and routes
382    /// back here instead of treating it as an invalid request.
383    ///
384    /// Blocking (not `async fn`) is deliberate: tool handlers in this crate
385    /// are plain synchronous closures — there is no async tool handler
386    /// support yet (MCP_TODO.md's TODO-17) for this to `.await` inside of.
387    /// The calling thread parks on the response channel for up to
388    /// `timeout`; on a thread-pool server this ties up one worker for that
389    /// long, same tradeoff `crate::timeout::with_timeout` already accepts
390    /// for bounding a slow handler's *caller*.
391    ///
392    /// Fails fast, before sending anything, if: the client's `initialize`
393    /// call never declared `capabilities.sampling` (it wouldn't know what
394    /// to do with the request); this request has no session id (nothing to
395    /// address the request to); or `ctx` has no live server behind it.
396    /// Otherwise fails with a timeout error if the client never responds —
397    /// including if it simply has no `GET /mcp` SSE connection open for
398    /// this session, since there's no separate "not connected" signal.
399    ///
400    /// ```rust,no_run
401    /// use rust_web_server::mcp::{McpServer, PromptMessage, SamplingRequest};
402    /// use std::time::Duration;
403    ///
404    /// let server = McpServer::new("my-server", "1.0")
405    ///     .tool_with_context("ask_llm", "Ask the connected client's model a question", "{}", |ctx, _args| {
406    ///         let response = ctx.sample(
407    ///             SamplingRequest {
408    ///                 messages: vec![PromptMessage::user("What is 2+2?")],
409    ///                 max_tokens: 100,
410    ///                 system_prompt: None,
411    ///             },
412    ///             Duration::from_secs(30),
413    ///         )?;
414    ///         Ok(response.content)
415    ///     });
416    /// ```
417    pub fn sample(&self, request: SamplingRequest, timeout: Duration) -> Result<SamplingResponse, String> {
418        if !self.sampling_supported {
419            return Err("the connected client did not declare sampling support in its initialize capabilities".to_string());
420        }
421
422        let messages_json: Vec<String> = request.messages.iter().map(|m| m.to_json()).collect();
423        let system_prompt_field = match &request.system_prompt {
424            Some(s) => format!(r#","systemPrompt":"{}""#, json_escape(s)),
425            None => String::new(),
426        };
427        let params = format!(
428            r#"{{"messages":[{}],"maxTokens":{}{system_prompt_field}}}"#,
429            messages_json.join(","), request.max_tokens,
430        );
431
432        let result_json = self.send_and_wait("sampling/createMessage", Some(&params), timeout)?;
433        parse_sampling_response(&result_json)
434    }
435
436    /// Ask the connected client which filesystem roots (workspace
437    /// directories, mounted volumes, ...) it has access to — useful for a
438    /// file-system-aware tool that should only operate within the client's
439    /// declared workspace rather than the whole filesystem.
440    ///
441    /// Like [`Self::sample`], this reverses the usual request direction (a
442    /// server-initiated `roots/list` request over SSE, answered by the
443    /// client's own `POST /mcp`) and blocks the calling thread for up to
444    /// `timeout` — see `sample`'s docs for why blocking is deliberate here.
445    ///
446    /// The result is cached per session: the first call after `initialize`
447    /// (or after the client sends `notifications/roots/list_changed`, which
448    /// invalidates the cache) does a live round trip; later calls in the
449    /// same session return the cached list without sending anything. A tool
450    /// handler can call this on every invocation without worrying about
451    /// spamming the client with redundant `roots/list` requests.
452    ///
453    /// Fails fast, before sending anything, under the same conditions as
454    /// [`Self::sample`] (translated to roots): the client never declared
455    /// `capabilities.roots`, this request has no session id, or `ctx` has
456    /// no live server behind it.
457    ///
458    /// ```rust,no_run
459    /// use rust_web_server::mcp::McpServer;
460    /// use std::time::Duration;
461    ///
462    /// let server = McpServer::new("my-server", "1.0")
463    ///     .tool_with_context("list_workspace_files", "List files in the client's workspace", "{}", |ctx, _args| {
464    ///         let roots = ctx.list_roots(Duration::from_secs(10))?;
465    ///         let names: Vec<String> = roots.iter().map(|r| r.uri.clone()).collect();
466    ///         Ok(rust_web_server::mcp::McpContent::text(names.join(", ")))
467    ///     });
468    /// ```
469    pub fn list_roots(&self, timeout: Duration) -> Result<Vec<McpRoot>, String> {
470        if !self.roots_supported {
471            return Err("the connected client did not declare roots support in its initialize capabilities".to_string());
472        }
473
474        if let (Some(session_id), Some(sessions)) = (&self.session_id, &self.sessions) {
475            if let Some(cached) = sessions.lock().unwrap().get(session_id).and_then(|info| info.roots.clone()) {
476                return Ok(cached);
477            }
478        }
479
480        let result_json = self.send_and_wait("roots/list", None, timeout)?;
481        let roots = parse_roots_response(&result_json)?;
482
483        if let (Some(session_id), Some(sessions)) = (&self.session_id, &self.sessions) {
484            if let Some(info) = sessions.lock().unwrap().get_mut(session_id) {
485                info.roots = Some(roots.clone());
486            }
487        }
488
489        Ok(roots)
490    }
491
492    /// Send a JSON-RPC request to the client for this context's session and
493    /// block for the reply — the shared send-and-correlate mechanic behind
494    /// [`Self::sample`] and [`Self::list_roots`]. Returns the raw `result`
495    /// JSON string (not yet parsed into either method's own response type)
496    /// on success.
497    fn send_and_wait(&self, method: &str, params_json: Option<&str>, timeout: Duration) -> Result<String, String> {
498        let session_id = self.session_id.clone()
499            .ok_or_else(|| format!("{method} requires a session (Mcp-Session-Id)"))?;
500        let sse_clients = self.sse_clients.as_ref()
501            .ok_or_else(|| format!("{method} requires a live server (this context has none)"))?;
502        let pending = self.pending_replies.as_ref()
503            .ok_or_else(|| format!("{method} requires a live server (this context has none)"))?;
504
505        let request_id = format!("\"{}\"", crate::request_id::generate_request_id());
506        let (tx, rx) = mpsc::channel::<Result<String, String>>();
507        pending.lock().unwrap().insert(request_id.clone(), tx);
508
509        let params_field = match params_json {
510            Some(p) => format!(r#","params":{p}"#),
511            None => String::new(),
512        };
513        let rpc = format!(r#"{{"jsonrpc":"2.0","id":{request_id},"method":"{method}"{params_field}}}"#);
514
515        send_sse_to_sessions(sse_clients, &[session_id], &rpc);
516
517        let outcome = rx.recv_timeout(timeout);
518        pending.lock().unwrap().remove(&request_id);
519
520        match outcome {
521            Ok(Ok(result_json)) => Ok(result_json),
522            Ok(Err(e)) => Err(e),
523            Err(_) => Err(format!("{method} timed out waiting for the client's response")),
524        }
525    }
526}
527
528/// A request to ask the connected MCP client to run LLM inference
529/// ("sampling") — build one and pass it to [`McpContext::sample`].
530///
531/// `messages` reuses [`PromptMessage`] rather than introducing a near-identical
532/// type — the spec's sampling message shape (`{"role":...,"content":{"type":"text",...}}`)
533/// is exactly what `PromptMessage` already models.
534pub struct SamplingRequest {
535    pub messages: Vec<PromptMessage>,
536    pub max_tokens: u32,
537    /// An optional system prompt to steer the client's model, per the
538    /// spec's `params.systemPrompt`.
539    pub system_prompt: Option<String>,
540}
541
542/// The client's answer to a [`SamplingRequest`], returned by
543/// [`McpContext::sample`].
544pub struct SamplingResponse {
545    /// Almost always `"assistant"`, per spec.
546    pub role: String,
547    pub content: McpContent,
548    /// The model the client actually used to generate this response, e.g.
549    /// `"claude-3-sonnet-20240307"`.
550    pub model: String,
551    /// Why the model stopped, e.g. `"endTurn"`, `"maxTokens"`, `"stopSequence"`.
552    /// `None` if the client didn't report one.
553    pub stop_reason: Option<String>,
554}
555
556/// Parse a `sampling/createMessage` response's `result` object (already
557/// extracted from the enclosing JSON-RPC envelope) into a [`SamplingResponse`].
558fn parse_sampling_response(result_json: &str) -> Result<SamplingResponse, String> {
559    let role = json_rpc::extract_str(result_json, "role").unwrap_or_else(|| "assistant".to_string());
560    let content_json = json_rpc::extract_raw(result_json, "content")
561        .ok_or_else(|| "sampling response missing content".to_string())?;
562    let kind = json_rpc::extract_str(&content_json, "type").unwrap_or_else(|| "text".to_string());
563    let content = match kind.as_str() {
564        "image" => McpContent::image(
565            json_rpc::extract_str(&content_json, "data").unwrap_or_default(),
566            json_rpc::extract_str(&content_json, "mimeType").unwrap_or_default(),
567        ),
568        _ => McpContent::text(json_rpc::extract_str(&content_json, "text").unwrap_or_default()),
569    };
570    let model = json_rpc::extract_str(result_json, "model").unwrap_or_default();
571    let stop_reason = json_rpc::extract_str(result_json, "stopReason");
572    Ok(SamplingResponse { role, content, model, stop_reason })
573}
574
575/// One filesystem root a client has access to, returned by
576/// [`McpContext::list_roots`] — a workspace directory, a mounted volume,
577/// or similar. `uri` is typically a `file://` URI per spec.
578#[derive(Debug, Clone)]
579pub struct McpRoot {
580    pub uri: String,
581    /// A human-readable label for the root, if the client provided one.
582    pub name: Option<String>,
583}
584
585/// Parse a `roots/list` response's `result` object (already extracted from
586/// the enclosing JSON-RPC envelope) into a `Vec<McpRoot>`.
587fn parse_roots_response(result_json: &str) -> Result<Vec<McpRoot>, String> {
588    let roots_array = json_rpc::extract_raw(result_json, "roots")
589        .ok_or_else(|| "roots/list response missing roots".to_string())?;
590    let roots = json_rpc::split_array_elements(&roots_array).iter().map(|elem| {
591        McpRoot {
592            uri: json_rpc::extract_str(elem, "uri").unwrap_or_default(),
593            name: json_rpc::extract_str(elem, "name"),
594        }
595    }).collect();
596    Ok(roots)
597}
598
599/// `clientInfo` recorded for one session at `initialize` time, looked up by
600/// `Mcp-Session-Id` for later requests in the same session. See
601/// `McpServer`'s `sessions` field doc comment for the unbounded-growth caveat.
602#[derive(Debug, Clone, Default)]
603struct StoredClientInfo {
604    name: Option<String>,
605    version: Option<String>,
606    /// Whether this session's `initialize` call declared `params.capabilities.sampling`
607    /// (spec: the client, not the server, declares sampling support — the
608    /// presence of the key is what matters, not its contents, which are
609    /// normally an empty object). Checked by [`McpContext::sample`] before
610    /// sending a `sampling/createMessage` request that the client would
611    /// have no idea how to answer.
612    supports_sampling: bool,
613    /// Whether this session's `initialize` call declared `params.capabilities.roots`,
614    /// checked by [`McpContext::list_roots`] the same way `supports_sampling` gates `sample`.
615    supports_roots: bool,
616    /// Cached result of this session's last `roots/list` round trip, read
617    /// and written by [`McpContext::list_roots`]. `None` means "never
618    /// fetched, or invalidated" — set back to `None` when this session
619    /// sends `notifications/roots/list_changed`, so the next `list_roots`
620    /// call does a fresh round trip instead of serving stale data.
621    roots: Option<Vec<McpRoot>>,
622}
623
624// ── ToolAnnotations ───────────────────────────────────────────────────────────
625
626/// Behavioral hints for a tool, per the MCP 2025-03-26 spec's tool
627/// annotations. Clients (Claude Desktop and others) use these to decide
628/// whether to warn or ask for confirmation before calling a tool — e.g. skip
629/// confirmation for a read-only tool, or warn before a destructive one.
630///
631/// Every field is a *hint*, not something this server enforces or verifies —
632/// nothing stops a handler registered with `read_only_hint: Some(true)` from
633/// actually writing to disk. A well-behaved server sets these accurately;
634/// a client is free to ignore them or ask for confirmation anyway.
635///
636/// Register with [`McpServer::tool_annotated`]. Build one with plain struct
637/// syntax — every field defaults to `None` (no hint given, the client's own
638/// default applies):
639///
640/// ```rust
641/// use rust_web_server::mcp::ToolAnnotations;
642///
643/// let destructive = ToolAnnotations {
644///     destructive_hint: Some(true),
645///     read_only_hint: Some(false),
646///     ..Default::default()
647/// };
648/// ```
649#[derive(Debug, Clone, Copy, Default)]
650pub struct ToolAnnotations {
651    /// The tool does not modify its environment.
652    pub read_only_hint: Option<bool>,
653    /// The tool may perform destructive updates (only meaningful when
654    /// `read_only_hint` is not `Some(true)`).
655    pub destructive_hint: Option<bool>,
656    /// Calling the tool repeatedly with the same arguments has no additional
657    /// effect beyond the first call.
658    pub idempotent_hint: Option<bool>,
659    /// The tool may interact with an open-ended set of external entities
660    /// (e.g. web search), as opposed to a fixed, closed set.
661    pub open_world_hint: Option<bool>,
662}
663
664impl ToolAnnotations {
665    /// Render as a JSON object containing only the hints that are `Some`,
666    /// using the spec's camelCase key names. Returns `"{}"` if every field
667    /// is `None`.
668    fn to_json(self) -> String {
669        let mut fields = Vec::with_capacity(4);
670        if let Some(v) = self.read_only_hint {
671            fields.push(format!(r#""readOnlyHint":{v}"#));
672        }
673        if let Some(v) = self.destructive_hint {
674            fields.push(format!(r#""destructiveHint":{v}"#));
675        }
676        if let Some(v) = self.idempotent_hint {
677            fields.push(format!(r#""idempotentHint":{v}"#));
678        }
679        if let Some(v) = self.open_world_hint {
680            fields.push(format!(r#""openWorldHint":{v}"#));
681        }
682        format!("{{{}}}", fields.join(","))
683    }
684}
685
686// ── LogLevel ──────────────────────────────────────────────────────────────────
687
688/// RFC 5424 syslog severity levels, as used by the MCP `logging/setLevel`
689/// request and `notifications/message` log entries — ordered from most to
690/// least verbose so `level < min_level` comparisons work directly (this
691/// relies on declaration order matching severity order; don't reorder the
692/// variants).
693///
694/// ```rust
695/// use rust_web_server::mcp::LogLevel;
696///
697/// assert!(LogLevel::Debug < LogLevel::Warning);
698/// assert!(LogLevel::Emergency > LogLevel::Error);
699/// assert_eq!(LogLevel::parse("warning"), Some(LogLevel::Warning));
700/// assert_eq!(LogLevel::Warning.as_str(), "warning");
701/// ```
702#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
703pub enum LogLevel {
704    Debug,
705    Info,
706    Notice,
707    Warning,
708    Error,
709    Critical,
710    Alert,
711    Emergency,
712}
713
714impl LogLevel {
715    /// Parse the MCP spec's lowercase level name. Returns `None` for
716    /// anything that isn't one of the eight recognized levels.
717    pub fn parse(s: &str) -> Option<Self> {
718        match s {
719            "debug"     => Some(LogLevel::Debug),
720            "info"      => Some(LogLevel::Info),
721            "notice"    => Some(LogLevel::Notice),
722            "warning"   => Some(LogLevel::Warning),
723            "error"     => Some(LogLevel::Error),
724            "critical"  => Some(LogLevel::Critical),
725            "alert"     => Some(LogLevel::Alert),
726            "emergency" => Some(LogLevel::Emergency),
727            _           => None,
728        }
729    }
730
731    /// The MCP spec's lowercase level name, e.g. `"warning"`.
732    pub fn as_str(self) -> &'static str {
733        match self {
734            LogLevel::Debug     => "debug",
735            LogLevel::Info      => "info",
736            LogLevel::Notice    => "notice",
737            LogLevel::Warning   => "warning",
738            LogLevel::Error     => "error",
739            LogLevel::Critical  => "critical",
740            LogLevel::Alert     => "alert",
741            LogLevel::Emergency => "emergency",
742        }
743    }
744}
745
746// ── internal handler registrations ───────────────────────────────────────────
747
748type ToolFn     = Arc<dyn Fn(McpContext, &str) -> Result<McpContent, String>    + Send + Sync>;
749type ResourceFn = Arc<dyn Fn(&str) -> Result<McpContent, String>    + Send + Sync>;
750type PromptFn   = Arc<dyn Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync>;
751/// `Fn(argument_name, partial_value) -> candidate completion strings`.
752type CompletionFn = Arc<dyn Fn(&str, &str) -> Result<Vec<String>, String> + Send + Sync>;
753/// An async tool handler, boxed so `AsyncToolDef` can store handlers with
754/// different concrete `Future` types uniformly. The `Future` itself doesn't
755/// need `Send` for [`crate::async_bridge::block_on_isolated`] (which drives
756/// it to completion without ever moving it across a thread boundary), but
757/// it's required here anyway for consistency with [`crate::async_state`]'s
758/// equivalent handler type — the common case in practice, and one less
759/// surprise for anyone switching between the two async handler styles.
760#[cfg(feature = "http2")]
761type AsyncToolFn = Arc<dyn Fn(String) -> Pin<Box<dyn Future<Output = Result<McpContent, String>> + Send>> + Send + Sync>;
762
763#[derive(Clone)]
764struct ToolDef {
765    name: String,
766    description: String,
767    input_schema: String,
768    annotations: Option<ToolAnnotations>,
769    handler: ToolFn,
770}
771
772/// A tool registered via [`McpServer::async_tool`]/[`McpServer::register_async_tool`]
773/// — stored separately from [`ToolDef`] rather than unifying the two behind
774/// a handler enum, since sync and async tools are otherwise identical and
775/// keeping them apart touches far less of the existing (already
776/// substantial) tool-handling code. `tools/list` and `tools/call` merge
777/// both collections transparently; from the client's perspective there is
778/// no distinction.
779#[cfg(feature = "http2")]
780#[derive(Clone)]
781struct AsyncToolDef {
782    name: String,
783    description: String,
784    input_schema: String,
785    annotations: Option<ToolAnnotations>,
786    handler: AsyncToolFn,
787}
788
789#[derive(Clone)]
790struct ResourceDef {
791    uri_template: String,
792    name: String,
793    description: String,
794    handler: ResourceFn,
795}
796
797#[derive(Clone)]
798struct PromptDef {
799    name: String,
800    description: String,
801    arguments: Vec<PromptArgDef>,
802    handler: PromptFn,
803}
804
805/// One `.completion()` registration — completion candidates for a single
806/// named argument of a single tool or prompt. `ref_type` is the short form
807/// passed to `.completion()` (e.g. `"tool"`, `"prompt"`), matched against the
808/// request's `ref.type` (e.g. `"ref/tool"`) with the `"ref/"` prefix
809/// stripped, not the raw wire value.
810#[derive(Clone)]
811struct CompletionDef {
812    ref_type: String,
813    ref_name: String,
814    handler: CompletionFn,
815}
816
817// ── McpServer ─────────────────────────────────────────────────────────────────
818
819/// An HTTP server that implements the MCP 2024-11-05 protocol.
820///
821/// Register tools, resources, and prompts with the builder methods, then pass
822/// the server to [`Server::run`] (or [`Server::run_tls`]) as an [`Application`].
823/// Requests that do not match the MCP endpoint fall through to the built-in
824/// [`App`] controller chain.
825#[derive(Clone)]
826pub struct McpServer {
827    server_name: String,
828    server_version: String,
829    path: String,
830    /// `Arc<RwLock<_>>` (not a plain `Vec`) so a running server's tool list
831    /// can be mutated at runtime — see [`Self::register_tool`]/[`Self::remove_tool`]
832    /// — and every clone of this `McpServer` (each connection thread gets
833    /// one) sees the same live list.
834    tools: Arc<RwLock<Vec<ToolDef>>>,
835    /// Tools registered via [`Self::async_tool`]/[`Self::register_async_tool`],
836    /// bridged into synchronous [`Application::execute`] via
837    /// [`crate::async_bridge::block_on_isolated`] at call time. Kept
838    /// separate from `tools` rather than merged into one collection — see
839    /// [`AsyncToolDef`]'s doc comment.
840    #[cfg(feature = "http2")]
841    async_tools: Arc<RwLock<Vec<AsyncToolDef>>>,
842    resources: Arc<RwLock<Vec<ResourceDef>>>,
843    prompts: Arc<RwLock<Vec<PromptDef>>>,
844    /// Argument completion providers registered via [`Self::completion`].
845    /// `initialize` advertises the `completions` capability iff this is
846    /// non-empty at that moment.
847    completions: Arc<RwLock<Vec<CompletionDef>>>,
848    fallback: Option<Arc<dyn Application + Send + Sync>>,
849    auth_token: Option<String>,
850    /// Max items per page for `tools/list`/`resources/list`/`prompts/list`,
851    /// set via [`Self::page_size`]. `None` (the default) means no pagination
852    /// — every item comes back in one response, same as before pagination
853    /// existed.
854    page_size: Option<usize>,
855    /// `clientInfo` recorded per `Mcp-Session-Id`, minted at `initialize` time.
856    /// `Arc<Mutex<_>>` so every clone of this `McpServer` shares one map.
857    ///
858    /// This map only grows — nothing ever removes an entry, since there's no
859    /// session-termination signal in the MCP Streamable HTTP transport to key
860    /// eviction off of. Fine for the expected usage (a modest, roughly-stable
861    /// set of long-lived AI-agent clients); a public-internet-facing server
862    /// churning through unbounded distinct clients would leak memory here
863    /// with no built-in reaping mechanism.
864    sessions: Arc<Mutex<HashMap<String, StoredClientInfo>>>,
865    /// Senders for every currently-connected `GET /mcp` SSE client, pushed to
866    /// by [`Self::notify`]. `Arc<Mutex<_>>` so every clone of this `McpServer`
867    /// broadcasts to the same set of listeners.
868    ///
869    /// Entries for clients that disconnected (or whose buffer filled up) are
870    /// only pruned lazily, the next time [`Self::notify`] is called and its
871    /// `try_send` fails — not proactively, since nothing else observes the
872    /// underlying `Receiver` closing. A server that never calls `notify`
873    /// after clients disconnect will accumulate dead entries here.
874    sse_clients: Arc<Mutex<Vec<SseClient>>>,
875    /// Whether `initialize`'s advertised `capabilities` includes `"logging":{}`.
876    /// Set via [`Self::logging_enabled`]. This only controls what's
877    /// advertised — [`Self::log`] works regardless, same as [`Self::notify`]
878    /// does; a spec-honest client just wouldn't call `logging/setLevel` in
879    /// the first place if the capability was never advertised.
880    logging_enabled: bool,
881    /// The minimum [`LogLevel`] that [`Self::log`] will actually push,
882    /// settable at runtime by a client's `logging/setLevel` request. Starts
883    /// at [`LogLevel::Debug`] (the least restrictive level, i.e. nothing is
884    /// filtered) until a client requests otherwise.
885    min_log_level: Arc<Mutex<LogLevel>>,
886    /// In-flight `tools/call` cancellation flags, keyed by the request's raw
887    /// `id` JSON token. Populated just before dispatching a `tools/call` and
888    /// removed again once it returns (success, error, or the flag was never
889    /// checked) — unlike `sessions`/`sse_clients`, this map's entries are
890    /// always short-lived by construction, not merely "not evicted."
891    /// `notifications/cancelled` looks up `params.requestId` here and flips
892    /// the flag; see [`McpContext::is_cancelled`] for how (and whether) a
893    /// handler ever observes it.
894    cancellations: Arc<Mutex<HashMap<String, Arc<std::sync::atomic::AtomicBool>>>>,
895    /// Resource URI -> session ids subscribed to it via
896    /// `resources/subscribe`, consulted by [`Self::notify_resource_updated`].
897    /// A session id is only meaningful if the client also opened `GET /mcp`
898    /// with the same `Mcp-Session-Id` header (see [`SseClient`]) — a session
899    /// that only ever calls `resources/subscribe` over POST with no matching
900    /// SSE connection is subscribed in name only, since there's no channel
901    /// to push the update over. Entries are removed by explicit
902    /// `resources/unsubscribe` calls (URIs with zero subscribers are pruned
903    /// entirely); a session that disconnects without unsubscribing leaves a
904    /// harmless stale session id behind, same "no proactive eviction"
905    /// tradeoff already documented for `sessions`.
906    subscriptions: Arc<Mutex<HashMap<String, Vec<String>>>>,
907    /// In-flight `sampling/createMessage` requests this server has sent to
908    /// a client, keyed by the raw (already-quoted) request id token this
909    /// server minted. A JSON-RPC *response* has no `method` field, so
910    /// [`Self::handle_request_with_context`]/[`Self::handle_batch`]
911    /// special-case a method-less body with a recognized `id` as a
912    /// sampling reply (via [`Self::try_deliver_sampling_response`]) rather
913    /// than an invalid request. See [`McpContext::sample`] for the
914    /// send-and-block side.
915    pending_replies: Arc<Mutex<HashMap<String, mpsc::Sender<Result<String, String>>>>>,
916}
917
918/// One `GET /mcp` SSE client: its outbound channel plus the
919/// `Mcp-Session-Id` it connected with, if any. Broadcast notifications
920/// (`.notify()`, `.log()`, `list_changed`) go to every client regardless of
921/// `session_id`; [`McpServer::notify_resource_updated`] targets only
922/// clients whose `session_id` is subscribed to the changed URI.
923#[derive(Debug)]
924struct SseClient {
925    session_id: Option<String>,
926    sender: SseSender,
927}
928
929/// One `GET /mcp` SSE client's outbound channel. Bounded so a slow or stuck
930/// client can't grow memory without limit; [`McpServer::notify`] uses
931/// `try_send` (never blocks) and drops any client whose buffer is full.
932type SseSender = SyncSender<Vec<u8>>;
933
934/// Max buffered-but-unread SSE frames per client before it's treated as dead.
935const SSE_CHANNEL_CAPACITY: usize = 32;
936
937/// How often an idle SSE connection gets a `: keep-alive` comment.
938const SSE_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(15);
939
940/// Max `completion/complete` values returned in one response, per spec
941/// guidance that servers SHOULD NOT return more than 100. A handler
942/// returning more has the rest reported via `hasMore`/`total` rather than
943/// silently included.
944const MAX_COMPLETION_VALUES: usize = 100;
945
946impl McpServer {
947    /// Create a new `McpServer`.  The default MCP endpoint is `POST /mcp`.
948    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
949        McpServer {
950            server_name: name.into(),
951            server_version: version.into(),
952            path: "/mcp".to_string(),
953            tools: Arc::new(RwLock::new(Vec::new())),
954            #[cfg(feature = "http2")]
955            async_tools: Arc::new(RwLock::new(Vec::new())),
956            resources: Arc::new(RwLock::new(Vec::new())),
957            prompts: Arc::new(RwLock::new(Vec::new())),
958            completions: Arc::new(RwLock::new(Vec::new())),
959            fallback: None,
960            auth_token: None,
961            page_size: None,
962            sessions: Arc::new(Mutex::new(HashMap::new())),
963            sse_clients: Arc::new(Mutex::new(Vec::new())),
964            logging_enabled: false,
965            min_log_level: Arc::new(Mutex::new(LogLevel::Debug)),
966            cancellations: Arc::new(Mutex::new(HashMap::new())),
967            subscriptions: Arc::new(Mutex::new(HashMap::new())),
968            pending_replies: Arc::new(Mutex::new(HashMap::new())),
969        }
970    }
971
972    /// Cap `tools/list`, `resources/list`, and `prompts/list` to at most `n`
973    /// items per response, enabling cursor-based pagination: a response with
974    /// more items remaining includes `"nextCursor"`, an opaque string the
975    /// client echoes back as `params.cursor` on its next call to get the next
976    /// page. `n` is clamped to a minimum of `1`.
977    ///
978    /// Without calling this, every registered tool/resource/prompt is
979    /// returned in a single response — the default, and the only behavior
980    /// before pagination existed.
981    ///
982    /// ```rust
983    /// use rust_web_server::mcp::McpServer;
984    ///
985    /// let server = McpServer::new("my-server", "1.0").page_size(50);
986    /// ```
987    pub fn page_size(mut self, n: usize) -> Self {
988        self.page_size = Some(n.max(1));
989        self
990    }
991
992    /// Push a JSON-RPC notification (no `id` — fire-and-forget, per the
993    /// spec) to every client currently connected to the `GET /mcp` SSE
994    /// stream, framed as an SSE `data:` event.
995    ///
996    /// `params_json`, if given, must already be a valid JSON value (usually
997    /// an object) — it's spliced in verbatim, not escaped or re-serialized.
998    ///
999    /// Never blocks: a client whose event buffer is full (not reading fast
1000    /// enough) is treated the same as a disconnected one and dropped from
1001    /// the broadcast list, same as `notify` would drop it anyway.
1002    ///
1003    /// ```rust
1004    /// use rust_web_server::mcp::McpServer;
1005    ///
1006    /// let server = McpServer::new("my-server", "1.0");
1007    /// server.notify("notifications/message", Some(r#"{"level":"info","data":"hello"}"#));
1008    /// ```
1009    pub fn notify(&self, method: &str, params_json: Option<&str>) {
1010        let json = render_notification(method, params_json);
1011        broadcast_sse_to(&self.sse_clients, &json);
1012    }
1013
1014    /// Push `notifications/resources/updated` for `uri` to every session
1015    /// that called `resources/subscribe` for it — the mechanism behind
1016    /// live-updating resource panels (e.g. Claude Desktop watching a
1017    /// config file or a dashboard resource for changes). Call this from
1018    /// wherever your application actually changes the underlying data a
1019    /// resource represents (a file watcher, a webhook handler, a database
1020    /// trigger poll, ...).
1021    ///
1022    /// A no-op if nobody has subscribed to `uri` — including if every
1023    /// subscriber's `GET /mcp` SSE connection has since disconnected
1024    /// (pruned the same way [`Self::notify`] prunes dead broadcast clients,
1025    /// but the `subscriptions` bookkeeping for `uri` itself is untouched
1026    /// either way; only [`Self::do_resource_unsubscribe`] removes that).
1027    ///
1028    /// ```rust
1029    /// use rust_web_server::mcp::McpServer;
1030    ///
1031    /// let server = McpServer::new("my-server", "1.0");
1032    /// // Elsewhere, e.g. after reloading a watched config file:
1033    /// server.notify_resource_updated("config://main");
1034    /// ```
1035    pub fn notify_resource_updated(&self, uri: &str) {
1036        let session_ids = match self.subscriptions.lock().unwrap().get(uri) {
1037            Some(ids) if !ids.is_empty() => ids.clone(),
1038            _ => return,
1039        };
1040        let params = format!(r#"{{"uri":"{}"}}"#, json_escape(uri));
1041        let json = render_notification("notifications/resources/updated", Some(&params));
1042        send_sse_to_sessions(&self.sse_clients, &session_ids, &json);
1043    }
1044
1045    /// Handle `GET /mcp`: register a new SSE client and return a
1046    /// `text/event-stream` response that streams from its channel until the
1047    /// connection closes. See the module docs' SSE section for the wire
1048    /// details (keep-alive interval, backpressure behavior).
1049    ///
1050    /// Tags the client with this request's `Mcp-Session-Id` header, if
1051    /// present, so [`Self::notify_resource_updated`] can route
1052    /// `notifications/resources/updated` to just the sessions that
1053    /// subscribed via `resources/subscribe` — a client that connects
1054    /// without the header can still receive broadcasts (`.notify()`,
1055    /// `.log()`, `list_changed`) but can never be a subscription target.
1056    fn start_sse_stream(&self, request: &Request) -> Response {
1057        let session_id = request.get_header("Mcp-Session-Id".to_string()).map(|h| h.value.clone());
1058        let (tx, rx) = mpsc::sync_channel::<Vec<u8>>(SSE_CHANNEL_CAPACITY);
1059        self.sse_clients.lock().unwrap().push(SseClient { session_id, sender: tx });
1060
1061        let mut response = Response::new();
1062        response.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
1063        response.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
1064        response.headers.push(Header {
1065            name: Header::_CONTENT_TYPE.to_string(),
1066            value: "text/event-stream".to_string(),
1067        });
1068        response.headers.push(Header {
1069            name: Header::_CACHE_CONTROL.to_string(),
1070            value: "no-cache".to_string(),
1071        });
1072        response.headers.push(Header {
1073            name: "X-Accel-Buffering".to_string(),
1074            value: "no".to_string(),
1075        });
1076        response.stream_pipe = Some(Box::new(SseChannelReader::new(rx)));
1077        response
1078    }
1079
1080    /// Advertise the `logging` capability (`"logging":{}`) in `initialize`'s
1081    /// response, so clients know they can call `logging/setLevel` and expect
1082    /// `notifications/message` log entries over the `GET /mcp` SSE stream.
1083    ///
1084    /// This only changes what's *advertised* — [`Self::log`] pushes log
1085    /// entries regardless of whether this was called, same as [`Self::notify`]
1086    /// works unconditionally. A spec-honest client simply wouldn't send
1087    /// `logging/setLevel` in the first place without seeing the capability.
1088    ///
1089    /// ```rust
1090    /// use rust_web_server::mcp::McpServer;
1091    ///
1092    /// let server = McpServer::new("my-server", "1.0").logging_enabled();
1093    /// ```
1094    pub fn logging_enabled(mut self) -> Self {
1095        self.logging_enabled = true;
1096        self
1097    }
1098
1099    /// Push a `notifications/message` log entry to every client connected to
1100    /// the `GET /mcp` SSE stream, if `level` is at or above the level most
1101    /// recently set via a client's `logging/setLevel` request (or
1102    /// [`LogLevel::Debug`] — i.e. every level — if none has been set yet).
1103    ///
1104    /// `data_json` must already be a valid JSON value (the spec allows any
1105    /// type here, not just an object — a plain string is fine) — it's
1106    /// spliced in verbatim, not escaped or re-serialized. `logger`, if
1107    /// given, identifies the log's source (e.g. a module or subsystem name)
1108    /// and is escaped automatically.
1109    ///
1110    /// ```rust
1111    /// use rust_web_server::mcp::{LogLevel, McpServer};
1112    ///
1113    /// let server = McpServer::new("my-server", "1.0").logging_enabled();
1114    /// server.log(LogLevel::Warning, Some("database"), r#""connection pool exhausted""#);
1115    /// ```
1116    pub fn log(&self, level: LogLevel, logger: Option<&str>, data_json: &str) {
1117        if level < *self.min_log_level.lock().unwrap() {
1118            return;
1119        }
1120        let logger_field = match logger {
1121            Some(l) => format!(r#","logger":"{}""#, json_escape(l)),
1122            None => String::new(),
1123        };
1124        let params = format!(r#"{{"level":"{}"{logger_field},"data":{data_json}}}"#, level.as_str());
1125        self.notify("notifications/message", Some(&params));
1126    }
1127
1128    /// Handle `logging/setLevel`: store the requested minimum level so
1129    /// subsequent [`Self::log`] calls filter against it. Returns
1130    /// `INVALID_PARAMS` for a missing or unrecognized `params.level`.
1131    fn do_set_log_level(&self, body: &str) -> Result<String, (i32, String)> {
1132        let params = json_rpc::extract_raw(body, "params")
1133            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
1134        let level_str = json_rpc::extract_str(&params, "level")
1135            .ok_or((json_rpc::INVALID_PARAMS, "Missing level".to_string()))?;
1136        let level = LogLevel::parse(&level_str)
1137            .ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Unknown log level: {level_str}")))?;
1138        *self.min_log_level.lock().unwrap() = level;
1139        Ok("{}".to_string())
1140    }
1141
1142    // ── dynamic registration ──────────────────────────────────────────────────
1143    //
1144    // Unlike `.tool()`/`.resource()`/`.prompt()` (consuming builders, called
1145    // before the server starts serving requests), these take `&self` and can
1146    // be called at any time from any thread holding a clone of this
1147    // `McpServer` — e.g. after discovering a plugin, connecting to a
1148    // database, or reacting to a hot-reloaded config file. Every clone
1149    // shares the same underlying `Arc<RwLock<Vec<_>>>`, so a mutation made
1150    // through one clone is immediately visible to every other clone,
1151    // including the ones handling concurrent requests on other threads.
1152    //
1153    // Each registration/removal pushes the corresponding
1154    // `notifications/{tools,resources,prompts}/list_changed` event (no
1155    // params, per spec) to every `GET /mcp` SSE client via `.notify()`.
1156
1157    /// Register a callable tool at runtime, exactly like [`Self::tool`] but
1158    /// without needing to own the server (and usable after it's already
1159    /// serving requests). Pushes `notifications/tools/list_changed`.
1160    ///
1161    /// ```rust
1162    /// use rust_web_server::mcp::{McpContent, McpServer};
1163    ///
1164    /// let server = McpServer::new("my-server", "1.0");
1165    ///
1166    /// // Later, from any thread holding a clone of `server`:
1167    /// server.register_tool("refresh_cache", "Reload the in-memory cache", "{}", |_args| {
1168    ///     Ok(McpContent::text("cache refreshed"))
1169    /// });
1170    /// let existed = server.remove_tool("refresh_cache");
1171    /// assert!(existed);
1172    /// ```
1173    pub fn register_tool<F>(&self, name: &str, description: &str, input_schema: &str, handler: F)
1174    where
1175        F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1176    {
1177        self.tools.write().unwrap().push(ToolDef {
1178            name: name.to_string(),
1179            description: description.to_string(),
1180            input_schema: input_schema.to_string(),
1181            annotations: None,
1182            handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
1183        });
1184        self.notify("notifications/tools/list_changed", None);
1185    }
1186
1187    /// Register an `async fn` tool handler at runtime, exactly like
1188    /// [`Self::async_tool`] but usable after the server is already serving
1189    /// requests. Requires the `http2` feature — see `async_tool`'s docs for
1190    /// the async-to-sync bridging details.
1191    #[cfg(feature = "http2")]
1192    pub fn register_async_tool<F, Fut>(&self, name: &str, description: &str, input_schema: &str, handler: F)
1193    where
1194        F: Fn(&str) -> Fut + Send + Sync + 'static,
1195        Fut: Future<Output = Result<McpContent, String>> + Send + 'static,
1196    {
1197        self.async_tools.write().unwrap().push(AsyncToolDef {
1198            name: name.to_string(),
1199            description: description.to_string(),
1200            input_schema: input_schema.to_string(),
1201            annotations: None,
1202            handler: Arc::new(move |args: String| Box::pin(handler(&args))),
1203        });
1204        self.notify("notifications/tools/list_changed", None);
1205    }
1206
1207    /// Remove a previously-registered tool by name — a sync tool registered
1208    /// via [`Self::tool`]/[`Self::register_tool`], or (with the `http2`
1209    /// feature) an async one via [`Self::async_tool`]/[`Self::register_async_tool`];
1210    /// both collections are checked. Returns `true` if a tool with that name
1211    /// existed in either and was removed. Pushes `notifications/tools/list_changed`
1212    /// only when something was actually removed.
1213    pub fn remove_tool(&self, name: &str) -> bool {
1214        #[cfg_attr(not(feature = "http2"), allow(unused_mut))]
1215        let mut removed = {
1216            let mut tools = self.tools.write().unwrap();
1217            let before = tools.len();
1218            tools.retain(|t| t.name != name);
1219            tools.len() != before
1220        };
1221
1222        #[cfg(feature = "http2")]
1223        {
1224            let mut async_tools = self.async_tools.write().unwrap();
1225            let before = async_tools.len();
1226            async_tools.retain(|t| t.name != name);
1227            removed = removed || async_tools.len() != before;
1228        }
1229
1230        if removed {
1231            self.notify("notifications/tools/list_changed", None);
1232        }
1233        removed
1234    }
1235
1236    /// Register a readable resource at runtime, exactly like [`Self::resource`].
1237    /// Pushes `notifications/resources/list_changed`.
1238    pub fn register_resource<F>(&self, uri_template: &str, name: &str, description: &str, handler: F)
1239    where
1240        F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1241    {
1242        self.resources.write().unwrap().push(ResourceDef {
1243            uri_template: uri_template.to_string(),
1244            name: name.to_string(),
1245            description: description.to_string(),
1246            handler: Arc::new(handler),
1247        });
1248        self.notify("notifications/resources/list_changed", None);
1249    }
1250
1251    /// Remove a previously-registered resource by its exact `uri_template`
1252    /// (the same string passed to [`Self::register_resource`]/[`Self::resource`],
1253    /// not a concrete URI). Returns `true` if it existed. Pushes
1254    /// `notifications/resources/list_changed` only when something was removed.
1255    pub fn remove_resource(&self, uri_template: &str) -> bool {
1256        let removed = {
1257            let mut resources = self.resources.write().unwrap();
1258            let before = resources.len();
1259            resources.retain(|r| r.uri_template != uri_template);
1260            resources.len() != before
1261        };
1262        if removed {
1263            self.notify("notifications/resources/list_changed", None);
1264        }
1265        removed
1266    }
1267
1268    /// Register a prompt template at runtime, exactly like [`Self::prompt`]
1269    /// (no argument definitions — use [`Self::remove_prompt`] +
1270    /// [`Self::register_prompt`] if you need to change a prompt's arguments
1271    /// later; there is no dynamic equivalent of [`Self::prompt_with_args`]).
1272    /// Pushes `notifications/prompts/list_changed`.
1273    pub fn register_prompt<F>(&self, name: &str, description: &str, handler: F)
1274    where
1275        F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
1276    {
1277        self.prompts.write().unwrap().push(PromptDef {
1278            name: name.to_string(),
1279            description: description.to_string(),
1280            arguments: vec![],
1281            handler: Arc::new(handler),
1282        });
1283        self.notify("notifications/prompts/list_changed", None);
1284    }
1285
1286    /// Remove a previously-registered prompt by name. Returns `true` if it
1287    /// existed. Pushes `notifications/prompts/list_changed` only when
1288    /// something was removed.
1289    pub fn remove_prompt(&self, name: &str) -> bool {
1290        let removed = {
1291            let mut prompts = self.prompts.write().unwrap();
1292            let before = prompts.len();
1293            prompts.retain(|p| p.name != name);
1294            prompts.len() != before
1295        };
1296        if removed {
1297            self.notify("notifications/prompts/list_changed", None);
1298        }
1299        removed
1300    }
1301
1302    /// Require a bearer token on every request to the MCP endpoint.
1303    ///
1304    /// The client must send `Authorization: Bearer <token>`. Requests with a
1305    /// missing or wrong token receive `401 Unauthorized` before any JSON-RPC
1306    /// processing occurs.
1307    ///
1308    /// Store the token in an environment variable — never hard-code it:
1309    ///
1310    /// ```rust,no_run
1311    /// use rust_web_server::app::App;
1312    /// use rust_web_server::core::New;
1313    ///
1314    /// let app = App::new()
1315    ///     .mcp("my-server", "1.0")
1316    ///     .require_bearer(std::env::var("MCP_TOKEN").expect("MCP_TOKEN not set"));
1317    /// ```
1318    ///
1319    /// Claude Desktop config:
1320    /// ```json
1321    /// { "mcpServers": { "my-server": {
1322    ///     "url": "http://localhost:7878/mcp",
1323    ///     "headers": { "Authorization": "Bearer <token>" }
1324    /// }}}
1325    /// ```
1326    pub fn require_bearer(mut self, token: impl Into<String>) -> Self {
1327        self.auth_token = Some(token.into());
1328        self
1329    }
1330
1331    /// Wrap an existing [`Application`] so that non-MCP requests are forwarded
1332    /// to it instead of the built-in [`App`].
1333    ///
1334    /// Use this when your existing server has custom routes, state, or
1335    /// middleware that you want to keep alongside the MCP endpoint:
1336    ///
1337    /// ```rust,no_run
1338    /// use rust_web_server::app::App;
1339    /// use rust_web_server::mcp::{McpServer, McpContent};
1340    /// use rust_web_server::response::{Response, STATUS_CODE_REASON_PHRASE};
1341    /// use rust_web_server::test_client::TestClient;
1342    ///
1343    /// let existing_app = App::with_state(42u32)
1344    ///     .get("/api/hello", |_req, _params, _conn, _state| {
1345    ///         Response::get_response(&STATUS_CODE_REASON_PHRASE.n200_ok, None, None)
1346    ///     });
1347    ///
1348    /// let server = McpServer::new("my-app", "1.0")
1349    ///     .tool("ping", "Ping", "{}", |_| Ok(McpContent::text("pong")))
1350    ///     .wrap(existing_app);
1351    ///
1352    /// // Both /mcp and /api/hello are now handled by the same server.
1353    /// let client = TestClient::new(server);
1354    /// ```
1355    pub fn wrap(mut self, app: impl Application + Send + Sync + 'static) -> Self {
1356        self.fallback = Some(Arc::new(app));
1357        self
1358    }
1359
1360    /// Override the HTTP path for the MCP endpoint (default `"/mcp"`).
1361    pub fn at(mut self, path: impl Into<String>) -> Self {
1362        self.path = path.into();
1363        self
1364    }
1365
1366    /// Register a callable tool.
1367    ///
1368    /// - `name` — tool identifier (snake_case recommended)
1369    /// - `description` — human-readable description shown to the AI
1370    /// - `input_schema` — JSON Schema object for the tool's arguments
1371    /// - `handler` — closure receiving the raw `arguments` JSON string
1372    ///
1373    /// The handler returns [`McpContent`] on success or an error string.  An
1374    /// error is returned to the client as `isError: true` (not a protocol error).
1375    ///
1376    /// Use [`Self::tool_with_context`] instead if the handler needs the
1377    /// caller's identity, session, or headers.
1378    pub fn tool<F>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
1379    where
1380        F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1381    {
1382        self.tools.write().unwrap().push(ToolDef {
1383            name: name.to_string(),
1384            description: description.to_string(),
1385            input_schema: input_schema.to_string(),
1386            annotations: None,
1387            handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
1388        });
1389        self
1390    }
1391
1392    /// Register an `async fn` tool handler — for a tool whose work is
1393    /// naturally async (an `AsyncClient` HTTP call, an async database
1394    /// query, awaiting another future) rather than forcing it through a
1395    /// blocking call inside a plain [`Self::tool`] handler.
1396    ///
1397    /// Requires the `http2` feature (tokio). `tools/call` bridges into the
1398    /// handler's future via [`crate::async_bridge::block_on_isolated`] —
1399    /// the same mechanism [`crate::proxy::H2ReverseProxy`] and
1400    /// [`crate::async_state::AsyncAppWithState`] already use to call async
1401    /// code from a synchronous [`Application::execute`] — rather than
1402    /// `tokio::task::block_in_place`, which panics outside a `multi_thread`
1403    /// runtime; `block_on_isolated` works under any runtime flavor,
1404    /// including `current_thread`.
1405    ///
1406    /// Like [`Self::tool`] (not [`Self::tool_with_context`]), the handler
1407    /// only receives `arguments` — there is no async equivalent of
1408    /// `tool_with_context` or `tool_annotated` yet.
1409    ///
1410    /// ```rust,no_run
1411    /// # #[cfg(feature = "http2")]
1412    /// # {
1413    /// use rust_web_server::mcp::{McpContent, McpServer};
1414    ///
1415    /// let server = McpServer::new("my-server", "1.0")
1416    ///     .async_tool("call_api", "Call an external API", "{}", |_args: &str| async move {
1417    ///         Ok(McpContent::text("response"))
1418    ///     });
1419    /// # }
1420    /// ```
1421    #[cfg(feature = "http2")]
1422    pub fn async_tool<F, Fut>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
1423    where
1424        F: Fn(&str) -> Fut + Send + Sync + 'static,
1425        Fut: Future<Output = Result<McpContent, String>> + Send + 'static,
1426    {
1427        self.async_tools.write().unwrap().push(AsyncToolDef {
1428            name: name.to_string(),
1429            description: description.to_string(),
1430            input_schema: input_schema.to_string(),
1431            annotations: None,
1432            handler: Arc::new(move |args: String| Box::pin(handler(&args))),
1433        });
1434        self
1435    }
1436
1437    /// Register a callable tool with [`ToolAnnotations`] — behavioral hints
1438    /// (read-only, destructive, idempotent, open-world) that MCP clients use
1439    /// to decide whether to warn or confirm before calling it. Otherwise
1440    /// identical to [`Self::tool`] — the handler still only receives
1441    /// `arguments`, not [`McpContext`] (there is currently no single builder
1442    /// combining annotations with per-request context; call [`Self::tool_with_context`]
1443    /// instead if you need context and don't need annotations).
1444    ///
1445    /// ```rust,no_run
1446    /// use rust_web_server::mcp::{McpContent, McpServer, ToolAnnotations};
1447    ///
1448    /// let server = McpServer::new("my-server", "1.0")
1449    ///     .tool_annotated(
1450    ///         "delete_file",
1451    ///         "Delete a file from disk",
1452    ///         r#"{"type":"object","properties":{"path":{"type":"string"}},"required":["path"]}"#,
1453    ///         ToolAnnotations {
1454    ///             destructive_hint: Some(true),
1455    ///             read_only_hint: Some(false),
1456    ///             idempotent_hint: Some(true), // deleting twice = deleting once
1457    ///             ..Default::default()
1458    ///         },
1459    ///         |_args| Ok(McpContent::text("deleted")),
1460    ///     );
1461    /// ```
1462    pub fn tool_annotated<F>(
1463        self,
1464        name: &str,
1465        description: &str,
1466        input_schema: &str,
1467        annotations: ToolAnnotations,
1468        handler: F,
1469    ) -> Self
1470    where
1471        F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1472    {
1473        self.tools.write().unwrap().push(ToolDef {
1474            name: name.to_string(),
1475            description: description.to_string(),
1476            input_schema: input_schema.to_string(),
1477            annotations: Some(annotations),
1478            handler: Arc::new(move |_ctx: McpContext, args: &str| handler(args)),
1479        });
1480        self
1481    }
1482
1483    /// Register a callable tool whose handler also receives [`McpContext`] —
1484    /// caller identity/session info derived from this request's headers and
1485    /// whatever `clientInfo` this session sent at `initialize` time.
1486    ///
1487    /// Same `name`/`description`/`input_schema` semantics as [`Self::tool`];
1488    /// the only difference is the handler's first parameter.
1489    ///
1490    /// ```rust,no_run
1491    /// use rust_web_server::mcp::{McpContent, McpServer};
1492    ///
1493    /// let server = McpServer::new("my-server", "1.0")
1494    ///     .tool_with_context(
1495    ///         "whoami",
1496    ///         "Report the caller's client info",
1497    ///         "{}",
1498    ///         |ctx, _args| {
1499    ///             let name = ctx.client_name.as_deref().unwrap_or("unknown client");
1500    ///             Ok(McpContent::text(format!("Called by {name}")))
1501    ///         },
1502    ///     );
1503    /// ```
1504    pub fn tool_with_context<F>(self, name: &str, description: &str, input_schema: &str, handler: F) -> Self
1505    where
1506        F: Fn(McpContext, &str) -> Result<McpContent, String> + Send + Sync + 'static,
1507    {
1508        self.tools.write().unwrap().push(ToolDef {
1509            name: name.to_string(),
1510            description: description.to_string(),
1511            input_schema: input_schema.to_string(),
1512            annotations: None,
1513            handler: Arc::new(handler),
1514        });
1515        self
1516    }
1517
1518    /// Register a readable resource.
1519    ///
1520    /// `uri_template` uses `{param}` placeholders, e.g. `"user://{id}"`.
1521    /// The handler receives the full concrete URI string.
1522    pub fn resource<F>(self, uri_template: &str, name: &str, description: &str, handler: F) -> Self
1523    where
1524        F: Fn(&str) -> Result<McpContent, String> + Send + Sync + 'static,
1525    {
1526        self.resources.write().unwrap().push(ResourceDef {
1527            uri_template: uri_template.to_string(),
1528            name: name.to_string(),
1529            description: description.to_string(),
1530            handler: Arc::new(handler),
1531        });
1532        self
1533    }
1534
1535    /// Register a prompt template.
1536    ///
1537    /// The handler receives the raw `arguments` JSON string and returns a
1538    /// list of [`PromptMessage`] values.
1539    pub fn prompt<F>(self, name: &str, description: &str, handler: F) -> Self
1540    where
1541        F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
1542    {
1543        self.prompts.write().unwrap().push(PromptDef {
1544            name: name.to_string(),
1545            description: description.to_string(),
1546            arguments: vec![],
1547            handler: Arc::new(handler),
1548        });
1549        self
1550    }
1551
1552    /// Register a prompt template with explicit argument definitions.
1553    pub fn prompt_with_args<F>(
1554        self,
1555        name: &str,
1556        description: &str,
1557        args: Vec<PromptArgDef>,
1558        handler: F,
1559    ) -> Self
1560    where
1561        F: Fn(&str) -> Result<Vec<PromptMessage>, String> + Send + Sync + 'static,
1562    {
1563        self.prompts.write().unwrap().push(PromptDef {
1564            name: name.to_string(),
1565            description: description.to_string(),
1566            arguments: args,
1567            handler: Arc::new(handler),
1568        });
1569        self
1570    }
1571
1572    /// Register an argument-completion provider for one named argument of a
1573    /// tool or prompt, so clients like Cursor and VS Code can offer
1574    /// autocomplete while the user fills in that argument.
1575    ///
1576    /// `ref_type` is `"tool"` or `"prompt"` — matched against the incoming
1577    /// `completion/complete` request's `ref.type` (`"ref/tool"`/`"ref/prompt"`
1578    /// on the wire) with the `"ref/"` prefix stripped. `ref_name` is the
1579    /// tool or prompt name this applies to. The handler receives the
1580    /// argument's name and whatever partial value the user has typed so
1581    /// far, and returns candidate completion strings (or an error, mapped
1582    /// to a JSON-RPC `INVALID_PARAMS` response).
1583    ///
1584    /// `initialize` advertises the `completions` capability automatically
1585    /// once at least one `.completion()` has been registered — there's no
1586    /// separate opt-in flag to remember.
1587    ///
1588    /// ```rust
1589    /// use rust_web_server::mcp::McpServer;
1590    ///
1591    /// let server = McpServer::new("my-server", "1.0")
1592    ///     .completion("tool", "deploy", |arg_name, _partial| {
1593    ///         match arg_name {
1594    ///             "region" => Ok(vec!["us-east-1".to_string(), "eu-west-1".to_string()]),
1595    ///             _ => Ok(vec![]),
1596    ///         }
1597    ///     });
1598    /// ```
1599    pub fn completion<F>(self, ref_type: &str, ref_name: &str, handler: F) -> Self
1600    where
1601        F: Fn(&str, &str) -> Result<Vec<String>, String> + Send + Sync + 'static,
1602    {
1603        self.completions.write().unwrap().push(CompletionDef {
1604            ref_type: ref_type.to_string(),
1605            ref_name: ref_name.to_string(),
1606            handler: Arc::new(handler),
1607        });
1608        self
1609    }
1610
1611    // ── request dispatch ──────────────────────────────────────────────────────
1612
1613    /// Process a raw JSON-RPC body and return an HTTP response.
1614    ///
1615    /// Equivalent to [`Self::handle_request_with_context`] with an empty
1616    /// [`McpContext`] — tool handlers registered via
1617    /// [`Self::tool_with_context`] will see every field as `None`. Prefer
1618    /// calling through [`Application::execute`] (i.e. actually serving HTTP
1619    /// requests) when you need real per-request context; this method exists
1620    /// for calling the JSON-RPC layer directly, e.g. in tests.
1621    pub fn handle_request(&self, body: &str) -> Response {
1622        self.handle_request_with_context(body, McpContext::default())
1623    }
1624
1625    /// Process a raw JSON-RPC body with an explicit [`McpContext`] and return
1626    /// an HTTP response. [`Self::execute`] calls this with a context built
1627    /// from the request's headers and this session's stored `clientInfo`;
1628    /// [`Self::handle_request`] calls this with an empty context.
1629    ///
1630    /// On a successful `initialize`, this mints a new session id (reusing
1631    /// [`crate::request_id::generate_request_id`]'s ID generator), records
1632    /// `params.clientInfo` under it, and returns the id in an
1633    /// `Mcp-Session-Id` response header — the client is expected to echo that
1634    /// header back on subsequent requests so later `tools/call`s in the same
1635    /// session can look their `clientInfo` back up.
1636    pub fn handle_request_with_context(&self, body: &str, ctx: McpContext) -> Response {
1637        let trimmed = body.trim_start();
1638        if trimmed.starts_with('[') {
1639            return self.handle_batch(trimmed, ctx);
1640        }
1641
1642        let id = json_rpc::extract_id(body);
1643
1644        let method = match json_rpc::extract_str(body, "method") {
1645            Some(m) => m,
1646            None => {
1647                // No `method` — either malformed, or a JSON-RPC *response*
1648                // to a sampling/createMessage request this server sent
1649                // earlier (responses never carry `method`).
1650                if let Some(id) = &id {
1651                    if self.try_deliver_sampling_response(id, body) {
1652                        return no_content();
1653                    }
1654                }
1655                return rpc_error(None, json_rpc::INVALID_REQUEST, "Missing method");
1656            }
1657        };
1658
1659        if method == "notifications/cancelled" {
1660            self.handle_cancellation(body);
1661            return no_content();
1662        }
1663
1664        if method == "notifications/roots/list_changed" {
1665            self.invalidate_roots_cache(&ctx.session_id);
1666            return no_content();
1667        }
1668
1669        // Notifications have no `id` — acknowledge with 202 and no body.
1670        if method == "notifications/initialized" || (id.is_none() && method != "ping") {
1671            return no_content();
1672        }
1673
1674        let result = self.dispatch_with_cancellation(&method, body, ctx, &id);
1675        let id_str = id.as_deref().unwrap_or("null");
1676        let is_ok = result.is_ok();
1677
1678        let mut response = json_response(&Self::format_result(id_str, &result));
1679
1680        if method == "initialize" && is_ok {
1681            self.start_session(body, &mut response);
1682        }
1683
1684        response
1685    }
1686
1687    /// Process a JSON-RPC 2.0 batch request — a top-level JSON array of
1688    /// request objects sent in a single `POST /mcp` body, per the JSON-RPC
1689    /// batch spec that MCP inherits. Each element is dispatched exactly as
1690    /// [`Self::handle_request_with_context`] would dispatch it standalone;
1691    /// notifications (no `id`) contribute no entry to the response array,
1692    /// same as they'd get no response body outside a batch.
1693    ///
1694    /// An empty array (`[]`) is itself an invalid request per the JSON-RPC
1695    /// spec, so it gets one `Invalid Request` error object back rather than
1696    /// an empty array. A batch made up entirely of notifications produces no
1697    /// response body at all (`202 Accepted`), matching a single notification.
1698    ///
1699    /// If the batch contains a successful `initialize` call, the *first* one
1700    /// mints a session and attaches `Mcp-Session-Id` to the overall response,
1701    /// same as a standalone `initialize` would — sending more than one
1702    /// `initialize` in a batch is unusual and only the first is honored for
1703    /// session purposes, since one HTTP response can only carry one session id.
1704    fn handle_batch(&self, array_body: &str, ctx: McpContext) -> Response {
1705        let elements = json_rpc::split_array_elements(array_body);
1706        if elements.is_empty() {
1707            return rpc_error(None, json_rpc::INVALID_REQUEST, "Invalid Request");
1708        }
1709
1710        let mut parts: Vec<String> = Vec::new();
1711        let mut session_init_body: Option<String> = None;
1712
1713        for elem in &elements {
1714            let id = json_rpc::extract_id(elem);
1715
1716            let method = match json_rpc::extract_str(elem, "method") {
1717                Some(m) => m,
1718                None => {
1719                    if let Some(id) = &id {
1720                        if self.try_deliver_sampling_response(id, elem) {
1721                            continue; // delivered; no response entry, same as any notification
1722                        }
1723                    }
1724                    parts.push(Self::format_result(
1725                        "null",
1726                        &Err((json_rpc::INVALID_REQUEST, "Missing method".to_string())),
1727                    ));
1728                    continue;
1729                }
1730            };
1731
1732            if method == "notifications/cancelled" {
1733                self.handle_cancellation(elem);
1734                continue;
1735            }
1736
1737            if method == "notifications/roots/list_changed" {
1738                self.invalidate_roots_cache(&ctx.session_id);
1739                continue;
1740            }
1741
1742            if method == "notifications/initialized" || (id.is_none() && method != "ping") {
1743                continue;
1744            }
1745
1746            let result = self.dispatch_with_cancellation(&method, elem, ctx.clone(), &id);
1747            let id_str = id.as_deref().unwrap_or("null");
1748            let is_ok = result.is_ok();
1749
1750            if method == "initialize" && is_ok && session_init_body.is_none() {
1751                session_init_body = Some(elem.clone());
1752            }
1753
1754            parts.push(Self::format_result(id_str, &result));
1755        }
1756
1757        if parts.is_empty() {
1758            // Every element was a notification — no response body, same as a
1759            // single standalone notification.
1760            return no_content();
1761        }
1762
1763        let mut response = json_response(&format!("[{}]", parts.join(",")));
1764        if let Some(init_body) = session_init_body {
1765            self.start_session(&init_body, &mut response);
1766        }
1767        response
1768    }
1769
1770    /// Dispatch one already-parsed JSON-RPC `method` against `body` (the raw
1771    /// single-object message, whether it arrived standalone or as one element
1772    /// of a batch) and return the JSON-RPC `result` payload or an error.
1773    /// Shared by [`Self::handle_request_with_context`] and [`Self::handle_batch`]
1774    /// so the method table exists in exactly one place.
1775    fn dispatch(&self, method: &str, body: &str, ctx: McpContext) -> Result<String, (i32, String)> {
1776        match method {
1777            "initialize"     => self.do_initialize(body),
1778            "ping"           => Ok("{}".to_string()),
1779            "tools/list"     => self.do_tools_list(body),
1780            "tools/call"     => self.do_tools_call(body, ctx),
1781            "resources/list" => self.do_resources_list(body),
1782            "resources/read" => self.do_resources_read(body),
1783            "resources/subscribe"   => self.do_resource_subscribe(body, ctx.session_id),
1784            "resources/unsubscribe" => self.do_resource_unsubscribe(body, ctx.session_id),
1785            "prompts/list"   => self.do_prompts_list(body),
1786            "prompts/get"    => self.do_prompts_get(body),
1787            "logging/setLevel" => self.do_set_log_level(body),
1788            "completion/complete" => self.do_completion(body),
1789            _                => Err((json_rpc::METHOD_NOT_FOUND, format!("Unknown method: {method}"))),
1790        }
1791    }
1792
1793    /// Wraps [`Self::dispatch`] for one request, additionally registering a
1794    /// cancellation flag for `tools/call` (keyed by `id`, guaranteed `Some`
1795    /// for `tools/call` — a notification-shaped `tools/call` with no `id`
1796    /// never reaches this far, see the notification checks in
1797    /// [`Self::handle_request_with_context`]/[`Self::handle_batch`]) so a
1798    /// later `notifications/cancelled` referencing this exact request can
1799    /// flip it. The entry is removed again once dispatch returns, whether
1800    /// the handler checked the flag or not — this map never accumulates
1801    /// stale entries the way `sessions`/`sse_clients` can.
1802    fn dispatch_with_cancellation(
1803        &self,
1804        method: &str,
1805        body: &str,
1806        ctx: McpContext,
1807        id: &Option<String>,
1808    ) -> Result<String, (i32, String)> {
1809        let Some(id_str) = (method == "tools/call").then_some(id.as_ref()).flatten() else {
1810            return self.dispatch(method, body, ctx);
1811        };
1812
1813        let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
1814        self.cancellations.lock().unwrap().insert(id_str.clone(), flag.clone());
1815        let ctx = McpContext { cancellation: Some(flag), ..ctx };
1816        let result = self.dispatch(method, body, ctx);
1817        self.cancellations.lock().unwrap().remove(id_str);
1818        result
1819    }
1820
1821    /// Handle `notifications/cancelled`: look up `params.requestId` (the
1822    /// spec allows `string | number`, so this is matched as a raw JSON
1823    /// token, the same way [`McpContext::progress_token`] is) in
1824    /// `cancellations` and flip its flag if the request is still in flight.
1825    /// Silently does nothing for an unknown/already-finished request id —
1826    /// the target call may simply have already completed naturally, which
1827    /// isn't an error.
1828    fn handle_cancellation(&self, body: &str) {
1829        let Some(params) = json_rpc::extract_raw(body, "params") else { return };
1830        let Some(request_id) = json_rpc::extract_raw(&params, "requestId") else { return };
1831        if let Some(flag) = self.cancellations.lock().unwrap().get(&request_id) {
1832            flag.store(true, std::sync::atomic::Ordering::Relaxed);
1833        }
1834    }
1835
1836    /// Handle `notifications/roots/list_changed`: clear this session's
1837    /// cached `roots/list` result (if any), so the next
1838    /// [`McpContext::list_roots`] call in this session does a fresh round
1839    /// trip instead of serving stale data. Correlated purely by this
1840    /// request's own `Mcp-Session-Id` (`session_id`) — unlike
1841    /// `notifications/cancelled`, this notification carries no params of
1842    /// its own to key off of; it's about "your cache for *this connection*
1843    /// is stale," not any other request.
1844    fn invalidate_roots_cache(&self, session_id: &Option<String>) {
1845        let Some(sid) = session_id else { return };
1846        if let Some(info) = self.sessions.lock().unwrap().get_mut(sid) {
1847            info.roots = None;
1848        }
1849    }
1850
1851    /// If `body` is a JSON-RPC *response* (no `method`, by definition — see
1852    /// [`Self::handle_request_with_context`]) to a `sampling/createMessage`
1853    /// request this server sent and is still waiting on (`id` found in
1854    /// `pending_replies`), deliver it to the blocked [`McpContext::sample`]
1855    /// call and return `true`. Returns `false` for any `id` this server
1856    /// isn't tracking — the caller still needs to treat that as a genuine
1857    /// malformed/unrecognized message.
1858    fn try_deliver_sampling_response(&self, id: &str, body: &str) -> bool {
1859        let sender = match self.pending_replies.lock().unwrap().remove(id) {
1860            Some(s) => s,
1861            None => return false,
1862        };
1863        let payload = match json_rpc::extract_raw(body, "result") {
1864            Some(result) => Ok(result),
1865            None => {
1866                let message = json_rpc::extract_raw(body, "error")
1867                    .and_then(|e| json_rpc::extract_str(&e, "message"))
1868                    .unwrap_or_else(|| "sampling/createMessage request failed".to_string());
1869                Err(message)
1870            }
1871        };
1872        let _ = sender.send(payload); // the waiter may have already timed out and dropped rx
1873        true
1874    }
1875
1876    /// Render one JSON-RPC 2.0 response object — `{"jsonrpc":"2.0","result":...,"id":...}`
1877    /// or the `error` shape — from a dispatch result and its request's `id` (already
1878    /// rendered as a raw JSON token, e.g. `"1"`, `"\"abc\""`, or `"null"`).
1879    fn format_result(id_str: &str, result: &Result<String, (i32, String)>) -> String {
1880        match result {
1881            Ok(result_json) => format!(
1882                r#"{{"jsonrpc":"2.0","result":{result_json},"id":{id_str}}}"#
1883            ),
1884            Err((code, msg)) => {
1885                let escaped = json_escape(msg);
1886                format!(
1887                    r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"{escaped}"}},"id":{id_str}}}"#
1888                )
1889            }
1890        }
1891    }
1892
1893    /// Mint a new session id, record `body`'s `params.clientInfo` under it
1894    /// (logging the caller's identity), and attach the id to `response` as
1895    /// an `Mcp-Session-Id` header. Called once, from
1896    /// [`Self::handle_request_with_context`], right after a successful
1897    /// `initialize`.
1898    fn start_session(&self, body: &str, response: &mut Response) {
1899        let params = json_rpc::extract_raw(body, "params");
1900        let client_info = params.as_deref().and_then(|p| json_rpc::extract_raw(p, "clientInfo"));
1901        let (name, version) = match &client_info {
1902            Some(info) => (
1903                json_rpc::extract_str(info, "name"),
1904                json_rpc::extract_str(info, "version"),
1905            ),
1906            None => (None, None),
1907        };
1908        let capabilities = params.as_deref().and_then(|p| json_rpc::extract_raw(p, "capabilities"));
1909        let supports_sampling = capabilities.as_deref()
1910            .and_then(|c| json_rpc::extract_raw(c, "sampling"))
1911            .is_some();
1912        let supports_roots = capabilities.as_deref()
1913            .and_then(|c| json_rpc::extract_raw(c, "roots"))
1914            .is_some();
1915
1916        eprintln!(
1917            "[mcp] initialize from client {} v{}",
1918            name.as_deref().unwrap_or("unknown"),
1919            version.as_deref().unwrap_or("unknown"),
1920        );
1921
1922        let session_id = crate::request_id::generate_request_id();
1923        self.sessions
1924            .lock()
1925            .unwrap()
1926            .insert(session_id.clone(), StoredClientInfo { name, version, supports_sampling, supports_roots, roots: None });
1927
1928        response.headers.push(Header {
1929            name: "Mcp-Session-Id".to_string(),
1930            value: session_id,
1931        });
1932    }
1933
1934    // ── method handlers ───────────────────────────────────────────────────────
1935
1936    /// Handle `initialize`. Per spec, the server must inspect the client's
1937    /// requested `protocolVersion` and respond with the version it actually
1938    /// supports — allowing the client to abort the session if incompatible —
1939    /// rather than blindly echoing `PROTOCOL_VERSION` regardless of what was
1940    /// asked for.
1941    ///
1942    /// This server implements exactly one protocol version, so "negotiation"
1943    /// here means: if the client asked for that same version, confirm it;
1944    /// otherwise tell the client the version we actually speak (older *or*
1945    /// newer than what was requested), which is always the lower of the two
1946    /// — version strings are `YYYY-MM-DD` dates, so a plain string comparison
1947    /// already orders them correctly with no date parsing needed.
1948    ///
1949    /// `clientInfo` is *not* handled here — [`Self::handle_request_with_context`]
1950    /// extracts and stores it (under a freshly minted session id) after this
1951    /// returns, so it's only ever parsed out of `body` once per call.
1952    fn do_initialize(&self, body: &str) -> Result<String, (i32, String)> {
1953        let params = json_rpc::extract_raw(body, "params");
1954
1955        let client_version = params.as_deref().and_then(|p| json_rpc::extract_str(p, "protocolVersion"));
1956
1957        let negotiated_version: &str = match client_version.as_deref() {
1958            Some(v) if v < PROTOCOL_VERSION => v,
1959            _ => PROTOCOL_VERSION,
1960        };
1961
1962        let logging_cap = if self.logging_enabled { r#","logging":{}"# } else { "" };
1963        // completions is advertised iff at least one .completion() has been registered —
1964        // no separate opt-in flag needed, unlike logging: if nothing was registered,
1965        // completion/complete would just return empty results for everything anyway.
1966        let completions_cap = if self.completions.read().unwrap().is_empty() { "" } else { r#","completions":{}"# };
1967        // listChanged is always true: register_tool/remove_tool (and the resource/prompt
1968        // equivalents) are always available, unlike logging which is opt-in via
1969        // .logging_enabled(). resources.subscribe is also always true now that
1970        // resources/subscribe and resources/unsubscribe are implemented (MCP_TODO.md's TODO-14).
1971        let caps = format!(
1972            r#"{{"tools":{{"listChanged":true}},"resources":{{"subscribe":true,"listChanged":true}},"prompts":{{"listChanged":true}}{logging_cap}{completions_cap}}}"#
1973        );
1974        Ok(format!(
1975            r#"{{"protocolVersion":"{}","capabilities":{caps},"serverInfo":{{"name":"{}","version":"{}"}}}}"#,
1976            json_escape(negotiated_version),
1977            json_escape(&self.server_name),
1978            json_escape(&self.server_version),
1979        ))
1980    }
1981
1982    fn do_tools_list(&self, body: &str) -> Result<String, (i32, String)> {
1983        #[cfg_attr(not(feature = "http2"), allow(unused_mut))]
1984        let mut items: Vec<String> = self.tools.read().unwrap().iter()
1985            .map(|t| Self::render_tool_list_entry(&t.name, &t.description, &t.input_schema, t.annotations))
1986            .collect();
1987
1988        #[cfg(feature = "http2")]
1989        items.extend(self.async_tools.read().unwrap().iter()
1990            .map(|t| Self::render_tool_list_entry(&t.name, &t.description, &t.input_schema, t.annotations)));
1991
1992        let (page, next_cursor) = self.paginate(&items, body)?;
1993        Ok(format!(r#"{{"tools":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
1994    }
1995
1996    /// Render one `tools/list` entry — shared by the sync (`tools`) and
1997    /// (with the `http2` feature) async (`async_tools`) collections, which
1998    /// are otherwise identical from the client's point of view.
1999    fn render_tool_list_entry(name: &str, description: &str, input_schema: &str, annotations: Option<ToolAnnotations>) -> String {
2000        let annotations_field = match annotations {
2001            Some(a) => format!(r#","annotations":{}"#, a.to_json()),
2002            None => String::new(),
2003        };
2004        format!(
2005            r#"{{"name":"{}","description":"{}","inputSchema":{}{}}}"#,
2006            json_escape(name), json_escape(description), input_schema, annotations_field,
2007        )
2008    }
2009
2010    fn do_tools_call(&self, body: &str, ctx: McpContext) -> Result<String, (i32, String)> {
2011        let params = json_rpc::extract_raw(body, "params")
2012            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2013        let name = json_rpc::extract_str(&params, "name")
2014            .ok_or((json_rpc::INVALID_PARAMS, "Missing tool name".to_string()))?;
2015        let args = json_rpc::extract_raw(&params, "arguments")
2016            .unwrap_or_else(|| "{}".to_string());
2017
2018        // `_meta.progressToken` (string or number, per spec) — stored raw so
2019        // `McpContext::report_progress` can splice it back verbatim.
2020        let progress_token = json_rpc::extract_raw(&params, "_meta")
2021            .and_then(|meta| json_rpc::extract_raw(&meta, "progressToken"));
2022        let ctx = McpContext { progress_token, ..ctx };
2023
2024        let sync_handler = {
2025            let tools = self.tools.read().unwrap();
2026            tools.iter().find(|t| t.name == name).map(|t| t.handler.clone())
2027        };
2028        if let Some(handler) = sync_handler {
2029            return Ok(Self::format_tool_result(handler(ctx, &args)));
2030        }
2031
2032        #[cfg(feature = "http2")]
2033        {
2034            let async_handler = {
2035                let async_tools = self.async_tools.read().unwrap();
2036                async_tools.iter().find(|t| t.name == name).map(|t| t.handler.clone())
2037            };
2038            if let Some(handler) = async_handler {
2039                let args_owned = args.clone();
2040                let result = crate::async_bridge::block_on_isolated(move || handler(args_owned));
2041                return Ok(Self::format_tool_result(result));
2042            }
2043        }
2044
2045        Err((json_rpc::INVALID_PARAMS, format!("Unknown tool: {name}")))
2046    }
2047
2048    /// Render a tool handler's result as the spec's `tools/call` shape —
2049    /// `{"content":[...],"isError":false}` on success, or `isError:true`
2050    /// with the error message as a text content block. Shared by the sync
2051    /// and (with `http2`) async `tools/call` dispatch paths.
2052    fn format_tool_result(result: Result<McpContent, String>) -> String {
2053        match result {
2054            Ok(c) => format!(
2055                r#"{{"content":[{}],"isError":false}}"#,
2056                c.to_content_json(),
2057            ),
2058            Err(e) => {
2059                let escaped = json_escape(&e);
2060                format!(
2061                    r#"{{"content":[{{"type":"text","text":"{escaped}"}}],"isError":true}}"#
2062                )
2063            }
2064        }
2065    }
2066
2067    fn do_resources_list(&self, body: &str) -> Result<String, (i32, String)> {
2068        let items: Vec<String> = self.resources.read().unwrap().iter().map(|r| {
2069            format!(
2070                r#"{{"uri":"{}","name":"{}","description":"{}","mimeType":"text/plain"}}"#,
2071                json_escape(&r.uri_template),
2072                json_escape(&r.name),
2073                json_escape(&r.description),
2074            )
2075        }).collect();
2076        let (page, next_cursor) = self.paginate(&items, body)?;
2077        Ok(format!(r#"{{"resources":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2078    }
2079
2080    fn do_resources_read(&self, body: &str) -> Result<String, (i32, String)> {
2081        let params = json_rpc::extract_raw(body, "params")
2082            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2083        let uri = json_rpc::extract_str(&params, "uri")
2084            .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2085
2086        let handler = {
2087            let resources = self.resources.read().unwrap();
2088            resources.iter().find(|r| uri_matches(&r.uri_template, &uri)).map(|r| r.handler.clone())
2089        }.ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Resource not found: {uri}")))?;
2090
2091        match handler(&uri) {
2092            Ok(c) => {
2093                let text_esc = json_escape(&c.text);
2094                let uri_esc  = json_escape(&uri);
2095                Ok(format!(
2096                    r#"{{"contents":[{{"uri":"{uri_esc}","mimeType":"{}","text":"{text_esc}"}}]}}"#,
2097                    c.mime(),
2098                ))
2099            }
2100            Err(e) => Err((json_rpc::INVALID_PARAMS, e)),
2101        }
2102    }
2103
2104    /// Handle `resources/subscribe`: record that `session_id` (this
2105    /// request's `Mcp-Session-Id`) wants `notifications/resources/updated`
2106    /// pushed whenever [`Self::notify_resource_updated`] is called for
2107    /// `params.uri`. Requires a session id — without one there's no way to
2108    /// later match this subscription to a specific `GET /mcp` SSE
2109    /// connection, so a client that never sent `Mcp-Session-Id` gets
2110    /// `INVALID_PARAMS` rather than a subscription that can never fire.
2111    fn do_resource_subscribe(&self, body: &str, session_id: Option<String>) -> Result<String, (i32, String)> {
2112        let params = json_rpc::extract_raw(body, "params")
2113            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2114        let uri = json_rpc::extract_str(&params, "uri")
2115            .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2116        let session_id = session_id.ok_or((
2117            json_rpc::INVALID_PARAMS,
2118            "resources/subscribe requires an Mcp-Session-Id header (call initialize first)".to_string(),
2119        ))?;
2120
2121        let mut subs = self.subscriptions.lock().unwrap();
2122        let subscribers = subs.entry(uri).or_default();
2123        if !subscribers.contains(&session_id) {
2124            subscribers.push(session_id);
2125        }
2126        Ok("{}".to_string())
2127    }
2128
2129    /// Handle `resources/unsubscribe`: the inverse of
2130    /// [`Self::do_resource_subscribe`]. Removing the last subscriber for a
2131    /// URI drops the URI's entry entirely rather than leaving an empty
2132    /// `Vec` behind.
2133    fn do_resource_unsubscribe(&self, body: &str, session_id: Option<String>) -> Result<String, (i32, String)> {
2134        let params = json_rpc::extract_raw(body, "params")
2135            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2136        let uri = json_rpc::extract_str(&params, "uri")
2137            .ok_or((json_rpc::INVALID_PARAMS, "Missing uri".to_string()))?;
2138        let session_id = session_id.ok_or((
2139            json_rpc::INVALID_PARAMS,
2140            "resources/unsubscribe requires an Mcp-Session-Id header".to_string(),
2141        ))?;
2142
2143        let mut subs = self.subscriptions.lock().unwrap();
2144        if let Some(subscribers) = subs.get_mut(&uri) {
2145            subscribers.retain(|s| s != &session_id);
2146            if subscribers.is_empty() {
2147                subs.remove(&uri);
2148            }
2149        }
2150        Ok("{}".to_string())
2151    }
2152
2153    fn do_prompts_list(&self, body: &str) -> Result<String, (i32, String)> {
2154        let items: Vec<String> = self.prompts.read().unwrap().iter().map(|p| {
2155            let arg_defs: Vec<String> = p.arguments.iter().map(|a| {
2156                format!(
2157                    r#"{{"name":"{}","description":"{}","required":{}}}"#,
2158                    json_escape(&a.name),
2159                    json_escape(&a.description),
2160                    a.required,
2161                )
2162            }).collect();
2163            format!(
2164                r#"{{"name":"{}","description":"{}","arguments":[{}]}}"#,
2165                json_escape(&p.name),
2166                json_escape(&p.description),
2167                arg_defs.join(","),
2168            )
2169        }).collect();
2170        let (page, next_cursor) = self.paginate(&items, body)?;
2171        Ok(format!(r#"{{"prompts":[{}]{}}}"#, page.join(","), next_cursor_json(&next_cursor)))
2172    }
2173
2174    /// Slice `items` (already-rendered JSON object strings for one
2175    /// `*/list` response) according to [`Self::page_size`] and this
2176    /// request's `params.cursor`, returning the page and — if more items
2177    /// remain — the opaque `nextCursor` to embed in the response.
2178    ///
2179    /// Without a configured `page_size`, always returns every item and no
2180    /// cursor, i.e. pagination is fully opt-in.
2181    fn paginate<'a>(&self, items: &'a [String], body: &str) -> Result<(&'a [String], Option<String>), (i32, String)> {
2182        let page_size = match self.page_size {
2183            Some(n) => n,
2184            None => return Ok((items, None)),
2185        };
2186
2187        let cursor = json_rpc::extract_raw(body, "params")
2188            .and_then(|p| json_rpc::extract_str(&p, "cursor"));
2189
2190        let offset = match cursor {
2191            Some(c) => decode_cursor(&c)
2192                .ok_or((json_rpc::INVALID_PARAMS, "Invalid cursor".to_string()))?,
2193            None => 0,
2194        };
2195
2196        if offset >= items.len() {
2197            return Ok((&[], None));
2198        }
2199
2200        let end = (offset + page_size).min(items.len());
2201        let next_cursor = if end < items.len() { Some(encode_cursor(end)) } else { None };
2202        Ok((&items[offset..end], next_cursor))
2203    }
2204
2205    fn do_prompts_get(&self, body: &str) -> Result<String, (i32, String)> {
2206        let params = json_rpc::extract_raw(body, "params")
2207            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2208        let name = json_rpc::extract_str(&params, "name")
2209            .ok_or((json_rpc::INVALID_PARAMS, "Missing prompt name".to_string()))?;
2210        let args = json_rpc::extract_raw(&params, "arguments")
2211            .unwrap_or_else(|| "{}".to_string());
2212
2213        let (description, handler) = {
2214            let prompts = self.prompts.read().unwrap();
2215            prompts.iter().find(|p| p.name == name).map(|p| (p.description.clone(), p.handler.clone()))
2216        }.ok_or_else(|| (json_rpc::INVALID_PARAMS, format!("Unknown prompt: {name}")))?;
2217
2218        match handler(&args) {
2219            Ok(msgs) => {
2220                let msg_jsons: Vec<String> = msgs.iter().map(|m| m.to_json()).collect();
2221                Ok(format!(
2222                    r#"{{"description":"{}","messages":[{}]}}"#,
2223                    json_escape(&description),
2224                    msg_jsons.join(","),
2225                ))
2226            }
2227            Err(e) => Err((json_rpc::INVALID_PARAMS, e)),
2228        }
2229    }
2230
2231    /// Handle `completion/complete`: look up the registered
2232    /// [`CompletionDef`] matching `params.ref.type`/`params.ref.name`, call
2233    /// its handler with `params.argument.name`/`params.argument.value`, and
2234    /// render the spec's `{"completion":{"values":[...],"hasMore":...,
2235    /// "total":...}}` shape. No registered provider for the given ref/name
2236    /// (or an unrecognized `ref.type` not stripped of `"ref/"`) returns an
2237    /// empty `values` list rather than an error — matching the spec's own
2238    /// framing of completion as a best-effort hint, not a required capability
2239    /// per tool/prompt.
2240    fn do_completion(&self, body: &str) -> Result<String, (i32, String)> {
2241        let params = json_rpc::extract_raw(body, "params")
2242            .ok_or((json_rpc::INVALID_PARAMS, "Missing params".to_string()))?;
2243        let reference = json_rpc::extract_raw(&params, "ref")
2244            .ok_or((json_rpc::INVALID_PARAMS, "Missing ref".to_string()))?;
2245        let ref_type_raw = json_rpc::extract_str(&reference, "type")
2246            .ok_or((json_rpc::INVALID_PARAMS, "Missing ref.type".to_string()))?;
2247        let ref_type = ref_type_raw.strip_prefix("ref/").unwrap_or(&ref_type_raw);
2248        let ref_name = json_rpc::extract_str(&reference, "name")
2249            .ok_or((json_rpc::INVALID_PARAMS, "Missing ref.name".to_string()))?;
2250
2251        let argument = json_rpc::extract_raw(&params, "argument")
2252            .ok_or((json_rpc::INVALID_PARAMS, "Missing argument".to_string()))?;
2253        let arg_name = json_rpc::extract_str(&argument, "name")
2254            .ok_or((json_rpc::INVALID_PARAMS, "Missing argument.name".to_string()))?;
2255        let partial = json_rpc::extract_str(&argument, "value").unwrap_or_default();
2256
2257        let handler = {
2258            let completions = self.completions.read().unwrap();
2259            completions.iter()
2260                .find(|c| c.ref_type == ref_type && c.ref_name == ref_name)
2261                .map(|c| c.handler.clone())
2262        };
2263
2264        let values = match handler {
2265            Some(h) => h(&arg_name, &partial).map_err(|e| (json_rpc::INVALID_PARAMS, e))?,
2266            None => vec![],
2267        };
2268
2269        let total = values.len();
2270        let has_more = total > MAX_COMPLETION_VALUES;
2271        let page = if has_more { &values[..MAX_COMPLETION_VALUES] } else { &values[..] };
2272        let values_json: Vec<String> = page.iter().map(|v| format!(r#""{}""#, json_escape(v))).collect();
2273
2274        Ok(format!(
2275            r#"{{"completion":{{"values":[{}],"hasMore":{has_more},"total":{total}}}}}"#,
2276            values_json.join(","),
2277        ))
2278    }
2279
2280    /// Build the [`McpContext`] for an incoming request: the `Mcp-Session-Id`
2281    /// header, if present, plus whatever `clientInfo` was recorded for that
2282    /// session at `initialize` time (if this session is recognized).
2283    fn context_for(&self, request: &Request) -> McpContext {
2284        let session_id = request
2285            .get_header("Mcp-Session-Id".to_string())
2286            .map(|h| h.value.clone());
2287
2288        let (client_name, client_version, sampling_supported, roots_supported) = match &session_id {
2289            Some(sid) => match self.sessions.lock().unwrap().get(sid) {
2290                Some(info) => (info.name.clone(), info.version.clone(), info.supports_sampling, info.supports_roots),
2291                None => (None, None, false, false),
2292            },
2293            None => (None, None, false, false),
2294        };
2295
2296        McpContext {
2297            client_name,
2298            client_version,
2299            session_id,
2300            auth_claims: None,
2301            progress_token: None,
2302            sse_clients: Some(self.sse_clients.clone()),
2303            cancellation: None,
2304            sampling_supported,
2305            pending_replies: Some(self.pending_replies.clone()),
2306            roots_supported,
2307            sessions: Some(self.sessions.clone()),
2308        }
2309    }
2310}
2311
2312/// Render one JSON-RPC 2.0 notification (no `id` — fire-and-forget, per
2313/// spec) as an SSE `data:`-ready message body. Shared by [`McpServer::notify`]
2314/// and [`McpContext::report_progress`].
2315fn render_notification(method: &str, params_json: Option<&str>) -> String {
2316    let params_field = match params_json {
2317        Some(p) => format!(r#","params":{p}"#),
2318        None => String::new(),
2319    };
2320    format!(r#"{{"jsonrpc":"2.0","method":"{}"{}}}"#, json_escape(method), params_field)
2321}
2322
2323/// Send a raw pre-built JSON-RPC message to every client in `clients`,
2324/// pruning any whose channel is full or disconnected. Shared by
2325/// [`McpServer::notify`] and [`McpContext::report_progress`] — the latter
2326/// only has a clone of the broadcast list, not a whole `McpServer`.
2327fn broadcast_sse_to(clients: &Arc<Mutex<Vec<SseClient>>>, json: &str) {
2328    let frame = format!("data: {json}\n\n").into_bytes();
2329    let mut clients = clients.lock().unwrap();
2330    clients.retain(|c| c.sender.try_send(frame.clone()).is_ok());
2331}
2332
2333/// Send a raw pre-built JSON-RPC message only to clients whose `session_id`
2334/// is in `session_ids`, pruning any of *those* whose channel is full or
2335/// disconnected. A client with no `session_id`, or one not in
2336/// `session_ids`, is left untouched (kept, not sent to) — this is a
2337/// targeted send for [`McpServer::notify_resource_updated`], not a
2338/// broadcast like [`broadcast_sse_to`].
2339fn send_sse_to_sessions(clients: &Arc<Mutex<Vec<SseClient>>>, session_ids: &[String], json: &str) {
2340    let frame = format!("data: {json}\n\n").into_bytes();
2341    let mut clients = clients.lock().unwrap();
2342    clients.retain(|c| {
2343        let is_target = c.session_id.as_deref().is_some_and(|sid| session_ids.iter().any(|s| s == sid));
2344        if is_target {
2345            c.sender.try_send(frame.clone()).is_ok()
2346        } else {
2347            true
2348        }
2349    });
2350}
2351
2352// ── SSE channel reader ────────────────────────────────────────────────────────
2353
2354/// Adapts an `mpsc::Receiver<Vec<u8>>` of pre-framed SSE bytes into a
2355/// blocking [`std::io::Read`], so `Server::pipe_stream` (already written for
2356/// proxy passthrough streaming) can drive a `GET /mcp` SSE connection with no
2357/// changes to the server's write loop.
2358///
2359/// Blocks in [`Self::read`] until either a frame arrives, the sender side is
2360/// dropped (all `McpServer` clones gone — EOF, closing the connection), or
2361/// [`SSE_KEEPALIVE_INTERVAL`] elapses with nothing to send (writes a `:
2362/// keep-alive` comment instead, both to satisfy proxies that time out
2363/// silent connections and to surface a dead peer on the next write attempt).
2364struct SseChannelReader {
2365    rx: mpsc::Receiver<Vec<u8>>,
2366    leftover: Vec<u8>,
2367}
2368
2369impl SseChannelReader {
2370    fn new(rx: mpsc::Receiver<Vec<u8>>) -> Self {
2371        SseChannelReader { rx, leftover: Vec::new() }
2372    }
2373}
2374
2375impl std::io::Read for SseChannelReader {
2376    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2377        if self.leftover.is_empty() {
2378            loop {
2379                match self.rx.recv_timeout(SSE_KEEPALIVE_INTERVAL) {
2380                    Ok(frame) => { self.leftover = frame; break; }
2381                    Err(mpsc::RecvTimeoutError::Timeout) => {
2382                        self.leftover = b": keep-alive\n\n".to_vec();
2383                        break;
2384                    }
2385                    Err(mpsc::RecvTimeoutError::Disconnected) => return Ok(0),
2386                }
2387            }
2388        }
2389
2390        let n = self.leftover.len().min(buf.len());
2391        buf[..n].copy_from_slice(&self.leftover[..n]);
2392        self.leftover.drain(..n);
2393        Ok(n)
2394    }
2395}
2396
2397// ── Application ───────────────────────────────────────────────────────────────
2398
2399impl Application for McpServer {
2400    fn execute(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
2401        if request.request_uri == self.path {
2402            // Check bearer token before processing any MCP request.
2403            if let Some(expected) = &self.auth_token {
2404                let provided = request.headers.iter()
2405                    .find(|h| h.name.eq_ignore_ascii_case("authorization"))
2406                    .map(|h| h.value.as_str())
2407                    .unwrap_or("");
2408                let bearer = provided.strip_prefix("Bearer ").unwrap_or("");
2409                if bearer != expected.as_str() {
2410                    return Ok(unauthorized());
2411                }
2412            }
2413
2414            return Ok(match request.method.as_str() {
2415                "POST" => {
2416                    let body = std::str::from_utf8(&request.body).unwrap_or("");
2417                    let ctx = self.context_for(request);
2418                    self.handle_request_with_context(body, ctx)
2419                }
2420                "GET" => self.start_sse_stream(request),
2421                "OPTIONS" => {
2422                    // CORS preflight for browser-based MCP clients
2423                    let mut r = Response::new();
2424                    r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
2425                    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
2426                    r.headers.push(Header {
2427                        name: "Allow".to_string(),
2428                        value: "GET, POST, OPTIONS".to_string(),
2429                    });
2430                    r
2431                }
2432                _ => {
2433                    let mut r = Response::new();
2434                    r.status_code = *STATUS_CODE_REASON_PHRASE.n405_method_not_allowed.status_code;
2435                    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n405_method_not_allowed.reason_phrase.to_string();
2436                    r.headers.push(Header {
2437                        name: "Allow".to_string(),
2438                        value: "GET, POST, OPTIONS".to_string(),
2439                    });
2440                    r.content_range_list = vec![Range::get_content_range(
2441                        b"MCP endpoint only accepts GET (SSE) or POST".to_vec(),
2442                        MimeType::TEXT_PLAIN.to_string(),
2443                    )];
2444                    r
2445                }
2446            });
2447        }
2448
2449        // Not an MCP path — fall through to the wrapped app (or built-in App).
2450        match &self.fallback {
2451            Some(app) => app.execute(request, connection),
2452            None      => App::new().execute(request, connection),
2453        }
2454    }
2455}
2456
2457// ── public helper ─────────────────────────────────────────────────────────────
2458
2459/// Extract a string argument from a tool/prompt `arguments` JSON object.
2460///
2461/// ```rust
2462/// use rust_web_server::mcp::extract_arg;
2463/// assert_eq!(extract_arg(r#"{"text":"hello"}"#, "text").as_deref(), Some("hello"));
2464/// assert_eq!(extract_arg(r#"{}"#, "missing"), None);
2465/// ```
2466pub fn extract_arg(arguments: &str, name: &str) -> Option<String> {
2467    json_rpc::extract_str(arguments, name)
2468}
2469
2470// ── internal helpers ──────────────────────────────────────────────────────────
2471
2472fn json_response(body: &str) -> Response {
2473    let mut r = Response::new();
2474    r.status_code = *STATUS_CODE_REASON_PHRASE.n200_ok.status_code;
2475    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok.reason_phrase.to_string();
2476    r.content_range_list = vec![Range::get_content_range(
2477        body.as_bytes().to_vec(),
2478        MimeType::APPLICATION_JSON.to_string(),
2479    )];
2480    r
2481}
2482
2483fn no_content() -> Response {
2484    let mut r = Response::new();
2485    r.status_code = *STATUS_CODE_REASON_PHRASE.n202_accepted.status_code;
2486    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n202_accepted.reason_phrase.to_string();
2487    r
2488}
2489
2490fn unauthorized() -> Response {
2491    let mut r = Response::new();
2492    r.status_code = *STATUS_CODE_REASON_PHRASE.n401_unauthorized.status_code;
2493    r.reason_phrase = STATUS_CODE_REASON_PHRASE.n401_unauthorized.reason_phrase.to_string();
2494    r.headers.push(Header {
2495        name: "WWW-Authenticate".to_string(),
2496        value: "Bearer".to_string(),
2497    });
2498    r.content_range_list = vec![Range::get_content_range(
2499        b"Unauthorized".to_vec(),
2500        MimeType::TEXT_PLAIN.to_string(),
2501    )];
2502    r
2503}
2504
2505fn rpc_error(id: Option<&str>, code: i32, message: &str) -> Response {
2506    let id_str  = id.unwrap_or("null");
2507    let escaped = json_escape(message);
2508    json_response(&format!(
2509        r#"{{"jsonrpc":"2.0","error":{{"code":{code},"message":"{escaped}"}},"id":{id_str}}}"#
2510    ))
2511}
2512
2513pub(crate) fn json_escape(s: &str) -> String {
2514    let mut out = String::with_capacity(s.len() + 4);
2515    for ch in s.chars() {
2516        match ch {
2517            '"'  => out.push_str("\\\""),
2518            '\\' => out.push_str("\\\\"),
2519            '\n' => out.push_str("\\n"),
2520            '\r' => out.push_str("\\r"),
2521            '\t' => out.push_str("\\t"),
2522            c if (c as u32) < 0x20 => { let _ = std::fmt::Write::write_fmt(&mut out, format_args!("\\u{:04x}", c as u32)); }
2523            c    => out.push(c),
2524        }
2525    }
2526    out
2527}
2528
2529// ── pagination cursors ─────────────────────────────────────────────────────────
2530
2531/// Render `,"nextCursor":"..."` for a `*/list` response, or `""` if there's
2532/// no next page — spliced directly after the closing `]` of the items array.
2533fn next_cursor_json(next_cursor: &Option<String>) -> String {
2534    match next_cursor {
2535        Some(c) => format!(r#","nextCursor":"{}""#, json_escape(c)),
2536        None => String::new(),
2537    }
2538}
2539
2540/// Encode a `tools/list`/`resources/list`/`prompts/list` offset as the
2541/// opaque `nextCursor`/`params.cursor` string the MCP spec expects — just
2542/// base64 of the decimal offset, e.g. `50` → `"NTA="`. Callers only ever
2543/// treat this as opaque; the encoding is a private implementation detail of
2544/// this module, not a client-facing contract.
2545fn encode_cursor(offset: usize) -> String {
2546    base64_encode(offset.to_string().as_bytes())
2547}
2548
2549/// Decode a cursor produced by [`encode_cursor`]. Returns `None` for
2550/// anything that isn't valid base64 of a decimal `usize` — a malformed or
2551/// tampered cursor, not a crash.
2552fn decode_cursor(cursor: &str) -> Option<usize> {
2553    String::from_utf8(base64_decode(cursor)?).ok()?.parse().ok()
2554}
2555
2556const BASE64_TABLE: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
2557
2558fn base64_encode(data: &[u8]) -> String {
2559    let mut out = String::with_capacity((data.len() + 2) / 3 * 4);
2560    for chunk in data.chunks(3) {
2561        let b0 = chunk[0] as u32;
2562        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
2563        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
2564        let n = (b0 << 16) | (b1 << 8) | b2;
2565        out.push(BASE64_TABLE[((n >> 18) & 0x3F) as usize] as char);
2566        out.push(BASE64_TABLE[((n >> 12) & 0x3F) as usize] as char);
2567        out.push(if chunk.len() > 1 { BASE64_TABLE[((n >> 6) & 0x3F) as usize] as char } else { '=' });
2568        out.push(if chunk.len() > 2 { BASE64_TABLE[(n & 0x3F) as usize] as char } else { '=' });
2569    }
2570    out
2571}
2572
2573fn base64_decode(s: &str) -> Option<Vec<u8>> {
2574    fn sextet(c: u8) -> Option<u32> {
2575        match c {
2576            b'A'..=b'Z' => Some((c - b'A') as u32),
2577            b'a'..=b'z' => Some((c - b'a' + 26) as u32),
2578            b'0'..=b'9' => Some((c - b'0' + 52) as u32),
2579            b'+' => Some(62),
2580            b'/' => Some(63),
2581            _ => None,
2582        }
2583    }
2584
2585    let trimmed = s.trim_end_matches('=');
2586    let bytes = trimmed.as_bytes();
2587    let mut out = Vec::with_capacity(bytes.len() * 3 / 4 + 3);
2588    for chunk in bytes.chunks(4) {
2589        if chunk.len() == 1 {
2590            return None; // not a valid base64 length
2591        }
2592        let vals: Vec<u32> = chunk.iter().map(|&b| sextet(b)).collect::<Option<Vec<_>>>()?;
2593        let n = vals.iter().enumerate().fold(0u32, |acc, (i, &v)| acc | (v << (18 - 6 * i)));
2594        out.push(((n >> 16) & 0xFF) as u8);
2595        if vals.len() > 2 { out.push(((n >> 8) & 0xFF) as u8); }
2596        if vals.len() > 3 { out.push((n & 0xFF) as u8); }
2597    }
2598    Some(out)
2599}
2600
2601fn uri_matches(template: &str, uri: &str) -> bool {
2602    // Template `"user://{id}"` matches any URI starting with `"user://"`.
2603    match template.find('{') {
2604        Some(pos) => uri.starts_with(&template[..pos]),
2605        None      => template == uri,
2606    }
2607}