Skip to main content

rust_web_server/mcp/
gateway.rs

1//! A minimal MCP gateway: one endpoint in front of several upstream MCP
2//! servers.
3//!
4//! [`McpGateway::build`] connects to each [`Upstream`], lists its tools and
5//! registers each one as `<prefix>__<tool>` on an ordinary [`McpServer`];
6//! calling it forwards the call to that upstream. The gateway's caller
7//! authenticates to the gateway (put [`McpServer::require_bearer_tokens`] or
8//! [`McpServer::require_oauth`] on the server `build` returns); upstreams
9//! get only the headers configured for them — the caller's token is never
10//! passed on. [`McpGateway::allow`] decides which caller (the `sub` of
11//! [`McpContext::auth_claims`](super::McpContext::auth_claims)) sees which tools, and nothing is allowed
12//! unless a rule says so.
13//!
14//! Upstream prompts are federated as `<prefix>__<name>` and resources under
15//! their own URIs (the first upstream to publish a URI keeps it), both
16//! listed at `build` and filtered by the same rules as tools (a resource
17//! counts as `<prefix>__<uri>`).
18//!
19//! Tools are listed at `build` and again every [`McpGateway::refresh_every`]
20//! (5 minutes by default): new upstream tools appear, removed ones go, and
21//! the gateway's clients get `notifications/tools/list_changed`. Between
22//! refreshes `tools/list` is answered from the gateway's own copy.
23//!
24//! Each upstream speaks the protocol it supports: the gateway opens a
25//! 2025-11-25 session, and when an upstream refuses `initialize` it talks to
26//! it the 2026-07-28 way instead, statelessly (`server/discover` first, then
27//! every request carrying its version and capabilities in `_meta` and the
28//! `Mcp-Method`/`Mcp-Name` headers). Clients of either era reach upstreams of
29//! either era.
30
31use std::sync::atomic::{AtomicU64, Ordering};
32use std::sync::{Arc, Mutex};
33
34use super::{json_escape, json_rpc, McpContent, McpServer, ToolAnnotations};
35use crate::http_client::Client;
36
37/// The protocol version the gateway asks upstreams for.
38const PROTOCOL_VERSION: &str = "2025-11-25";
39
40/// The stateless protocol, for upstreams that refuse `initialize`.
41const MODERN_VERSION: &str = "2026-07-28";
42
43/// Separates an upstream's prefix from its tool names.
44pub const SEPARATOR: &str = "__";
45
46/// `tools/list` pages followed per upstream before giving up.
47const MAX_LIST_PAGES: usize = 100;
48
49/// An upstream MCP server (Streamable HTTP).
50#[derive(Clone)]
51pub struct Upstream {
52    prefix: String,
53    url: String,
54    headers: Vec<(String, String)>,
55    /// Headers computed per tool call from the caller's claims.
56    caller_headers: Vec<(String, CallerHeader)>,
57    timeout_ms: u64,
58}
59
60/// [`Upstream::header_for`]: the caller's verified claims (JSON, `None`
61/// without an identity) → a header value, or `None` to send none.
62type CallerHeader = Arc<dyn Fn(Option<&str>) -> Option<String> + Send + Sync>;
63
64impl std::fmt::Debug for Upstream {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        // Header values are credentials: names only.
67        f.debug_struct("Upstream")
68            .field("prefix", &self.prefix)
69            .field("url", &self.url)
70            .field("headers", &self.headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
71            .field("caller_headers", &self.caller_headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
72            .field("timeout_ms", &self.timeout_ms)
73            .finish()
74    }
75}
76
77impl Upstream {
78    /// The server at `url` (its MCP endpoint, e.g. `https://mcp.example.com/mcp`),
79    /// whose tools appear as `<prefix>__<tool>`. `prefix` is letters, digits,
80    /// `-` and single `_`s.
81    pub fn new(prefix: impl Into<String>, url: impl Into<String>) -> Self {
82        Upstream { prefix: prefix.into(), url: url.into(), headers: Vec::new(), caller_headers: Vec::new(), timeout_ms: 30_000 }
83    }
84
85    /// Send this header to the upstream on every request — its credentials,
86    /// e.g. `.header("Authorization", "Bearer <upstream token>")`.
87    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
88        self.headers.push((name.into(), value.into()));
89        self
90    }
91
92    /// Send header `name` on each tool call with a value computed from the
93    /// caller's verified claims (the JSON of
94    /// [`McpContext::auth_claims`](super::McpContext::auth_claims), `None`
95    /// for a caller without one) — e.g. each user's own upstream token,
96    /// looked up by `sub`, so the upstream acts as that user. `None` from
97    /// `value` sends no header. Only `tools/call` carries a caller; listing
98    /// and prompts/resources use the static [`Self::header`]s.
99    pub fn header_for<F>(mut self, name: impl Into<String>, value: F) -> Self
100    where
101        F: Fn(Option<&str>) -> Option<String> + Send + Sync + 'static,
102    {
103        self.caller_headers.push((name.into(), Arc::new(value)));
104        self
105    }
106
107    /// Give up on an upstream request after this long (default 30 s).
108    pub fn timeout_ms(mut self, timeout_ms: u64) -> Self {
109        self.timeout_ms = timeout_ms;
110        self
111    }
112}
113
114/// Builds a gateway [`McpServer`]; see the [module docs](self).
115pub struct McpGateway {
116    name: String,
117    version: String,
118    upstreams: Vec<Upstream>,
119    rules: Vec<(String, Vec<String>)>,
120    refresh: Option<std::time::Duration>,
121    limits: Vec<ToolLimit>,
122    audit: bool,
123}
124
125/// [`McpGateway::limit`]: calls of the tools matching `pattern`, per caller.
126struct ToolLimit {
127    pattern: String,
128    max_calls: u32,
129    window_secs: u64,
130    limiter: crate::rate_limit::RateLimiter,
131}
132
133/// How often upstream tool lists are re-read by default.
134pub const DEFAULT_REFRESH: std::time::Duration = std::time::Duration::from_secs(300);
135
136impl McpGateway {
137    /// A gateway announcing itself as `name`/`version`.
138    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
139        McpGateway { name: name.into(), version: version.into(), upstreams: Vec::new(), rules: Vec::new(), refresh: Some(DEFAULT_REFRESH), limits: Vec::new(), audit: false }
140    }
141
142    /// Allow each caller (each `sub`) at most `max_calls` calls per
143    /// `window_secs` of the tools matching `tools` (a full name, a prefix
144    /// ending in `*`, or `*`), counted per tool. Over the limit a call
145    /// answers a tool error saying when to retry. Limits add up: a call
146    /// must pass every one that matches. Counted in this process.
147    pub fn limit(mut self, tools: impl Into<String>, max_calls: u32, window_secs: u64) -> Self {
148        self.limits.push(ToolLimit { pattern: tools.into(), max_calls, window_secs, limiter: crate::rate_limit::RateLimiter::new(max_calls, window_secs) });
149        self
150    }
151
152    /// Write one JSON line per `tools/call` to the access log (stdout, or
153    /// `RWS_CONFIG_ACCESS_LOG`): time, caller (`sub`), tool, upstream,
154    /// outcome (`ok`, `tool_error`, `refused` by a limit, `denied` by the
155    /// ACL) and duration. Arguments and results are not logged.
156    pub fn audit_log(mut self, on: bool) -> Self {
157        self.audit = on;
158        self
159    }
160
161    /// Re-read every upstream's tools this often (default
162    /// [`DEFAULT_REFRESH`]); `None` lists them only at `build`. An upstream
163    /// that can't be reached keeps the tools it had.
164    pub fn refresh_every(mut self, every: Option<std::time::Duration>) -> Self {
165        self.refresh = every;
166        self
167    }
168
169    /// Federate `upstream`'s tools.
170    pub fn upstream(mut self, upstream: Upstream) -> Self {
171        self.upstreams.push(upstream);
172        self
173    }
174
175    /// Let `identity` see and call the tools matching `tools`: a full name
176    /// (`github__search_issues`), a prefix ending in `*` (`github__*`), or
177    /// `*` for all. `identity` is the caller's `sub` claim; `*` means any
178    /// identified caller. Rules add up; a caller no rule names gets no tools.
179    pub fn allow<I, S>(mut self, identity: impl Into<String>, tools: I) -> Self
180    where
181        I: IntoIterator<Item = S>,
182        S: Into<String>,
183    {
184        self.rules.push((identity.into(), tools.into_iter().map(Into::into).collect()));
185        self
186    }
187
188    /// Connect to every upstream, list its tools and return the gateway.
189    /// Fails, naming the upstream, if one can't be reached or answers
190    /// something that isn't MCP. Add authentication to the result.
191    pub fn build(self) -> Result<McpServer, String> {
192        let mut prefixes: Vec<&str> = Vec::new();
193        for upstream in &self.upstreams {
194            if !valid_prefix(&upstream.prefix) {
195                return Err(format!("upstream prefix \"{}\": use letters, digits, '-' and single '_'", upstream.prefix));
196            }
197            if prefixes.contains(&upstream.prefix.as_str()) {
198                return Err(format!("upstream prefix \"{}\" is used twice", upstream.prefix));
199            }
200            prefixes.push(&upstream.prefix);
201        }
202
203        let rules = Arc::new(self.rules);
204        let tool_rules = Arc::clone(&rules);
205        let mut server = McpServer::new(self.name, self.version).tool_filter(move |ctx, tool| {
206            let identity = ctx.auth_claims.as_deref().and_then(|claims| top_level_str(claims, "sub"));
207            identity.is_some_and(|identity| allowed(&tool_rules, &identity, tool))
208        });
209        if self.audit {
210            server = server.after_tool_call(|ctx, call| {
211                let sub = ctx.auth_claims.as_deref().and_then(|claims| top_level_str(claims, "sub")).unwrap_or_default();
212                let upstream = call.tool.split_once(SEPARATOR).map_or("", |(prefix, _)| prefix);
213                let outcome = match call.outcome {
214                    crate::mcp::ToolCallOutcome::Ok => "ok",
215                    crate::mcp::ToolCallOutcome::ToolError => "tool_error",
216                    crate::mcp::ToolCallOutcome::Refused => "refused",
217                    crate::mcp::ToolCallOutcome::Denied => "denied",
218                };
219                let line = audit_line(&sub, call.tool, upstream, outcome, call.duration);
220                crate::log::access_sink::write_line(|out| out.extend_from_slice(line.as_bytes()));
221            });
222        }
223        if !self.limits.is_empty() {
224            let limits = self.limits;
225            server = server.before_tool_call(move |ctx, tool| {
226                let identity = ctx.auth_claims.as_deref().and_then(|claims| top_level_str(claims, "sub")).unwrap_or_default();
227                for limit in limits.iter().filter(|l| matches_pattern(&l.pattern, tool)) {
228                    let key = format!("{identity}\u{0}{tool}");
229                    if !limit.limiter.check(&key) {
230                        return Err(format!("Rate limited: {tool} allows {} calls per {} s; retry in {} s", limit.max_calls, limit.window_secs, limit.limiter.retry_after(&key).max(1)));
231                    }
232                }
233                Ok(())
234            });
235        }
236        // Resources and prompts: listed at build, ACL'd like tools (a
237        // resource as "<prefix>__<uri>"). The first upstream to publish a
238        // URI keeps it.
239        let resource_owner: Arc<Mutex<std::collections::HashMap<String, String>>> = Arc::new(Mutex::new(std::collections::HashMap::new()));
240        {
241            let rules = Arc::clone(&rules);
242            let owners = Arc::clone(&resource_owner);
243            server = server.resource_filter(move |ctx, uri| {
244                let identity = ctx.auth_claims.as_deref().and_then(|claims| top_level_str(claims, "sub"));
245                let owner = owners.lock().ok().and_then(|o| o.get(uri).cloned());
246                match (identity, owner) {
247                    (Some(identity), Some(prefix)) => allowed(&rules, &identity, &format!("{prefix}{SEPARATOR}{uri}")),
248                    (_, None) => true, // not federated: the gateway's own
249                    (None, Some(_)) => false,
250                }
251            });
252        }
253        {
254            let rules = Arc::clone(&rules);
255            server = server.prompt_filter(move |ctx, name| {
256                let identity = ctx.auth_claims.as_deref().and_then(|claims| top_level_str(claims, "sub"));
257                identity.is_some_and(|identity| allowed(&rules, &identity, name))
258            });
259        }
260        let mut federated = Vec::new();
261        for upstream in self.upstreams {
262            let connection = Arc::new(Connection::new(upstream));
263            let mut known = std::collections::HashMap::new();
264            for tool in connection.list_tools()? {
265                known.insert(tool.name.clone(), tool.fingerprint());
266                server = register(server, &connection, tool);
267            }
268            // Best effort: an upstream's tools matter most, so a broken
269            // prompts or resources list is logged, not fatal.
270            let listed = |method: &str, field: &str| {
271                connection.list_all(method, field).unwrap_or_else(|e| {
272                    eprintln!("mcp gateway: not federating {field}: {e}");
273                    Vec::new()
274                })
275            };
276            for prompt in listed("prompts/list", "prompts") {
277                server = register_prompt(server, &connection, &prompt);
278            }
279            for (method, field, key) in [("resources/list", "resources", "uri"), ("resources/templates/list", "resourceTemplates", "uriTemplate")] {
280                for resource in listed(method, field) {
281                    let Some(uri) = top_level_str(&resource, key) else { continue };
282                    {
283                        let mut owners = resource_owner.lock().map_err(|_| "resource lock poisoned".to_string())?;
284                        if owners.contains_key(&uri) {
285                            eprintln!("mcp gateway: {} also publishes {uri}; keeping the first", connection.name());
286                            continue;
287                        }
288                        owners.insert(uri.clone(), connection.upstream.prefix.clone());
289                    }
290                    server = register_resource(server, &connection, &uri, &resource);
291                }
292            }
293            federated.push((connection, known));
294        }
295        if let Some(every) = self.refresh {
296            let live = server.clone();
297            let spawned = std::thread::Builder::new().name("rws-mcp-gateway-refresh".to_string()).spawn(move || loop {
298                std::thread::sleep(every);
299                for (connection, known) in federated.iter_mut() {
300                    refresh(&live, connection, known);
301                }
302            });
303            if let Err(e) = spawned {
304                eprintln!("mcp gateway: tool list refresh not started: {e}");
305            }
306        }
307        Ok(server)
308    }
309}
310
311/// Re-list `connection`'s tools and apply the difference to `server`:
312/// register new or changed tools, remove gone ones, then tell clients.
313fn refresh(server: &McpServer, connection: &Arc<Connection>, known: &mut std::collections::HashMap<String, String>) {
314    let tools = match connection.list_tools() {
315        Ok(tools) => tools,
316        Err(e) => {
317            eprintln!("mcp gateway: keeping {}'s tools: {e}", connection.name());
318            return;
319        }
320    };
321    let prefix = &connection.upstream.prefix;
322    let mut changed = false;
323    let mut seen = std::collections::HashSet::new();
324    for tool in tools {
325        seen.insert(tool.name.clone());
326        let fingerprint = tool.fingerprint();
327        if known.get(&tool.name) == Some(&fingerprint) {
328            continue;
329        }
330        let exposed = format!("{prefix}{SEPARATOR}{}", tool.name);
331        if known.contains_key(&tool.name) {
332            server.remove_tool(&exposed);
333        }
334        known.insert(tool.name.clone(), fingerprint);
335        let _ = register(server.clone(), connection, tool);
336        changed = true;
337    }
338    let gone: Vec<String> = known.keys().filter(|name| !seen.contains(*name)).cloned().collect();
339    for name in gone {
340        known.remove(&name);
341        server.remove_tool(&format!("{prefix}{SEPARATOR}{name}"));
342        changed = true;
343    }
344    if changed {
345        server.notify("notifications/tools/list_changed", None);
346    }
347}
348
349/// One upstream tool, as `tools/list` described it.
350#[derive(Clone)]
351struct UpstreamTool {
352    name: String,
353    description: String,
354    title: Option<String>,
355    input_schema: String,
356    output_schema: Option<String>,
357    annotations: Option<ToolAnnotations>,
358}
359
360impl UpstreamTool {
361    /// Changes when anything the gateway republishes changes.
362    fn fingerprint(&self) -> String {
363        format!("{}\u{0}{}\u{0}{:?}\u{0}{}\u{0}{:?}\u{0}{:?}", self.name, self.description, self.title, self.input_schema, self.output_schema, self.annotations)
364    }
365}
366
367fn register(server: McpServer, connection: &Arc<Connection>, tool: UpstreamTool) -> McpServer {
368    let exposed = format!("{}{SEPARATOR}{}", connection.upstream.prefix, tool.name);
369    let forward = Arc::clone(connection);
370    let upstream_name = tool.name.clone();
371    let mut server = server.tool_with_context(&exposed, &tool.description, &tool.input_schema, move |ctx, args| {
372        forward.call_tool(&upstream_name, args, ctx.auth_claims.as_deref()).map(McpContent::raw_result)
373    });
374    if let Some(title) = tool.title {
375        server = server.tool_title(&exposed, title);
376    }
377    if let Some(schema) = tool.output_schema {
378        server = server.tool_output_schema(&exposed, &schema);
379    }
380    if let Some(annotations) = tool.annotations {
381        server = server.tool_annotations(&exposed, annotations);
382    }
383    server
384}
385
386fn register_prompt(server: McpServer, connection: &Arc<Connection>, prompt: &str) -> McpServer {
387    let Some(name) = top_level_str(prompt, "name") else { return server };
388    let exposed = format!("{}{SEPARATOR}{name}", connection.upstream.prefix);
389    let description = top_level_str(prompt, "description").unwrap_or_default();
390    let args = top_level_raw(prompt, "arguments")
391        .map(|list| {
392            json_rpc::split_array_elements(&list)
393                .into_iter()
394                .filter_map(|arg| {
395                    let name = top_level_str(&arg, "name")?;
396                    let description = top_level_str(&arg, "description").unwrap_or_default();
397                    let required = top_level_raw(&arg, "required").as_deref() == Some("true");
398                    Some(if required { super::PromptArgDef::required(name, description) } else { super::PromptArgDef::optional(name, description) })
399                })
400                .collect()
401        })
402        .unwrap_or_default();
403    let forward = Arc::clone(connection);
404    server.prompt_with_args(&exposed, &description, args, move |arguments| {
405        let params = format!(r#"{{"name":"{}","arguments":{}}}"#, json_escape(&name), if arguments.trim().is_empty() { "{}" } else { arguments });
406        let result = forward.request("prompts/get", &params).map_err(|e| format!("{}: {e}", forward.upstream.prefix))?;
407        let messages = top_level_raw(&result, "messages").ok_or_else(|| format!("{}: prompts/get without messages", forward.upstream.prefix))?;
408        Ok(json_rpc::split_array_elements(&messages)
409            .into_iter()
410            .filter_map(|message| {
411                let role = if top_level_str(&message, "role").as_deref() == Some("assistant") { "assistant" } else { "user" };
412                let content = top_level_raw(&message, "content").filter(|c| c.starts_with('{'))?;
413                Some(super::PromptMessage { role, content: McpContent::raw_block(content) })
414            })
415            .collect())
416    })
417}
418
419fn register_resource(server: McpServer, connection: &Arc<Connection>, uri: &str, resource: &str) -> McpServer {
420    let name = top_level_str(resource, "name").unwrap_or_else(|| uri.to_string());
421    let description = top_level_str(resource, "description").unwrap_or_default();
422    let forward = Arc::clone(connection);
423    server.resource(uri, &name, &description, move |requested| {
424        let params = format!(r#"{{"uri":"{}"}}"#, json_escape(requested));
425        forward.request("resources/read", &params).map(McpContent::raw_result).map_err(|e| format!("{}: {e}", forward.upstream.prefix))
426    })
427}
428
429fn valid_prefix(prefix: &str) -> bool {
430    !prefix.is_empty()
431        && !prefix.contains(SEPARATOR)
432        && !prefix.ends_with('_')
433        && prefix.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
434}
435
436/// Does a rule for `identity` (or `*`) match `tool`?
437fn allowed(rules: &[(String, Vec<String>)], identity: &str, tool: &str) -> bool {
438    rules
439        .iter()
440        .filter(|(who, _)| who == identity || who == "*")
441        .flat_map(|(_, patterns)| patterns)
442        .any(|pattern| matches_pattern(pattern, tool))
443}
444
445/// One audit log line (without the newline).
446fn audit_line(sub: &str, tool: &str, upstream: &str, outcome: &str, duration: std::time::Duration) -> String {
447    let mut time = String::new();
448    crate::log::iso8601_now(|iso| time.push_str(iso));
449    format!(
450        r#"{{"time":"{time}","event":"mcp_tool_call","sub":"{}","tool":"{}","upstream":"{}","outcome":"{outcome}","duration_ms":{:.3}}}"#,
451        json_escape(sub),
452        json_escape(tool),
453        json_escape(upstream),
454        duration.as_secs_f64() * 1000.0
455    )
456}
457
458/// A full tool name, a prefix ending in `*`, or `*`.
459fn matches_pattern(pattern: &str, tool: &str) -> bool {
460    match pattern.strip_suffix('*') {
461        Some(prefix) => tool.starts_with(prefix),
462        None => pattern == tool,
463    }
464}
465
466/// The string member `key` of the top level of JSON object `json`.
467fn top_level_str(json: &str, key: &str) -> Option<String> {
468    let raw = top_level_raw(json, key)?;
469    raw.starts_with('"').then(|| json_rpc::extract_str(&format!(r#"{{"v":{raw}}}"#), "v")).flatten()
470}
471
472/// The raw JSON of member `key` of the top level of JSON object `json`.
473fn top_level_raw(json: &str, key: &str) -> Option<String> {
474    json_rpc::object_members(json)?.into_iter().find(|(k, _)| k == key).map(|(_, v)| v)
475}
476
477/// The gateway's session with one upstream.
478struct Connection {
479    upstream: Upstream,
480    client: Client,
481    /// `(Mcp-Session-Id, negotiated protocol version)`, once initialized.
482    session: Mutex<Option<Session>>,
483    next_id: AtomicU64,
484}
485
486#[derive(Clone)]
487struct Session {
488    id: Option<String>,
489    version: String,
490    /// 2026-07-28: no session; `_meta` and headers on every request.
491    modern: bool,
492}
493
494impl Connection {
495    fn new(upstream: Upstream) -> Self {
496        let client = Client::new().timeout_ms(upstream.timeout_ms).max_redirects(0);
497        Connection { upstream, client, session: Mutex::new(None), next_id: AtomicU64::new(1) }
498    }
499
500    fn name(&self) -> String {
501        format!("upstream {} ({})", self.upstream.prefix, self.upstream.url)
502    }
503
504    /// Every tool, following `nextCursor`.
505    fn list_tools(&self) -> Result<Vec<UpstreamTool>, String> {
506        let mut tools = Vec::new();
507        let mut cursor: Option<String> = None;
508        for _ in 0..MAX_LIST_PAGES {
509            let params = match &cursor {
510                Some(cursor) => format!(r#"{{"cursor":"{}"}}"#, json_escape(cursor)),
511                None => "{}".to_string(),
512            };
513            let result = self.request("tools/list", &params).map_err(|e| format!("{}: {e}", self.name()))?;
514            let list = top_level_raw(&result, "tools").ok_or_else(|| format!("{}: tools/list without tools", self.name()))?;
515            for tool in json_rpc::split_array_elements(&list) {
516                tools.push(parse_tool(&tool).ok_or_else(|| format!("{}: malformed tool {tool}", self.name()))?);
517            }
518            cursor = top_level_str(&result, "nextCursor");
519            if cursor.is_none() {
520                return Ok(tools);
521            }
522        }
523        Err(format!("{}: more than {MAX_LIST_PAGES} pages of tools", self.name()))
524    }
525
526    /// Every item of a paginated list method (`prompts/list`, ...), as raw
527    /// JSON objects; `Ok(empty)` when the upstream doesn't have the method.
528    fn list_all(&self, method: &str, field: &str) -> Result<Vec<String>, String> {
529        let mut items = Vec::new();
530        let mut cursor: Option<String> = None;
531        for _ in 0..MAX_LIST_PAGES {
532            let params = match &cursor {
533                Some(cursor) => format!(r#"{{"cursor":"{}"}}"#, json_escape(cursor)),
534                None => "{}".to_string(),
535            };
536            let result = match self.request(method, &params) {
537                Ok(result) => result,
538                // No such capability: nothing to federate.
539                Err(e) if e.contains("not found") || e.contains("Unknown method") || e.contains("-32601") || e.contains("answered HTTP 404") => return Ok(items),
540                Err(e) => return Err(format!("{}: {method}: {e}", self.name())),
541            };
542            let Some(list) = top_level_raw(&result, field) else { return Ok(items) };
543            items.extend(json_rpc::split_array_elements(&list));
544            cursor = top_level_str(&result, "nextCursor");
545            if cursor.is_none() {
546                return Ok(items);
547            }
548        }
549        Err(format!("{}: more than {MAX_LIST_PAGES} pages of {field}", self.name()))
550    }
551
552    /// Calls `name` upstream: the raw `tools/call` result, or why it failed.
553    fn call_tool(&self, name: &str, arguments: &str, claims: Option<&str>) -> Result<String, String> {
554        let params = format!(r#"{{"name":"{}","arguments":{arguments}}}"#, json_escape(name));
555        let caller: Vec<(String, String)> = self
556            .upstream
557            .caller_headers
558            .iter()
559            .filter_map(|(header, value)| value(claims).map(|v| (header.clone(), v)))
560            .collect();
561        let result = self.request_as("tools/call", &params, &caller).map_err(|e| format!("{}: {e}", self.upstream.prefix))?;
562        if top_level_str(&result, "resultType").as_deref() == Some("input_required") {
563            return Err(format!("{}: the tool asked for more input (2026-07-28 multi round-trip), which the gateway doesn't relay", self.upstream.prefix));
564        }
565        Ok(without_modern_fields(&result))
566    }
567
568    /// Sends one request in the current session (initializing first if
569    /// needed, and once more if the upstream has forgotten the session).
570    fn request(&self, method: &str, params: &str) -> Result<String, String> {
571        self.request_as(method, params, &[])
572    }
573
574    /// [`Self::request`] with headers for this one call (the caller's).
575    fn request_as(&self, method: &str, params: &str, caller: &[(String, String)]) -> Result<String, String> {
576        let session = self.session()?;
577        match self.send(&session, method, params, caller)? {
578            Reply::Result(result) => Ok(result),
579            Reply::SessionGone => {
580                self.forget(&session);
581                let session = self.session()?;
582                match self.send(&session, method, params, caller)? {
583                    Reply::Result(result) => Ok(result),
584                    Reply::SessionGone => Err("session not found twice in a row".to_string()),
585                }
586            }
587        }
588    }
589
590    fn session(&self) -> Result<Session, String> {
591        let mut guard = self.session.lock().map_err(|_| "session lock poisoned".to_string())?;
592        if let Some(session) = guard.as_ref() {
593            return Ok(session.clone());
594        }
595        let session = self.initialize()?;
596        *guard = Some(session.clone());
597        Ok(session)
598    }
599
600    fn forget(&self, stale: &Session) {
601        if let Ok(mut guard) = self.session.lock() {
602            if guard.as_ref().is_some_and(|current| current.id == stale.id) {
603                *guard = None;
604            }
605        }
606    }
607
608    /// A 2025-11-25 session, or, when the upstream refuses that, the
609    /// stateless 2026-07-28 protocol after a `server/discover`.
610    fn initialize(&self) -> Result<Session, String> {
611        match self.initialize_legacy() {
612            Ok(session) => Ok(session),
613            Err(legacy) => self.discover().map_err(|modern| format!("{legacy}; as {MODERN_VERSION}: {modern}")),
614        }
615    }
616
617    fn discover(&self) -> Result<Session, String> {
618        let session = Session { id: None, version: MODERN_VERSION.to_string(), modern: true };
619        match self.send(&session, "server/discover", "{}", &[])? {
620            Reply::Result(result) if result.contains(MODERN_VERSION) => Ok(session),
621            Reply::Result(_) => Err(format!("server/discover doesn't list {MODERN_VERSION}")),
622            Reply::SessionGone => Err("server/discover answered 404".to_string()),
623        }
624    }
625
626    fn initialize_legacy(&self) -> Result<Session, String> {
627        let params = format!(
628            r#"{{"protocolVersion":"{PROTOCOL_VERSION}","capabilities":{{}},"clientInfo":{{"name":"rws-mcp-gateway","version":"{}"}}}}"#,
629            env!("CARGO_PKG_VERSION"),
630        );
631        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
632        let response = self.post(None, PROTOCOL_VERSION, &[], &envelope(id, "initialize", &params))?;
633        if !(200..300).contains(&response.status()) {
634            return Err(format!("initialize answered HTTP {}", response.status()));
635        }
636        let session_id = response.header("mcp-session-id").map(str::to_string);
637        let result = parse_reply(response.header("content-type").unwrap_or(""), response.bytes(), id)?;
638        let version = top_level_str(&result, "protocolVersion").unwrap_or_else(|| PROTOCOL_VERSION.to_string());
639        let session = Session { id: session_id, version, modern: false };
640        let initialized = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
641        self.post(session.id.as_deref(), &session.version, &[], initialized)?;
642        Ok(session)
643    }
644
645    fn send(&self, session: &Session, method: &str, params: &str, caller: &[(String, String)]) -> Result<Reply, String> {
646        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
647        let response = if session.modern {
648            let mut headers: Vec<(&str, String)> = vec![("Mcp-Method", method.to_string())];
649            let named = match method {
650                "tools/call" | "prompts/get" => top_level_str(params, "name"),
651                "resources/read" => top_level_str(params, "uri"),
652                _ => None,
653            };
654            if let Some(name) = named {
655                headers.push(("Mcp-Name", name));
656            }
657            headers.extend(caller.iter().map(|(k, v)| (k.as_str(), v.clone())));
658            self.post(None, &session.version, &headers, &envelope(id, method, &with_modern_meta(params)))?
659        } else {
660            let headers: Vec<(&str, String)> = caller.iter().map(|(k, v)| (k.as_str(), v.clone())).collect();
661            self.post(session.id.as_deref(), &session.version, &headers, &envelope(id, method, params))?
662        };
663        if response.status() == 404 && session.id.is_some() {
664            return Ok(Reply::SessionGone);
665        }
666        if !(200..300).contains(&response.status()) {
667            return Err(format!("answered HTTP {}", response.status()));
668        }
669        parse_reply(response.header("content-type").unwrap_or(""), response.bytes(), id).map(Reply::Result)
670    }
671
672    /// One POST to the upstream, with its own headers only.
673    fn post(&self, session_id: Option<&str>, version: &str, extra: &[(&str, String)], body: &str) -> Result<crate::http_client::Response, String> {
674        let mut request = self
675            .client
676            .post(&self.upstream.url)
677            .header("Content-Type", "application/json")
678            .header("Accept", "application/json, text/event-stream")
679            .header("MCP-Protocol-Version", version);
680        if let Some(id) = session_id {
681            request = request.header("Mcp-Session-Id", id);
682        }
683        for (name, value) in extra {
684            request = request.header(*name, value);
685        }
686        for (name, value) in &self.upstream.headers {
687            request = request.header(name, value);
688        }
689        request.body(body.as_bytes().to_vec()).send().map_err(|e| format!("unreachable: {e}"))
690    }
691}
692
693enum Reply {
694    Result(String),
695    SessionGone,
696}
697
698/// A 2026-07-28 result without the fields the gateway's own server adds for
699/// its client (`resultType`, cache hints): passed through, they would
700/// appear twice, or reach a 2025 client that doesn't know them.
701fn without_modern_fields(result: &str) -> String {
702    let Some(members) = json_rpc::object_members(result) else { return result.to_string() };
703    if !members.iter().any(|(k, _)| matches!(k.as_str(), "resultType" | "ttlMs" | "cacheScope")) {
704        return result.to_string();
705    }
706    let kept: Vec<String> = members
707        .into_iter()
708        .filter(|(k, _)| !matches!(k.as_str(), "resultType" | "ttlMs" | "cacheScope"))
709        .map(|(k, v)| format!(r#""{}":{v}"#, json_escape(&k)))
710        .collect();
711    format!("{{{}}}", kept.join(","))
712}
713
714/// `params` with the 2026-07-28 `_meta` (version, client info, no client
715/// capabilities: the gateway answers no server-to-client requests).
716fn with_modern_meta(params: &str) -> String {
717    let meta = format!(
718        r#""_meta":{{"io.modelcontextprotocol/protocolVersion":"{MODERN_VERSION}","io.modelcontextprotocol/clientInfo":{{"name":"rws-mcp-gateway","version":"{}"}},"io.modelcontextprotocol/clientCapabilities":{{}}}}"#,
719        env!("CARGO_PKG_VERSION"),
720    );
721    let inner = params.trim().strip_prefix('{').and_then(|p| p.strip_suffix('}')).unwrap_or("").trim();
722    // After the request's own members: some JSON readers take the first
723    // `name` at any depth, which would be clientInfo's.
724    if inner.is_empty() { format!("{{{meta}}}") } else { format!("{{{inner},{meta}}}") }
725}
726
727fn envelope(id: u64, method: &str, params: &str) -> String {
728    format!(r#"{{"jsonrpc":"2.0","id":{id},"method":"{method}","params":{params}}}"#)
729}
730
731fn parse_tool(json: &str) -> Option<UpstreamTool> {
732    let members = json_rpc::object_members(json)?;
733    let raw = |key: &str| members.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
734    let string = |key: &str| top_level_str(json, key);
735    let name = string("name")?;
736    let input_schema = raw("inputSchema").filter(|schema| schema.starts_with('{'))?;
737    let annotations = raw("annotations").filter(|a| a.starts_with('{')).map(|a| {
738        let hint = |key: &str| top_level_raw(&a, key).and_then(|v| v.parse::<bool>().ok());
739        ToolAnnotations {
740            read_only_hint: hint("readOnlyHint"),
741            destructive_hint: hint("destructiveHint"),
742            idempotent_hint: hint("idempotentHint"),
743            open_world_hint: hint("openWorldHint"),
744        }
745    });
746    Some(UpstreamTool {
747        name,
748        description: string("description").unwrap_or_default(),
749        title: string("title"),
750        input_schema,
751        output_schema: raw("outputSchema").filter(|schema| schema.starts_with('{')),
752        annotations,
753    })
754}
755
756/// The `result` of the JSON-RPC response with `id` in an upstream reply —
757/// a JSON body, or an SSE stream whose events may include notifications and
758/// requests before the response. A JSON-RPC `error` becomes its message.
759#[doc(hidden)]
760pub fn parse_reply(content_type: &str, body: &[u8], id: u64) -> Result<String, String> {
761    let body = std::str::from_utf8(body).map_err(|_| "reply is not UTF-8".to_string())?;
762    let media_type = content_type.split(';').next().unwrap_or("").trim();
763    let id = id.to_string();
764    if media_type.eq_ignore_ascii_case("text/event-stream") {
765        let mut data = String::new();
766        for line in body.lines().chain(std::iter::once("")) {
767            if let Some(value) = line.strip_prefix("data:") {
768                if !data.is_empty() {
769                    data.push('\n');
770                }
771                data.push_str(value.strip_prefix(' ').unwrap_or(value));
772            } else if line.is_empty() && !data.is_empty() {
773                let event = std::mem::take(&mut data);
774                if top_level_raw(&event, "id").as_deref() == Some(id.as_str()) && top_level_raw(&event, "method").is_none() {
775                    return response_result(&event);
776                }
777            }
778        }
779        Err("the event stream ended without a response".to_string())
780    } else {
781        if top_level_raw(body, "id").as_deref() != Some(id.as_str()) {
782            return Err("reply is not the response to this request".to_string());
783        }
784        response_result(body)
785    }
786}
787
788fn response_result(response: &str) -> Result<String, String> {
789    if let Some(result) = top_level_raw(response, "result") {
790        return Ok(result);
791    }
792    let error = top_level_raw(response, "error").ok_or_else(|| "response has neither result nor error".to_string())?;
793    Err(top_level_str(&error, "message").unwrap_or(error))
794}
795
796/// Entry points for `fuzz_api`.
797#[doc(hidden)]
798pub mod fuzzing {
799    /// The tools a `tools/list` result describes.
800    pub fn tools(result: &str) -> usize {
801        let Some(list) = super::top_level_raw(result, "tools") else { return 0 };
802        super::json_rpc::split_array_elements(&list).iter().filter_map(|tool| super::parse_tool(tool)).count()
803    }
804}
805
806#[cfg(test)]
807mod tests;