Skip to main content

stateknot_integrations/
mcp_client.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! General MCP 2026-07-28 stateless Tool client.
5//!
6//! This surface is deliberately separate from the durable, exact-schema
7//! [`crate::McpRemoteTool`] binding. It implements broad protocol
8//! interoperability without weakening the runtime's stronger admission and
9//! reconciliation contract.
10
11use std::{
12    collections::HashSet,
13    fmt,
14    sync::{
15        Arc,
16        atomic::{AtomicU64, Ordering},
17    },
18    time::Duration,
19};
20
21use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
22use futures_util::StreamExt;
23use http::{HeaderName, HeaderValue};
24use reqwest::{StatusCode, header};
25use serde_json::{Map, Value, json};
26use stateknot_core::BoxFuture;
27use thiserror::Error;
28
29use crate::{
30    McpAuthorization, McpAuthorizationError, ProviderEndpoint, ProviderEndpointError,
31    ProviderHttpOptions,
32    http::build_client,
33    sse::{SseDecodeError, SseDecoder},
34};
35
36/// The modern, stateless MCP revision implemented by this client.
37pub const MCP_PROTOCOL_VERSION_2026_07_28: &str = "2026-07-28";
38
39const MCP_JSON: &str = "application/json";
40const MCP_EVENT_STREAM: &str = "text/event-stream";
41const MCP_ACCEPT: &str = "application/json, text/event-stream";
42const MCP_HEADER_PROTOCOL_VERSION: &str = "mcp-protocol-version";
43const MCP_HEADER_METHOD: &str = "mcp-method";
44const MCP_HEADER_NAME: &str = "mcp-name";
45const MCP_HEADER_PARAMETER_PREFIX: &str = "mcp-param-";
46const MCP_META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
47const MCP_META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
48const MCP_META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
49const MCP_META_SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";
50const BASE64_PREFIX: &str = "=?base64?";
51const BASE64_SUFFIX: &str = "?=";
52const MAX_IDENTITY_COMPONENT_BYTES: usize = 256;
53const MAX_PROTOCOL_VERSIONS: usize = 64;
54const MAX_PROTOCOL_VERSION_BYTES: usize = 128;
55const MAX_TOOL_NAME_BYTES: usize = 1024;
56const MAX_CURSOR_BYTES: usize = 4096;
57const MAX_REMOTE_ERROR_MESSAGE_BYTES: usize = 4096;
58const MAX_WWW_AUTHENTICATE_VALUES: usize = 16;
59const MAX_WWW_AUTHENTICATE_VALUE_BYTES: usize = 16 * 1024;
60const MAX_WWW_AUTHENTICATE_TOTAL_BYTES: usize = 64 * 1024;
61const MEBIBYTE: usize = 1024 * 1024;
62const MCP_SKILL_WIRE_RESPONSE_BYTES: usize = 104 * MEBIBYTE;
63
64static NEXT_CLIENT_BINDING_ID: AtomicU64 = AtomicU64::new(1);
65
66/// Validated identity sent in every stateless MCP request.
67#[derive(Clone, Eq, PartialEq)]
68pub struct McpClientIdentity {
69    name: Box<str>,
70    version: Box<str>,
71}
72
73impl McpClientIdentity {
74    /// Constructs a bounded printable client identity.
75    pub fn new(
76        name: impl Into<String>,
77        version: impl Into<String>,
78    ) -> Result<Self, McpClientIdentityError> {
79        let name = name.into();
80        let version = version.into();
81        validate_identity_component(&name)?;
82        validate_identity_component(&version)?;
83        Ok(Self {
84            name: name.into_boxed_str(),
85            version: version.into_boxed_str(),
86        })
87    }
88
89    /// Returns the implementation name.
90    #[must_use]
91    pub fn name(&self) -> &str {
92        &self.name
93    }
94
95    /// Returns the implementation version.
96    #[must_use]
97    pub fn version(&self) -> &str {
98        &self.version
99    }
100}
101
102impl fmt::Debug for McpClientIdentity {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        formatter
105            .debug_struct("McpClientIdentity")
106            .field("name", &self.name)
107            .field("version", &self.version)
108            .finish()
109    }
110}
111
112/// Invalid MCP client identity.
113#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
114#[non_exhaustive]
115pub enum McpClientIdentityError {
116    /// A required component was empty.
117    #[error("MCP client identity component is empty")]
118    Empty,
119    /// A component exceeded its hard byte ceiling.
120    #[error("MCP client identity component is too long")]
121    TooLong,
122    /// Trimming would change a component.
123    #[error("MCP client identity component has boundary whitespace")]
124    BoundaryWhitespace,
125    /// A component contained a control character.
126    #[error("MCP client identity component contains a control character")]
127    ControlCharacter,
128}
129
130fn validate_identity_component(value: &str) -> Result<(), McpClientIdentityError> {
131    if value.is_empty() {
132        return Err(McpClientIdentityError::Empty);
133    }
134    if value.len() > MAX_IDENTITY_COMPONENT_BYTES {
135        return Err(McpClientIdentityError::TooLong);
136    }
137    if value.trim() != value {
138        return Err(McpClientIdentityError::BoundaryWhitespace);
139    }
140    if value.chars().any(char::is_control) {
141        return Err(McpClientIdentityError::ControlCharacter);
142    }
143    Ok(())
144}
145
146/// Bounded resource policy for a general stateless MCP client.
147#[derive(Clone, Copy, Debug, Eq, PartialEq)]
148pub struct McpClientOptions {
149    transport: ProviderHttpOptions,
150    request_timeout: Duration,
151    skills_enabled: bool,
152    maximum_authorization_retries: usize,
153    maximum_concurrent_requests: usize,
154    maximum_catalog_pages: usize,
155    maximum_catalog_tools: usize,
156    maximum_notifications_per_response: usize,
157}
158
159impl McpClientOptions {
160    /// Hard deadline ceiling for one outbound MCP HTTP attempt.
161    pub const HARD_MAXIMUM_REQUEST_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
162    /// Hard concurrent request ceiling.
163    pub const HARD_MAXIMUM_CONCURRENT_REQUESTS: usize = 1024;
164    /// Hard authorization retry ceiling for one logical MCP request.
165    pub const HARD_MAXIMUM_AUTHORIZATION_RETRIES: usize = 3;
166    /// Hard tool-catalog page ceiling.
167    pub const HARD_MAXIMUM_CATALOG_PAGES: usize = 64;
168    /// Hard tool-catalog entry ceiling.
169    pub const HARD_MAXIMUM_CATALOG_TOOLS: usize = 4096;
170    /// Hard request-scoped notification ceiling.
171    pub const HARD_MAXIMUM_NOTIFICATIONS_PER_RESPONSE: usize = 4096;
172
173    /// Constructs an explicit bounded client policy.
174    #[allow(clippy::too_many_arguments)]
175    pub const fn new(
176        transport: ProviderHttpOptions,
177        request_timeout: Duration,
178        maximum_concurrent_requests: usize,
179        maximum_catalog_pages: usize,
180        maximum_catalog_tools: usize,
181        maximum_notifications_per_response: usize,
182    ) -> Result<Self, McpClientOptionsError> {
183        if request_timeout.is_zero() {
184            return Err(McpClientOptionsError::ZeroTimeout);
185        }
186        if request_timeout.as_nanos() > Self::HARD_MAXIMUM_REQUEST_TIMEOUT.as_nanos() {
187            return Err(McpClientOptionsError::AboveHardMaximum);
188        }
189        if maximum_concurrent_requests == 0
190            || maximum_catalog_pages == 0
191            || maximum_catalog_tools == 0
192            || maximum_notifications_per_response == 0
193        {
194            return Err(McpClientOptionsError::ZeroLimit);
195        }
196        if maximum_concurrent_requests > Self::HARD_MAXIMUM_CONCURRENT_REQUESTS
197            || maximum_catalog_pages > Self::HARD_MAXIMUM_CATALOG_PAGES
198            || maximum_catalog_tools > Self::HARD_MAXIMUM_CATALOG_TOOLS
199            || maximum_notifications_per_response > Self::HARD_MAXIMUM_NOTIFICATIONS_PER_RESPONSE
200        {
201            return Err(McpClientOptionsError::AboveHardMaximum);
202        }
203        Ok(Self {
204            transport,
205            request_timeout,
206            skills_enabled: false,
207            maximum_authorization_retries: 1,
208            maximum_concurrent_requests,
209            maximum_catalog_pages,
210            maximum_catalog_tools,
211            maximum_notifications_per_response,
212        })
213    }
214
215    /// Returns the underlying bounded HTTP policy.
216    #[must_use]
217    pub const fn transport(self) -> ProviderHttpOptions {
218        self.transport
219    }
220
221    /// Returns the deadline for one outbound MCP HTTP attempt. Interactive
222    /// OAuth handoff uses its own independently bounded policy.
223    #[must_use]
224    pub const fn request_timeout(self) -> Duration {
225        self.request_timeout
226    }
227
228    /// Returns whether this client explicitly opted into the MCP Skills
229    /// extension and its larger bounded transport profile.
230    #[must_use]
231    pub const fn skills_enabled(self) -> bool {
232        self.skills_enabled
233    }
234
235    /// Returns the maximum OAuth challenge recoveries for one logical request.
236    #[must_use]
237    pub const fn maximum_authorization_retries(self) -> usize {
238        self.maximum_authorization_retries
239    }
240
241    /// Sets the bounded OAuth challenge recovery count.
242    ///
243    /// Zero disables automatic recovery. Values above the hard ceiling are
244    /// rejected so a malicious resource server cannot create an unbounded
245    /// authorization loop.
246    pub const fn with_maximum_authorization_retries(
247        mut self,
248        maximum: usize,
249    ) -> Result<Self, McpClientOptionsError> {
250        if maximum > Self::HARD_MAXIMUM_AUTHORIZATION_RETRIES {
251            return Err(McpClientOptionsError::AboveHardMaximum);
252        }
253        self.maximum_authorization_retries = maximum;
254        Ok(self)
255    }
256
257    /// Returns the maximum in-flight requests for this client.
258    #[must_use]
259    pub const fn maximum_concurrent_requests(self) -> usize {
260        self.maximum_concurrent_requests
261    }
262
263    /// Returns the catalog page ceiling.
264    #[must_use]
265    pub const fn maximum_catalog_pages(self) -> usize {
266        self.maximum_catalog_pages
267    }
268
269    /// Returns the catalog entry ceiling.
270    #[must_use]
271    pub const fn maximum_catalog_tools(self) -> usize {
272        self.maximum_catalog_tools
273    }
274
275    /// Returns the shared bounded catalog-entry ceiling used by Skills.
276    #[must_use]
277    pub const fn maximum_skill_catalog_entries(self) -> usize {
278        self.maximum_catalog_tools
279    }
280
281    /// Returns the request-scoped notification ceiling.
282    #[must_use]
283    pub const fn maximum_notifications_per_response(self) -> usize {
284        self.maximum_notifications_per_response
285    }
286
287    /// Returns a bounded transport profile capable of carrying every static
288    /// MCP Skill file up to the SEP-2640 16 MiB raw-byte support floor.
289    ///
290    /// JSON string escaping can expand one raw UTF-8 byte to six wire bytes,
291    /// so the complete-response and SSE ceilings are intentionally larger
292    /// than the content limit. Concurrency remains low to bound aggregate
293    /// memory exposure.
294    #[must_use]
295    pub fn for_skills() -> Self {
296        let transport = ProviderHttpOptions::new(
297            Duration::from_secs(10),
298            Duration::from_secs(90),
299            16 * MEBIBYTE,
300            MCP_SKILL_WIRE_RESPONSE_BYTES,
301            MCP_SKILL_WIRE_RESPONSE_BYTES,
302            MCP_SKILL_WIRE_RESPONSE_BYTES,
303            128 * MEBIBYTE,
304        )
305        .expect("the MCP Skills transport profile is within hard limits");
306        Self {
307            transport,
308            request_timeout: Duration::from_secs(60),
309            skills_enabled: true,
310            maximum_authorization_retries: 1,
311            maximum_concurrent_requests: 2,
312            maximum_catalog_pages: 16,
313            maximum_catalog_tools: 1024,
314            maximum_notifications_per_response: 1024,
315        }
316    }
317}
318
319impl Default for McpClientOptions {
320    fn default() -> Self {
321        Self {
322            transport: ProviderHttpOptions::default(),
323            request_timeout: Duration::from_secs(30),
324            skills_enabled: false,
325            maximum_authorization_retries: 1,
326            maximum_concurrent_requests: 16,
327            maximum_catalog_pages: 16,
328            maximum_catalog_tools: 1024,
329            maximum_notifications_per_response: 1024,
330        }
331    }
332}
333
334/// Invalid general MCP client policy.
335#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
336#[non_exhaustive]
337pub enum McpClientOptionsError {
338    /// The request deadline must be positive.
339    #[error("MCP client request timeout must be positive")]
340    ZeroTimeout,
341    /// All resource ceilings must be positive.
342    #[error("MCP client resource limits must be positive")]
343    ZeroLimit,
344    /// A resource ceiling exceeded the implementation maximum.
345    #[error("MCP client resource limit exceeds the implementation maximum")]
346    AboveHardMaximum,
347}
348
349/// Public-safe request facts supplied to an authorization provider.
350#[derive(Clone, Debug, Eq, PartialEq)]
351pub struct McpClientAuthorizationRequest {
352    method: Box<str>,
353    name: Option<Box<str>>,
354}
355
356impl McpClientAuthorizationRequest {
357    /// Returns the exact MCP method.
358    #[must_use]
359    pub fn method(&self) -> &str {
360        &self.method
361    }
362
363    /// Returns the tool, prompt, or resource name when the method has one.
364    #[must_use]
365    pub fn name(&self) -> Option<&str> {
366        self.name.as_deref()
367    }
368
369    /// Returns the protocol version carried by this request.
370    #[must_use]
371    pub const fn protocol_version(&self) -> &'static str {
372        MCP_PROTOCOL_VERSION_2026_07_28
373    }
374}
375
376/// Resolves authorization independently for every stateless MCP POST.
377pub trait McpClientAuthorizationProvider: Send + Sync + 'static {
378    /// Resolves authorization without exposing it through request metadata.
379    fn resolve(
380        &self,
381        request: &McpClientAuthorizationRequest,
382    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>>;
383
384    /// Handles a bounded HTTP Bearer challenge before the transport decides
385    /// whether the exact MCP request may be replayed once.
386    ///
387    /// Providers that do not implement interactive OAuth decline by default.
388    fn handle_challenge<'a>(
389        &'a self,
390        _request: &'a McpClientAuthorizationRequest,
391        _challenge: &'a McpClientAuthorizationChallenge,
392    ) -> BoxFuture<'a, Result<McpClientAuthorizationRetry, McpAuthorizationError>> {
393        Box::pin(async { Ok(McpClientAuthorizationRetry::Decline) })
394    }
395}
396
397/// HTTP status that triggered an MCP authorization challenge.
398#[derive(Clone, Copy, Debug, Eq, PartialEq)]
399#[non_exhaustive]
400pub enum McpClientAuthorizationChallengeStatus {
401    /// The resource server rejected missing, expired, or invalid credentials.
402    Unauthorized,
403    /// The resource server rejected the credential's current permissions.
404    Forbidden,
405}
406
407/// Bounded, public-safe facts from an MCP resource-server challenge.
408#[derive(Clone, Debug, Eq, PartialEq)]
409pub struct McpClientAuthorizationChallenge {
410    status: McpClientAuthorizationChallengeStatus,
411    www_authenticate: Arc<[Box<str>]>,
412}
413
414impl McpClientAuthorizationChallenge {
415    /// Returns the challenge status.
416    #[must_use]
417    pub const fn status(&self) -> McpClientAuthorizationChallengeStatus {
418        self.status
419    }
420
421    /// Returns all syntactically valid, bounded `WWW-Authenticate` values in
422    /// wire order. Values remain untrusted input.
423    #[must_use]
424    pub fn www_authenticate(&self) -> impl ExactSizeIterator<Item = &str> {
425        self.www_authenticate.iter().map(AsRef::as_ref)
426    }
427
428    /// Returns the first Bearer challenge, matching the scheme
429    /// case-insensitively and without interpreting its parameters.
430    #[must_use]
431    pub fn bearer(&self) -> Option<&str> {
432        self.www_authenticate()
433            .find(|value| authentication_scheme(value) == Some("bearer"))
434    }
435}
436
437/// Result of an authorization provider handling one challenge.
438#[derive(Clone, Copy, Debug, Eq, PartialEq)]
439#[non_exhaustive]
440pub enum McpClientAuthorizationRetry {
441    /// Credentials changed and the transport may replay the rejected request.
442    Retry,
443    /// The provider did not handle this challenge.
444    Decline,
445}
446
447/// Cache metadata attached to a modern MCP result.
448#[derive(Clone, Debug, Default, Eq, PartialEq)]
449pub struct McpCachePolicy {
450    ttl_ms: Option<u64>,
451    scope: Option<Box<str>>,
452}
453
454impl McpCachePolicy {
455    pub(crate) fn required(ttl_ms: u64, scope: Box<str>) -> Self {
456        Self {
457            ttl_ms: Some(ttl_ms),
458            scope: Some(scope),
459        }
460    }
461
462    /// Returns the advertised freshness lifetime in milliseconds.
463    #[must_use]
464    pub const fn ttl_ms(&self) -> Option<u64> {
465        self.ttl_ms
466    }
467
468    /// Returns the server-provided cache scope.
469    #[must_use]
470    pub fn scope(&self) -> Option<&str> {
471        self.scope.as_deref()
472    }
473}
474
475/// Immutable server facts observed through `server/discover`.
476#[derive(Clone, Debug)]
477pub struct McpClientServer {
478    supported_versions: Arc<[Box<str>]>,
479    capabilities: Arc<Map<String, Value>>,
480    name: Option<Box<str>>,
481    version: Option<Box<str>>,
482    instructions: Option<Box<str>>,
483    cache: McpCachePolicy,
484}
485
486impl McpClientServer {
487    /// Returns the protocol versions in the server's advertised order.
488    #[must_use]
489    pub fn supported_versions(&self) -> impl ExactSizeIterator<Item = &str> {
490        self.supported_versions.iter().map(AsRef::as_ref)
491    }
492
493    /// Returns the untrusted server capability object.
494    #[must_use]
495    pub fn capabilities(&self) -> &Map<String, Value> {
496        &self.capabilities
497    }
498
499    /// Returns whether discovery advertised the Tool capability.
500    #[must_use]
501    pub fn supports_tools(&self) -> bool {
502        self.capabilities.contains_key("tools")
503    }
504
505    /// Returns whether discovery advertised the base Resources capability.
506    #[must_use]
507    pub fn supports_resources(&self) -> bool {
508        self.capabilities
509            .get("resources")
510            .is_some_and(Value::is_object)
511    }
512
513    /// Returns the untrusted Skills extension capability object when present.
514    #[must_use]
515    pub fn skills_extension(&self) -> Option<&Map<String, Value>> {
516        self.capabilities
517            .get("extensions")
518            .and_then(Value::as_object)
519            .and_then(|extensions| extensions.get(crate::MCP_SKILLS_EXTENSION_ID))
520            .and_then(Value::as_object)
521    }
522
523    /// Returns the self-reported server implementation name.
524    #[must_use]
525    pub fn name(&self) -> Option<&str> {
526        self.name.as_deref()
527    }
528
529    /// Returns the self-reported server implementation version.
530    #[must_use]
531    pub fn version(&self) -> Option<&str> {
532        self.version.as_deref()
533    }
534
535    /// Returns untrusted natural-language usage instructions.
536    #[must_use]
537    pub fn instructions(&self) -> Option<&str> {
538        self.instructions.as_deref()
539    }
540
541    /// Returns the discovery result's cache metadata.
542    #[must_use]
543    pub const fn cache(&self) -> &McpCachePolicy {
544        &self.cache
545    }
546}
547
548#[derive(Clone, Copy, Debug, Eq, PartialEq)]
549enum HeaderValueKind {
550    String,
551    Integer,
552    Boolean,
553}
554
555#[derive(Clone, Debug)]
556struct HeaderBinding {
557    path: Arc<[Box<str>]>,
558    name: Box<str>,
559    kind: HeaderValueKind,
560}
561
562/// One validated Tool discovered from this exact client binding.
563#[derive(Clone)]
564pub struct McpTool {
565    binding_id: u64,
566    name: Box<str>,
567    title: Option<Box<str>>,
568    description: Option<Box<str>>,
569    input_schema: Arc<Value>,
570    output_schema: Option<Arc<Value>>,
571    raw: Arc<Value>,
572    headers: Arc<[HeaderBinding]>,
573}
574
575impl McpTool {
576    /// Returns the server-scoped Tool name.
577    #[must_use]
578    pub fn name(&self) -> &str {
579        &self.name
580    }
581
582    /// Returns the optional human-readable title.
583    #[must_use]
584    pub fn title(&self) -> Option<&str> {
585        self.title.as_deref()
586    }
587
588    /// Returns the optional untrusted Tool description.
589    #[must_use]
590    pub fn description(&self) -> Option<&str> {
591        self.description.as_deref()
592    }
593
594    /// Returns the Tool's untrusted input JSON Schema without resolving refs.
595    #[must_use]
596    pub fn input_schema(&self) -> &Value {
597        &self.input_schema
598    }
599
600    /// Returns the optional untrusted output JSON Schema without resolving refs.
601    #[must_use]
602    pub fn output_schema(&self) -> Option<&Value> {
603        self.output_schema.as_deref()
604    }
605
606    /// Returns the complete bounded wire descriptor, including extensions.
607    #[must_use]
608    pub fn raw(&self) -> &Value {
609        &self.raw
610    }
611}
612
613impl fmt::Debug for McpTool {
614    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
615        formatter
616            .debug_struct("McpTool")
617            .field("name", &self.name)
618            .field("title", &self.title)
619            .field("has_output_schema", &self.output_schema.is_some())
620            .field("promoted_header_count", &self.headers.len())
621            .finish_non_exhaustive()
622    }
623}
624
625/// Why one advertised Tool was excluded from the usable catalog.
626#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
627#[non_exhaustive]
628pub enum McpToolRejectionReason {
629    /// The descriptor was not a JSON object.
630    #[error("tool descriptor is not an object")]
631    DescriptorNotObject,
632    /// The Tool name was absent or outside its implementation bound.
633    #[error("tool name is invalid")]
634    InvalidName,
635    /// `inputSchema` was absent or not a JSON object.
636    #[error("tool input schema is invalid")]
637    InvalidInputSchema,
638    /// `outputSchema`, when present, was not a JSON object.
639    #[error("tool output schema is invalid")]
640    InvalidOutputSchema,
641    /// An `x-mcp-header` annotation was not a string.
642    #[error("x-mcp-header annotation is not a string")]
643    HeaderNameNotString,
644    /// An `x-mcp-header` annotation was empty or not an RFC 9110 token.
645    #[error("x-mcp-header annotation is not a valid HTTP token")]
646    InvalidHeaderName,
647    /// Header annotations were not case-insensitively unique.
648    #[error("x-mcp-header annotations contain a duplicate name")]
649    DuplicateHeaderName,
650    /// An annotation targeted a non-string/integer/boolean property.
651    #[error("x-mcp-header annotation targets a non-primitive property")]
652    HeaderOnNonPrimitive,
653    /// An annotation was reachable only through a forbidden schema keyword.
654    #[error("x-mcp-header annotation is not statically property-reachable")]
655    HeaderNotStaticallyReachable,
656}
657
658/// One excluded Tool and its public-safe reason.
659#[derive(Clone, Debug, Eq, PartialEq)]
660pub struct McpRejectedTool {
661    name: Option<Box<str>>,
662    reason: McpToolRejectionReason,
663}
664
665impl McpRejectedTool {
666    /// Returns the bounded Tool name when it could be read safely.
667    #[must_use]
668    pub fn name(&self) -> Option<&str> {
669        self.name.as_deref()
670    }
671
672    /// Returns the exclusion reason.
673    #[must_use]
674    pub const fn reason(&self) -> McpToolRejectionReason {
675        self.reason
676    }
677}
678
679/// One bounded page from `tools/list`.
680#[derive(Clone, Debug)]
681pub struct McpToolPage {
682    tools: Vec<McpTool>,
683    rejected: Vec<McpRejectedTool>,
684    next_cursor: Option<Box<str>>,
685    cache: McpCachePolicy,
686    advertised_count: usize,
687}
688
689impl McpToolPage {
690    /// Returns usable Tools after invalid header annotations were excluded.
691    #[must_use]
692    pub fn tools(&self) -> &[McpTool] {
693        &self.tools
694    }
695
696    /// Returns auditable exclusions without making invalid Tools callable.
697    #[must_use]
698    pub fn rejected_tools(&self) -> &[McpRejectedTool] {
699        &self.rejected
700    }
701
702    /// Returns the opaque next-page cursor.
703    #[must_use]
704    pub fn next_cursor(&self) -> Option<&str> {
705        self.next_cursor.as_deref()
706    }
707
708    /// Returns cache metadata for this page.
709    #[must_use]
710    pub const fn cache(&self) -> &McpCachePolicy {
711        &self.cache
712    }
713}
714
715/// A complete bounded Tool catalog.
716#[derive(Clone, Debug)]
717pub struct McpToolCatalog {
718    tools: Vec<McpTool>,
719    rejected: Vec<McpRejectedTool>,
720}
721
722impl McpToolCatalog {
723    /// Returns all usable Tools in server page order.
724    #[must_use]
725    pub fn tools(&self) -> &[McpTool] {
726        &self.tools
727    }
728
729    /// Returns all excluded Tool descriptors in server page order.
730    #[must_use]
731    pub fn rejected_tools(&self) -> &[McpRejectedTool] {
732        &self.rejected
733    }
734
735    /// Finds one usable Tool by its exact case-sensitive name.
736    #[must_use]
737    pub fn find(&self, name: &str) -> Option<&McpTool> {
738        self.tools.iter().find(|tool| tool.name() == name)
739    }
740}
741
742/// One request-scoped server notification received before an SSE final response.
743#[derive(Clone, Debug, PartialEq)]
744pub struct McpNotification {
745    method: Box<str>,
746    params: Option<Value>,
747    raw: Value,
748}
749
750impl McpNotification {
751    /// Returns the notification method.
752    #[must_use]
753    pub fn method(&self) -> &str {
754        &self.method
755    }
756
757    /// Returns optional untrusted notification parameters.
758    #[must_use]
759    pub const fn params(&self) -> Option<&Value> {
760        self.params.as_ref()
761    }
762
763    /// Returns the complete bounded notification.
764    #[must_use]
765    pub const fn raw(&self) -> &Value {
766        &self.raw
767    }
768}
769
770/// A complete Tool result. Tool-level failures remain results through
771/// [`Self::is_error`] so an Agent can inspect and recover from them.
772#[derive(Clone, Debug, PartialEq)]
773pub struct McpCompleteToolResult {
774    content: Vec<Value>,
775    structured_content: Option<Value>,
776    is_error: bool,
777    raw: Value,
778}
779
780impl McpCompleteToolResult {
781    /// Returns untrusted MCP content blocks.
782    #[must_use]
783    pub fn content(&self) -> &[Value] {
784        &self.content
785    }
786
787    /// Returns optional structured output without applying a local trust policy.
788    #[must_use]
789    pub const fn structured_content(&self) -> Option<&Value> {
790        self.structured_content.as_ref()
791    }
792
793    /// Returns whether the remote Tool reported an execution failure.
794    #[must_use]
795    pub const fn is_error(&self) -> bool {
796        self.is_error
797    }
798
799    /// Returns the complete bounded result object.
800    #[must_use]
801    pub const fn raw(&self) -> &Value {
802        &self.raw
803    }
804}
805
806/// An input-required Tool result bound to the exact original request.
807///
808/// Resuming consumes this value, ensuring the opaque `requestState` cannot be
809/// accidentally reused by a second retry through the safe API.
810pub struct McpInputRequired {
811    client: McpClient,
812    tool: McpTool,
813    arguments: Map<String, Value>,
814    input_requests: Map<String, Value>,
815    request_state: Option<Box<str>>,
816}
817
818impl McpInputRequired {
819    /// Returns the server-client requests that must be fulfilled.
820    #[must_use]
821    pub const fn input_requests(&self) -> &Map<String, Value> {
822        &self.input_requests
823    }
824
825    /// Returns whether the server supplied opaque state. Its bytes are kept
826    /// private so callers cannot accidentally parse and reconstruct it.
827    #[must_use]
828    pub const fn has_request_state(&self) -> bool {
829        self.request_state.is_some()
830    }
831
832    /// Retries the original Tool call with one response for every requested key.
833    pub async fn resume(
834        self,
835        input_responses: Map<String, Value>,
836    ) -> Result<McpToolCallResponse, StatelessMcpClientError> {
837        let expected = self.input_requests.keys().collect::<HashSet<_>>();
838        let actual = input_responses.keys().collect::<HashSet<_>>();
839        if expected != actual {
840            return Err(StatelessMcpClientError::InputResponseKeysMismatch);
841        }
842        self.client
843            .call_tool_round(
844                &self.tool,
845                self.arguments,
846                Some(input_responses),
847                self.request_state,
848            )
849            .await
850    }
851}
852
853impl fmt::Debug for McpInputRequired {
854    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
855        formatter
856            .debug_struct("McpInputRequired")
857            .field("tool", &self.tool.name())
858            .field("input_request_count", &self.input_requests.len())
859            .field("has_request_state", &self.request_state.is_some())
860            .finish_non_exhaustive()
861    }
862}
863
864/// The protocol outcome of one Tool-call round.
865#[derive(Debug)]
866#[non_exhaustive]
867pub enum McpToolCall {
868    /// The server completed the Tool call.
869    Complete(McpCompleteToolResult),
870    /// The server requires client-side input before a distinct retry.
871    InputRequired(McpInputRequired),
872}
873
874/// One Tool-call round plus any request-scoped SSE notifications.
875#[derive(Debug)]
876pub struct McpToolCallResponse {
877    outcome: McpToolCall,
878    notifications: Vec<McpNotification>,
879}
880
881impl McpToolCallResponse {
882    /// Returns the complete or input-required outcome.
883    #[must_use]
884    pub const fn outcome(&self) -> &McpToolCall {
885        &self.outcome
886    }
887
888    /// Consumes the envelope and returns the outcome.
889    #[must_use]
890    pub fn into_outcome(self) -> McpToolCall {
891        self.outcome
892    }
893
894    /// Returns request-scoped notifications in arrival order.
895    #[must_use]
896    pub fn notifications(&self) -> &[McpNotification] {
897        &self.notifications
898    }
899}
900
901/// A bounded JSON-RPC error returned by the MCP server.
902#[derive(Clone, Debug, PartialEq)]
903pub struct McpRemoteError {
904    code: i32,
905    message: Box<str>,
906    data: Option<Value>,
907}
908
909impl McpRemoteError {
910    /// Returns the JSON-RPC error code.
911    #[must_use]
912    pub const fn code(&self) -> i32 {
913        self.code
914    }
915
916    /// Returns the untrusted bounded error message.
917    #[must_use]
918    pub fn message(&self) -> &str {
919        &self.message
920    }
921
922    /// Returns optional untrusted error data.
923    #[must_use]
924    pub const fn data(&self) -> Option<&Value> {
925        self.data.as_ref()
926    }
927}
928
929impl fmt::Display for McpRemoteError {
930    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
931        write!(formatter, "JSON-RPC error {}", self.code)
932    }
933}
934
935impl std::error::Error for McpRemoteError {}
936
937/// Closed failure from the modern stateless MCP client.
938#[derive(Debug, Error)]
939#[non_exhaustive]
940pub enum StatelessMcpClientError {
941    /// Endpoint normalization failed.
942    #[error("invalid MCP endpoint: {0}")]
943    Endpoint(#[from] ProviderEndpointError),
944    /// The bounded no-redirect HTTP client could not be built.
945    #[error("MCP HTTP client construction failed")]
946    HttpClient,
947    /// Request authorization could not be resolved.
948    #[error(transparent)]
949    Authorization(#[from] McpAuthorizationError),
950    /// The request deadline elapsed. A Tool with external effects may require
951    /// authoritative reconciliation before any retry.
952    #[error("MCP request deadline elapsed")]
953    Timeout,
954    /// A unique local request identifier could no longer be allocated.
955    #[error("MCP request identifier space is exhausted")]
956    RequestIdExhausted,
957    /// A unique client binding identifier could no longer be allocated.
958    #[error("MCP client binding identifier space is exhausted")]
959    ClientBindingIdExhausted,
960    /// JSON request serialization failed.
961    #[error("MCP request serialization failed")]
962    RequestSerialization,
963    /// The serialized request exceeded its configured byte ceiling.
964    #[error("MCP request exceeded its byte ceiling")]
965    RequestTooLarge,
966    /// The network exchange failed without a trustworthy protocol outcome.
967    #[error("MCP HTTP transport failed")]
968    Transport,
969    /// The endpoint requires authorization.
970    #[error("MCP endpoint requires authorization")]
971    AuthorizationRequired,
972    /// An HTTP authorization challenge exceeded its syntax or resource bounds.
973    #[error("MCP endpoint returned an invalid authorization challenge")]
974    InvalidAuthorizationChallenge,
975    /// The supplied authorization lacks permission.
976    #[error("MCP endpoint denied permission")]
977    PermissionDenied,
978    /// The complete response exceeded its configured byte ceiling.
979    #[error("MCP response exceeded its byte ceiling")]
980    ResponseTooLarge,
981    /// The request-scoped event stream violated framing or resource bounds.
982    #[error("MCP event stream is invalid")]
983    InvalidEventStream,
984    /// The response did not use JSON or request-scoped SSE.
985    #[error("MCP response has an unsupported content type")]
986    UnexpectedContentType,
987    /// The endpoint returned an HTTP failure without a valid JSON-RPC error.
988    #[error("MCP endpoint returned HTTP status {0}")]
989    HttpStatus(u16),
990    /// The response was not a valid matching JSON-RPC response.
991    #[error("MCP response violated the JSON-RPC contract")]
992    Protocol,
993    /// The server returned a bounded JSON-RPC error.
994    #[error("MCP server returned {0}")]
995    Remote(McpRemoteError),
996    /// Version negotiation produced no mutually supported modern revision.
997    #[error("MCP server does not support protocol version 2026-07-28")]
998    UnsupportedProtocolVersion,
999    /// Discovery did not advertise the required modern revision.
1000    #[error("MCP discovery omitted protocol version 2026-07-28")]
1001    DiscoveryVersionMismatch,
1002    /// Discovery returned an invalid result.
1003    #[error("MCP discovery result is invalid")]
1004    InvalidDiscovery,
1005    /// A `tools/list` result was invalid.
1006    #[error("MCP Tool catalog response is invalid")]
1007    InvalidToolCatalog,
1008    /// Discovery did not advertise the Tool capability.
1009    #[error("MCP server did not advertise the Tool capability")]
1010    ToolsNotAdvertised,
1011    /// Catalog entries exceeded the configured ceiling.
1012    #[error("MCP Tool catalog exceeds its entry limit")]
1013    ToolCatalogTooLarge,
1014    /// Catalog pagination did not terminate within its configured ceiling.
1015    #[error("MCP Tool catalog exceeds its page limit")]
1016    ToolCatalogPageLimit,
1017    /// A cursor was empty, too large, or repeated.
1018    #[error("MCP Tool catalog pagination cursor is invalid")]
1019    InvalidPagination,
1020    /// A usable Tool name appeared more than once.
1021    #[error("MCP Tool catalog contains a duplicate usable name")]
1022    DuplicateToolName,
1023    /// The Tool descriptor belongs to another endpoint binding.
1024    #[error("MCP Tool belongs to a different client binding")]
1025    ForeignToolBinding,
1026    /// Tool arguments were not a JSON object.
1027    #[error("MCP Tool arguments must be a JSON object")]
1028    InvalidToolArguments,
1029    /// An annotated argument was not a safe value for its declared header type.
1030    #[error("MCP Tool header argument is invalid")]
1031    InvalidHeaderArgument,
1032    /// MRTR response keys did not exactly match the pending input requests.
1033    #[error("MCP input response keys do not match the pending requests")]
1034    InputResponseKeysMismatch,
1035    /// The Tool result was neither complete nor a valid input-required result.
1036    #[error("MCP Tool result is invalid")]
1037    InvalidToolResult,
1038    /// Too many notifications preceded the final SSE response.
1039    #[error("MCP response exceeded its notification limit")]
1040    TooManyNotifications,
1041}
1042
1043struct McpClientInner {
1044    http: reqwest::Client,
1045    endpoint: reqwest::Url,
1046    identity: McpClientIdentity,
1047    authorization: Arc<dyn McpClientAuthorizationProvider>,
1048    options: McpClientOptions,
1049    concurrency: tokio::sync::Semaphore,
1050    next_request_id: AtomicU64,
1051    binding_id: u64,
1052    server: std::sync::OnceLock<McpClientServer>,
1053}
1054
1055/// Connected general-purpose client for the stateless MCP 2026-07-28 Tool
1056/// surface.
1057#[derive(Clone)]
1058pub struct McpClient {
1059    inner: Arc<McpClientInner>,
1060}
1061
1062impl McpClient {
1063    /// Builds a bounded transport and validates the endpoint through
1064    /// `server/discover`.
1065    ///
1066    /// Automatic replays are limited to one `-32022`
1067    /// `UnsupportedProtocolVersion` recovery and the configured bounded OAuth
1068    /// challenge count. Redirects and generic HTTP retries remain off.
1069    pub async fn connect(
1070        endpoint: ProviderEndpoint,
1071        identity: McpClientIdentity,
1072        authorization: Arc<dyn McpClientAuthorizationProvider>,
1073        options: McpClientOptions,
1074    ) -> Result<Self, StatelessMcpClientError> {
1075        let endpoint = endpoint.join("")?;
1076        let http =
1077            build_client(options.transport()).map_err(|_| StatelessMcpClientError::HttpClient)?;
1078        let binding_id = allocate_monotonic_id(&NEXT_CLIENT_BINDING_ID)
1079            .ok_or(StatelessMcpClientError::ClientBindingIdExhausted)?;
1080        let client = Self {
1081            inner: Arc::new(McpClientInner {
1082                http,
1083                endpoint,
1084                identity,
1085                authorization,
1086                options,
1087                concurrency: tokio::sync::Semaphore::new(options.maximum_concurrent_requests()),
1088                next_request_id: AtomicU64::new(1),
1089                binding_id,
1090                server: std::sync::OnceLock::new(),
1091            }),
1092        };
1093        let exchange = client
1094            .send_rpc("server/discover", None, Map::new(), Vec::new())
1095            .await?;
1096        let server = parse_discovery(&exchange.result)?;
1097        if !server
1098            .supported_versions()
1099            .any(|version| version == MCP_PROTOCOL_VERSION_2026_07_28)
1100        {
1101            return Err(StatelessMcpClientError::DiscoveryVersionMismatch);
1102        }
1103        client
1104            .inner
1105            .server
1106            .set(server)
1107            .map_err(|_| StatelessMcpClientError::InvalidDiscovery)?;
1108        Ok(client)
1109    }
1110
1111    /// Returns the identity sent on every request.
1112    #[must_use]
1113    pub fn identity(&self) -> &McpClientIdentity {
1114        &self.inner.identity
1115    }
1116
1117    /// Returns the immutable discovery snapshot.
1118    #[must_use]
1119    pub fn server(&self) -> &McpClientServer {
1120        self.inner
1121            .server
1122            .get()
1123            .expect("connected MCP clients always retain discovery")
1124    }
1125
1126    /// Requests one bounded page of usable Tools.
1127    pub async fn list_tools_page(
1128        &self,
1129        cursor: Option<&str>,
1130    ) -> Result<McpToolPage, StatelessMcpClientError> {
1131        if !self.server().supports_tools() {
1132            return Err(StatelessMcpClientError::ToolsNotAdvertised);
1133        }
1134        if cursor.is_some_and(|value| value.is_empty() || value.len() > MAX_CURSOR_BYTES) {
1135            return Err(StatelessMcpClientError::InvalidPagination);
1136        }
1137        let mut params = Map::new();
1138        if let Some(cursor) = cursor {
1139            params.insert("cursor".to_owned(), Value::String(cursor.to_owned()));
1140        }
1141        let exchange = self
1142            .send_rpc("tools/list", None, params, Vec::new())
1143            .await?;
1144        parse_tool_page(&exchange.result, self.inner.binding_id)
1145    }
1146
1147    /// Traverses the complete bounded Tool catalog and rejects cyclic cursors
1148    /// or duplicate usable names.
1149    pub async fn list_tools(&self) -> Result<McpToolCatalog, StatelessMcpClientError> {
1150        let mut cursor: Option<Box<str>> = None;
1151        let mut seen_cursors = HashSet::new();
1152        let mut seen_names = HashSet::new();
1153        let mut tools = Vec::new();
1154        let mut rejected = Vec::new();
1155        let mut advertised = 0usize;
1156
1157        for _ in 0..self.inner.options.maximum_catalog_pages() {
1158            let page = self.list_tools_page(cursor.as_deref()).await?;
1159            advertised = advertised
1160                .checked_add(page.advertised_count)
1161                .ok_or(StatelessMcpClientError::ToolCatalogTooLarge)?;
1162            if advertised > self.inner.options.maximum_catalog_tools() {
1163                return Err(StatelessMcpClientError::ToolCatalogTooLarge);
1164            }
1165            for tool in page.tools {
1166                if !seen_names.insert(tool.name.to_string()) {
1167                    return Err(StatelessMcpClientError::DuplicateToolName);
1168                }
1169                tools.push(tool);
1170            }
1171            rejected.extend(page.rejected);
1172            let Some(next) = page.next_cursor else {
1173                return Ok(McpToolCatalog { tools, rejected });
1174            };
1175            if next.is_empty()
1176                || next.len() > MAX_CURSOR_BYTES
1177                || !seen_cursors.insert(next.to_string())
1178            {
1179                return Err(StatelessMcpClientError::InvalidPagination);
1180            }
1181            cursor = Some(next);
1182        }
1183        Err(StatelessMcpClientError::ToolCatalogPageLimit)
1184    }
1185
1186    /// Calls one Tool discovered from this exact client binding.
1187    pub async fn call_tool(
1188        &self,
1189        tool: &McpTool,
1190        arguments: Value,
1191    ) -> Result<McpToolCallResponse, StatelessMcpClientError> {
1192        let arguments = arguments
1193            .as_object()
1194            .cloned()
1195            .ok_or(StatelessMcpClientError::InvalidToolArguments)?;
1196        self.call_tool_round(tool, arguments, None, None).await
1197    }
1198
1199    /// Calls a discovered Tool with at most one HTTP exchange.
1200    ///
1201    /// Unlike [`Self::call_tool`], this never replays a rejected request for
1202    /// protocol negotiation or an OAuth challenge. The caller owns recovery;
1203    /// redirects and generic transport retries are also disabled. An MRTR
1204    /// response is returned, not automatically resumed.
1205    pub async fn call_tool_once(
1206        &self,
1207        tool: &McpTool,
1208        arguments: Value,
1209    ) -> Result<McpToolCallResponse, StatelessMcpClientError> {
1210        let arguments = arguments
1211            .as_object()
1212            .cloned()
1213            .ok_or(StatelessMcpClientError::InvalidToolArguments)?;
1214        self.call_tool_round_policy(tool, arguments, None, None, false)
1215            .await
1216    }
1217
1218    async fn call_tool_round(
1219        &self,
1220        tool: &McpTool,
1221        arguments: Map<String, Value>,
1222        input_responses: Option<Map<String, Value>>,
1223        request_state: Option<Box<str>>,
1224    ) -> Result<McpToolCallResponse, StatelessMcpClientError> {
1225        self.call_tool_round_policy(tool, arguments, input_responses, request_state, true)
1226            .await
1227    }
1228
1229    async fn call_tool_round_policy(
1230        &self,
1231        tool: &McpTool,
1232        arguments: Map<String, Value>,
1233        input_responses: Option<Map<String, Value>>,
1234        request_state: Option<Box<str>>,
1235        recover: bool,
1236    ) -> Result<McpToolCallResponse, StatelessMcpClientError> {
1237        if tool.binding_id != self.inner.binding_id {
1238            return Err(StatelessMcpClientError::ForeignToolBinding);
1239        }
1240        let headers = promoted_headers(tool, &arguments)?;
1241        let mut params = Map::new();
1242        params.insert("name".to_owned(), Value::String(tool.name.to_string()));
1243        params.insert("arguments".to_owned(), Value::Object(arguments.clone()));
1244        if let Some(input_responses) = input_responses {
1245            params.insert("inputResponses".to_owned(), Value::Object(input_responses));
1246        }
1247        if let Some(request_state) = request_state.as_deref() {
1248            params.insert(
1249                "requestState".to_owned(),
1250                Value::String(request_state.to_owned()),
1251            );
1252        }
1253        let exchange = if recover {
1254            self.send_rpc("tools/call", Some(tool.name()), params, headers)
1255                .await?
1256        } else {
1257            let request = McpClientAuthorizationRequest {
1258                method: "tools/call".into(),
1259                name: Some(tool.name().into()),
1260            };
1261            let deadline = tokio::time::Instant::now() + self.inner.options.request_timeout();
1262            match self
1263                .send_rpc_once(deadline, &request, params, headers)
1264                .await?
1265            {
1266                RpcAttempt::Exchange(exchange) => exchange,
1267                RpcAttempt::Challenge(challenge) => {
1268                    return Err(challenge_error(challenge.status()));
1269                }
1270            }
1271        };
1272        let outcome = parse_tool_result(exchange.result, self.clone(), tool.clone(), arguments)?;
1273        Ok(McpToolCallResponse {
1274            outcome,
1275            notifications: exchange.notifications,
1276        })
1277    }
1278
1279    async fn send_rpc(
1280        &self,
1281        method: &str,
1282        name: Option<&str>,
1283        params: Map<String, Value>,
1284        promoted_headers: Vec<(HeaderName, HeaderValue)>,
1285    ) -> Result<RpcExchange, StatelessMcpClientError> {
1286        let mut attempted_version_retry = false;
1287        let mut authorization_retries = 0usize;
1288        let authorization_request = McpClientAuthorizationRequest {
1289            method: method.to_owned().into_boxed_str(),
1290            name: name.map(|value| value.to_owned().into_boxed_str()),
1291        };
1292        loop {
1293            let deadline = tokio::time::Instant::now() + self.inner.options.request_timeout();
1294            let response = self
1295                .send_rpc_once(
1296                    deadline,
1297                    &authorization_request,
1298                    params.clone(),
1299                    promoted_headers.clone(),
1300                )
1301                .await;
1302            match response {
1303                Ok(RpcAttempt::Challenge(challenge)) => {
1304                    if authorization_retries >= self.inner.options.maximum_authorization_retries() {
1305                        return Err(challenge_error(challenge.status()));
1306                    }
1307                    let decision = self
1308                        .inner
1309                        .authorization
1310                        .handle_challenge(&authorization_request, &challenge)
1311                        .await?;
1312                    match decision {
1313                        McpClientAuthorizationRetry::Retry => {
1314                            authorization_retries += 1;
1315                        }
1316                        McpClientAuthorizationRetry::Decline => {
1317                            return Err(challenge_error(challenge.status()));
1318                        }
1319                    }
1320                }
1321                Err(StatelessMcpClientError::Remote(error))
1322                    if error.code() == -32_022 && !attempted_version_retry =>
1323                {
1324                    if !remote_supports_current_version(&error) {
1325                        return Err(StatelessMcpClientError::UnsupportedProtocolVersion);
1326                    }
1327                    attempted_version_retry = true;
1328                }
1329                Ok(RpcAttempt::Exchange(exchange)) => return Ok(exchange),
1330                Err(error) => return Err(error),
1331            }
1332        }
1333    }
1334
1335    async fn send_rpc_once(
1336        &self,
1337        deadline: tokio::time::Instant,
1338        authorization_request: &McpClientAuthorizationRequest,
1339        mut params: Map<String, Value>,
1340        promoted_headers: Vec<(HeaderName, HeaderValue)>,
1341    ) -> Result<RpcAttempt, StatelessMcpClientError> {
1342        let method = authorization_request.method();
1343        let name = authorization_request.name();
1344        let id = allocate_monotonic_id(&self.inner.next_request_id)
1345            .ok_or(StatelessMcpClientError::RequestIdExhausted)?;
1346        params.insert("_meta".to_owned(), Value::Object(self.request_metadata()));
1347        let body = serde_json::to_vec(&json!({
1348            "jsonrpc": "2.0",
1349            "id": id,
1350            "method": method,
1351            "params": params,
1352        }))
1353        .map_err(|_| StatelessMcpClientError::RequestSerialization)?;
1354        if body.len() > self.inner.options.transport().maximum_request_bytes() {
1355            return Err(StatelessMcpClientError::RequestTooLarge);
1356        }
1357
1358        let permit = wait_until(deadline, self.inner.concurrency.acquire())
1359            .await?
1360            .map_err(|_| StatelessMcpClientError::Transport)?;
1361        let authorization = wait_until(
1362            deadline,
1363            self.inner.authorization.resolve(authorization_request),
1364        )
1365        .await??;
1366
1367        let mut request = self
1368            .inner
1369            .http
1370            .post(self.inner.endpoint.clone())
1371            .header(header::ACCEPT, MCP_ACCEPT)
1372            .header(header::CONTENT_TYPE, MCP_JSON)
1373            .header(MCP_HEADER_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION_2026_07_28)
1374            .header(MCP_HEADER_METHOD, method);
1375        if let Some(name) = name {
1376            request = request.header(MCP_HEADER_NAME, encode_header_value(name));
1377        }
1378        match authorization {
1379            McpAuthorization::Anonymous => {}
1380            McpAuthorization::Bearer(key) => {
1381                request = request.bearer_auth(key.expose_secret());
1382            }
1383        }
1384        for (header_name, header_value) in promoted_headers {
1385            request = request.header(header_name, header_value);
1386        }
1387        let response = wait_until(deadline, request.body(body).send())
1388            .await?
1389            .map_err(|_| StatelessMcpClientError::Transport)?;
1390        let output = if matches!(
1391            response.status(),
1392            StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN
1393        ) {
1394            parse_authorization_challenge(&response).map(RpcAttempt::Challenge)
1395        } else {
1396            self.consume_response(deadline, id, response)
1397                .await
1398                .map(RpcAttempt::Exchange)
1399        };
1400        drop(permit);
1401        output
1402    }
1403
1404    fn request_metadata(&self) -> Map<String, Value> {
1405        let mut metadata = Map::new();
1406        metadata.insert(
1407            MCP_META_PROTOCOL_VERSION.to_owned(),
1408            Value::String(MCP_PROTOCOL_VERSION_2026_07_28.to_owned()),
1409        );
1410        metadata.insert(
1411            MCP_META_CLIENT_INFO.to_owned(),
1412            json!({
1413                "name": self.inner.identity.name(),
1414                "version": self.inner.identity.version(),
1415            }),
1416        );
1417        let client_capabilities = if self.inner.options.skills_enabled() {
1418            json!({
1419                "extensions": {
1420                    (crate::MCP_SKILLS_EXTENSION_ID): {}
1421                }
1422            })
1423        } else {
1424            Value::Object(Map::new())
1425        };
1426        metadata.insert(MCP_META_CLIENT_CAPABILITIES.to_owned(), client_capabilities);
1427        metadata
1428    }
1429
1430    pub(crate) async fn send_extension_rpc(
1431        &self,
1432        method: &str,
1433        name: Option<&str>,
1434        params: Map<String, Value>,
1435    ) -> Result<Value, StatelessMcpClientError> {
1436        Ok(self
1437            .send_rpc(method, name, params, Vec::new())
1438            .await?
1439            .result)
1440    }
1441
1442    pub(crate) fn binding_id(&self) -> u64 {
1443        self.inner.binding_id
1444    }
1445
1446    pub(crate) fn options(&self) -> McpClientOptions {
1447        self.inner.options
1448    }
1449
1450    async fn consume_response(
1451        &self,
1452        deadline: tokio::time::Instant,
1453        id: u64,
1454        response: reqwest::Response,
1455    ) -> Result<RpcExchange, StatelessMcpClientError> {
1456        let status = response.status();
1457        if matches!(status, StatusCode::ACCEPTED | StatusCode::NO_CONTENT) {
1458            return Err(StatelessMcpClientError::Protocol);
1459        }
1460        let content_type = response
1461            .headers()
1462            .get(header::CONTENT_TYPE)
1463            .and_then(|value| value.to_str().ok())
1464            .and_then(normalize_content_type);
1465        match content_type {
1466            Some(MCP_JSON) => {
1467                let body = wait_until(
1468                    deadline,
1469                    bounded_body(
1470                        response,
1471                        self.inner.options.transport().maximum_response_bytes(),
1472                    ),
1473                )
1474                .await??;
1475                let value = serde_json::from_slice::<Value>(&body)
1476                    .map_err(|_| StatelessMcpClientError::Protocol)?;
1477                match classify_rpc_message(value, id)? {
1478                    ParsedMessage::Result(result) if status.is_success() => Ok(RpcExchange {
1479                        result,
1480                        notifications: Vec::new(),
1481                    }),
1482                    ParsedMessage::Remote(error) => Err(StatelessMcpClientError::Remote(error)),
1483                    _ if !status.is_success() => {
1484                        Err(StatelessMcpClientError::HttpStatus(status.as_u16()))
1485                    }
1486                    _ => Err(StatelessMcpClientError::Protocol),
1487                }
1488            }
1489            Some(MCP_EVENT_STREAM) if status.is_success() => {
1490                self.consume_event_stream(deadline, id, response).await
1491            }
1492            Some(_) | None if !status.is_success() => {
1493                Err(StatelessMcpClientError::HttpStatus(status.as_u16()))
1494            }
1495            Some(_) | None => Err(StatelessMcpClientError::UnexpectedContentType),
1496        }
1497    }
1498
1499    async fn consume_event_stream(
1500        &self,
1501        deadline: tokio::time::Instant,
1502        id: u64,
1503        response: reqwest::Response,
1504    ) -> Result<RpcExchange, StatelessMcpClientError> {
1505        let mut stream = response.bytes_stream();
1506        let mut decoder = SseDecoder::new(self.inner.options.transport());
1507        let mut notifications = Vec::new();
1508        while let Some(chunk) = wait_until(deadline, stream.next()).await? {
1509            let chunk = chunk.map_err(|_| StatelessMcpClientError::Transport)?;
1510            let events = decoder.push(&chunk).map_err(map_sse_error)?;
1511            if let Some(result) = consume_sse_events(
1512                events,
1513                id,
1514                &mut notifications,
1515                self.inner.options.maximum_notifications_per_response(),
1516            )? {
1517                return Ok(RpcExchange {
1518                    result,
1519                    notifications,
1520                });
1521            }
1522        }
1523        let events = decoder.finish().map_err(map_sse_error)?;
1524        if let Some(result) = consume_sse_events(
1525            events,
1526            id,
1527            &mut notifications,
1528            self.inner.options.maximum_notifications_per_response(),
1529        )? {
1530            return Ok(RpcExchange {
1531                result,
1532                notifications,
1533            });
1534        }
1535        Err(StatelessMcpClientError::Protocol)
1536    }
1537}
1538
1539impl fmt::Debug for McpClient {
1540    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1541        formatter
1542            .debug_struct("McpClient")
1543            .field("identity", &self.inner.identity)
1544            .field("protocol_version", &MCP_PROTOCOL_VERSION_2026_07_28)
1545            .field("endpoint", &"[REDACTED]")
1546            .field("connected", &self.inner.server.get().is_some())
1547            .finish_non_exhaustive()
1548    }
1549}
1550
1551struct RpcExchange {
1552    result: Value,
1553    notifications: Vec<McpNotification>,
1554}
1555
1556enum RpcAttempt {
1557    Exchange(RpcExchange),
1558    Challenge(McpClientAuthorizationChallenge),
1559}
1560
1561fn parse_authorization_challenge(
1562    response: &reqwest::Response,
1563) -> Result<McpClientAuthorizationChallenge, StatelessMcpClientError> {
1564    let status = match response.status() {
1565        StatusCode::UNAUTHORIZED => McpClientAuthorizationChallengeStatus::Unauthorized,
1566        StatusCode::FORBIDDEN => McpClientAuthorizationChallengeStatus::Forbidden,
1567        _ => return Err(StatelessMcpClientError::Protocol),
1568    };
1569    let mut values = Vec::new();
1570    let mut total_bytes = 0usize;
1571    for value in response.headers().get_all(header::WWW_AUTHENTICATE) {
1572        if values.len() >= MAX_WWW_AUTHENTICATE_VALUES {
1573            return Err(StatelessMcpClientError::InvalidAuthorizationChallenge);
1574        }
1575        let value = value
1576            .to_str()
1577            .map_err(|_| StatelessMcpClientError::InvalidAuthorizationChallenge)?;
1578        if value.is_empty() || value.len() > MAX_WWW_AUTHENTICATE_VALUE_BYTES {
1579            return Err(StatelessMcpClientError::InvalidAuthorizationChallenge);
1580        }
1581        total_bytes = total_bytes
1582            .checked_add(value.len())
1583            .filter(|total| *total <= MAX_WWW_AUTHENTICATE_TOTAL_BYTES)
1584            .ok_or(StatelessMcpClientError::InvalidAuthorizationChallenge)?;
1585        values.push(value.to_owned().into_boxed_str());
1586    }
1587    Ok(McpClientAuthorizationChallenge {
1588        status,
1589        www_authenticate: values.into(),
1590    })
1591}
1592
1593fn challenge_error(status: McpClientAuthorizationChallengeStatus) -> StatelessMcpClientError {
1594    match status {
1595        McpClientAuthorizationChallengeStatus::Unauthorized => {
1596            StatelessMcpClientError::AuthorizationRequired
1597        }
1598        McpClientAuthorizationChallengeStatus::Forbidden => {
1599            StatelessMcpClientError::PermissionDenied
1600        }
1601    }
1602}
1603
1604fn authentication_scheme(value: &str) -> Option<&str> {
1605    let scheme = value
1606        .trim_start()
1607        .split_once(char::is_whitespace)
1608        .map_or_else(|| value.trim(), |(scheme, _)| scheme);
1609    if scheme.eq_ignore_ascii_case("bearer") {
1610        Some("bearer")
1611    } else {
1612        None
1613    }
1614}
1615
1616enum ParsedMessage {
1617    Result(Value),
1618    Remote(McpRemoteError),
1619    Notification(McpNotification),
1620}
1621
1622fn allocate_monotonic_id(counter: &AtomicU64) -> Option<u64> {
1623    counter
1624        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
1625            value.checked_add(1)
1626        })
1627        .ok()
1628}
1629
1630async fn wait_until<T, F>(
1631    deadline: tokio::time::Instant,
1632    future: F,
1633) -> Result<T, StatelessMcpClientError>
1634where
1635    F: std::future::Future<Output = T>,
1636{
1637    tokio::time::timeout_at(deadline, future)
1638        .await
1639        .map_err(|_| StatelessMcpClientError::Timeout)
1640}
1641
1642fn normalize_content_type(value: &str) -> Option<&'static str> {
1643    let mime = value.split(';').next()?.trim();
1644    if mime.eq_ignore_ascii_case(MCP_JSON) {
1645        Some(MCP_JSON)
1646    } else if mime.eq_ignore_ascii_case(MCP_EVENT_STREAM) {
1647        Some(MCP_EVENT_STREAM)
1648    } else {
1649        None
1650    }
1651}
1652
1653async fn bounded_body(
1654    response: reqwest::Response,
1655    maximum: usize,
1656) -> Result<Vec<u8>, StatelessMcpClientError> {
1657    if response
1658        .content_length()
1659        .is_some_and(|length| length > maximum as u64)
1660    {
1661        return Err(StatelessMcpClientError::ResponseTooLarge);
1662    }
1663    let mut output = Vec::new();
1664    let mut stream = response.bytes_stream();
1665    while let Some(chunk) = stream.next().await {
1666        let chunk = chunk.map_err(|_| StatelessMcpClientError::Transport)?;
1667        if output.len().saturating_add(chunk.len()) > maximum {
1668            return Err(StatelessMcpClientError::ResponseTooLarge);
1669        }
1670        output.extend_from_slice(&chunk);
1671    }
1672    Ok(output)
1673}
1674
1675fn map_sse_error(_error: SseDecodeError) -> StatelessMcpClientError {
1676    StatelessMcpClientError::InvalidEventStream
1677}
1678
1679fn consume_sse_events(
1680    events: Vec<crate::sse::SseEvent>,
1681    id: u64,
1682    notifications: &mut Vec<McpNotification>,
1683    maximum_notifications: usize,
1684) -> Result<Option<Value>, StatelessMcpClientError> {
1685    for event in events {
1686        let value = serde_json::from_str::<Value>(&event.data)
1687            .map_err(|_| StatelessMcpClientError::Protocol)?;
1688        match classify_rpc_message(value, id)? {
1689            ParsedMessage::Result(result) => return Ok(Some(result)),
1690            ParsedMessage::Remote(error) => {
1691                return Err(StatelessMcpClientError::Remote(error));
1692            }
1693            ParsedMessage::Notification(notification) => {
1694                if notifications.len() >= maximum_notifications {
1695                    return Err(StatelessMcpClientError::TooManyNotifications);
1696                }
1697                notifications.push(notification);
1698            }
1699        }
1700    }
1701    Ok(None)
1702}
1703
1704fn classify_rpc_message(
1705    value: Value,
1706    expected_id: u64,
1707) -> Result<ParsedMessage, StatelessMcpClientError> {
1708    let object = value.as_object().ok_or(StatelessMcpClientError::Protocol)?;
1709    if object.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
1710        return Err(StatelessMcpClientError::Protocol);
1711    }
1712    if let Some(method) = object.get("method").and_then(Value::as_str) {
1713        if object.contains_key("id")
1714            || object.contains_key("result")
1715            || object.contains_key("error")
1716        {
1717            return Err(StatelessMcpClientError::Protocol);
1718        }
1719        return Ok(ParsedMessage::Notification(McpNotification {
1720            method: method.to_owned().into_boxed_str(),
1721            params: object.get("params").cloned(),
1722            raw: value,
1723        }));
1724    }
1725    if object.get("id") != Some(&Value::from(expected_id)) {
1726        return Err(StatelessMcpClientError::Protocol);
1727    }
1728    match (object.get("result"), object.get("error")) {
1729        (Some(result), None) => Ok(ParsedMessage::Result(result.clone())),
1730        (None, Some(error)) => Ok(ParsedMessage::Remote(parse_remote_error(error)?)),
1731        _ => Err(StatelessMcpClientError::Protocol),
1732    }
1733}
1734
1735fn parse_remote_error(value: &Value) -> Result<McpRemoteError, StatelessMcpClientError> {
1736    let object = value.as_object().ok_or(StatelessMcpClientError::Protocol)?;
1737    let code = object
1738        .get("code")
1739        .and_then(Value::as_i64)
1740        .and_then(|value| i32::try_from(value).ok())
1741        .ok_or(StatelessMcpClientError::Protocol)?;
1742    let message = object
1743        .get("message")
1744        .and_then(Value::as_str)
1745        .ok_or(StatelessMcpClientError::Protocol)?;
1746    if message.len() > MAX_REMOTE_ERROR_MESSAGE_BYTES {
1747        return Err(StatelessMcpClientError::Protocol);
1748    }
1749    Ok(McpRemoteError {
1750        code,
1751        message: message.to_owned().into_boxed_str(),
1752        data: object.get("data").cloned(),
1753    })
1754}
1755
1756fn remote_supports_current_version(error: &McpRemoteError) -> bool {
1757    error
1758        .data()
1759        .and_then(Value::as_object)
1760        .and_then(|data| data.get("supported"))
1761        .and_then(Value::as_array)
1762        .is_some_and(|versions| {
1763            versions
1764                .iter()
1765                .any(|version| version.as_str() == Some(MCP_PROTOCOL_VERSION_2026_07_28))
1766        })
1767}
1768
1769fn parse_discovery(value: &Value) -> Result<McpClientServer, StatelessMcpClientError> {
1770    let object = value
1771        .as_object()
1772        .ok_or(StatelessMcpClientError::InvalidDiscovery)?;
1773    validate_complete_result_type(object, StatelessMcpClientError::InvalidDiscovery)?;
1774    let versions = object
1775        .get("supportedVersions")
1776        .and_then(Value::as_array)
1777        .ok_or(StatelessMcpClientError::InvalidDiscovery)?;
1778    if versions.is_empty() || versions.len() > MAX_PROTOCOL_VERSIONS {
1779        return Err(StatelessMcpClientError::InvalidDiscovery);
1780    }
1781    let mut supported_versions = Vec::with_capacity(versions.len());
1782    let mut unique_versions = HashSet::new();
1783    for version in versions {
1784        let version = version
1785            .as_str()
1786            .filter(|value| !value.is_empty() && value.len() <= MAX_PROTOCOL_VERSION_BYTES)
1787            .ok_or(StatelessMcpClientError::InvalidDiscovery)?;
1788        if !unique_versions.insert(version) {
1789            return Err(StatelessMcpClientError::InvalidDiscovery);
1790        }
1791        supported_versions.push(version.to_owned().into_boxed_str());
1792    }
1793    let capabilities = object
1794        .get("capabilities")
1795        .and_then(Value::as_object)
1796        .cloned()
1797        .ok_or(StatelessMcpClientError::InvalidDiscovery)?;
1798    let server_info = object
1799        .get("_meta")
1800        .and_then(Value::as_object)
1801        .and_then(|metadata| metadata.get(MCP_META_SERVER_INFO))
1802        .or_else(|| object.get("serverInfo"));
1803    let (name, version) = match server_info {
1804        Some(value) => {
1805            let implementation = value
1806                .as_object()
1807                .ok_or(StatelessMcpClientError::InvalidDiscovery)?;
1808            let name =
1809                bounded_optional_string(implementation.get("name"), MAX_IDENTITY_COMPONENT_BYTES)
1810                    .map_err(|_| StatelessMcpClientError::InvalidDiscovery)?;
1811            let version = bounded_optional_string(
1812                implementation.get("version"),
1813                MAX_IDENTITY_COMPONENT_BYTES,
1814            )
1815            .map_err(|_| StatelessMcpClientError::InvalidDiscovery)?;
1816            (name, version)
1817        }
1818        None => (None, None),
1819    };
1820    let instructions = bounded_optional_string(object.get("instructions"), 64 * 1024)
1821        .map_err(|_| StatelessMcpClientError::InvalidDiscovery)?;
1822    Ok(McpClientServer {
1823        supported_versions: supported_versions.into(),
1824        capabilities: Arc::new(capabilities),
1825        name,
1826        version,
1827        instructions,
1828        cache: parse_cache_policy(object).map_err(|_| StatelessMcpClientError::InvalidDiscovery)?,
1829    })
1830}
1831
1832fn bounded_optional_string(
1833    value: Option<&Value>,
1834    maximum_bytes: usize,
1835) -> Result<Option<Box<str>>, StatelessMcpClientError> {
1836    let Some(value) = value else {
1837        return Ok(None);
1838    };
1839    let value = value
1840        .as_str()
1841        .filter(|text| text.len() <= maximum_bytes)
1842        .ok_or(StatelessMcpClientError::Protocol)?;
1843    Ok(Some(value.to_owned().into_boxed_str()))
1844}
1845
1846fn parse_cache_policy(
1847    object: &Map<String, Value>,
1848) -> Result<McpCachePolicy, StatelessMcpClientError> {
1849    let ttl_ms = match object.get("ttlMs") {
1850        Some(value) => Some(value.as_u64().ok_or(StatelessMcpClientError::Protocol)?),
1851        None => None,
1852    };
1853    let scope = bounded_optional_string(object.get("cacheScope"), 64)?;
1854    Ok(McpCachePolicy { ttl_ms, scope })
1855}
1856
1857fn validate_complete_result_type(
1858    object: &Map<String, Value>,
1859    error: StatelessMcpClientError,
1860) -> Result<(), StatelessMcpClientError> {
1861    if object
1862        .get("resultType")
1863        .is_some_and(|value| value.as_str() != Some("complete"))
1864    {
1865        Err(error)
1866    } else {
1867        Ok(())
1868    }
1869}
1870
1871fn parse_tool_page(value: &Value, binding_id: u64) -> Result<McpToolPage, StatelessMcpClientError> {
1872    let object = value
1873        .as_object()
1874        .ok_or(StatelessMcpClientError::InvalidToolCatalog)?;
1875    validate_complete_result_type(object, StatelessMcpClientError::InvalidToolCatalog)?;
1876    let advertised = object
1877        .get("tools")
1878        .and_then(Value::as_array)
1879        .ok_or(StatelessMcpClientError::InvalidToolCatalog)?;
1880    let advertised_count = advertised.len();
1881    let mut tools = Vec::with_capacity(advertised_count);
1882    let mut rejected = Vec::new();
1883    for descriptor in advertised {
1884        match parse_tool(descriptor, binding_id) {
1885            Ok(tool) => tools.push(tool),
1886            Err((name, reason)) => rejected.push(McpRejectedTool { name, reason }),
1887        }
1888    }
1889    let next_cursor = match object.get("nextCursor") {
1890        Some(value) => {
1891            let value = value
1892                .as_str()
1893                .filter(|value| !value.is_empty() && value.len() <= MAX_CURSOR_BYTES)
1894                .ok_or(StatelessMcpClientError::InvalidPagination)?;
1895            Some(value.to_owned().into_boxed_str())
1896        }
1897        None => None,
1898    };
1899    let cache =
1900        parse_cache_policy(object).map_err(|_| StatelessMcpClientError::InvalidToolCatalog)?;
1901    Ok(McpToolPage {
1902        tools,
1903        rejected,
1904        next_cursor,
1905        cache,
1906        advertised_count,
1907    })
1908}
1909
1910fn parse_tool(
1911    descriptor: &Value,
1912    binding_id: u64,
1913) -> Result<McpTool, (Option<Box<str>>, McpToolRejectionReason)> {
1914    let Some(object) = descriptor.as_object() else {
1915        return Err((None, McpToolRejectionReason::DescriptorNotObject));
1916    };
1917    let rejected_name = object
1918        .get("name")
1919        .and_then(Value::as_str)
1920        .filter(|name| !name.is_empty() && name.len() <= MAX_TOOL_NAME_BYTES)
1921        .map(|name| name.to_owned().into_boxed_str());
1922    let name = rejected_name
1923        .as_deref()
1924        .ok_or((None, McpToolRejectionReason::InvalidName))?;
1925    let input_schema = object
1926        .get("inputSchema")
1927        .filter(|schema| schema.is_object())
1928        .ok_or_else(|| {
1929            (
1930                rejected_name.clone(),
1931                McpToolRejectionReason::InvalidInputSchema,
1932            )
1933        })?;
1934    let output_schema = match object.get("outputSchema") {
1935        Some(schema) if schema.is_object() => Some(Arc::new(schema.clone())),
1936        Some(_) => {
1937            return Err((rejected_name, McpToolRejectionReason::InvalidOutputSchema));
1938        }
1939        None => None,
1940    };
1941    let headers =
1942        collect_header_bindings(input_schema).map_err(|reason| (rejected_name.clone(), reason))?;
1943    Ok(McpTool {
1944        binding_id,
1945        name: name.to_owned().into_boxed_str(),
1946        title: optional_descriptor_text(object.get("title")),
1947        description: optional_descriptor_text(object.get("description")),
1948        input_schema: Arc::new(input_schema.clone()),
1949        output_schema,
1950        raw: Arc::new(descriptor.clone()),
1951        headers: headers.into(),
1952    })
1953}
1954
1955fn optional_descriptor_text(value: Option<&Value>) -> Option<Box<str>> {
1956    value
1957        .and_then(Value::as_str)
1958        .filter(|text| text.len() <= 64 * 1024)
1959        .map(|text| text.to_owned().into_boxed_str())
1960}
1961
1962fn collect_header_bindings(
1963    input_schema: &Value,
1964) -> Result<Vec<HeaderBinding>, McpToolRejectionReason> {
1965    let mut output = Vec::new();
1966    let mut seen = HashSet::new();
1967    scan_header_schema(input_schema, false, &mut Vec::new(), &mut seen, &mut output)?;
1968    Ok(output)
1969}
1970
1971fn scan_header_schema(
1972    schema: &Value,
1973    annotation_allowed: bool,
1974    path: &mut Vec<Box<str>>,
1975    seen: &mut HashSet<String>,
1976    output: &mut Vec<HeaderBinding>,
1977) -> Result<(), McpToolRejectionReason> {
1978    let Some(object) = schema.as_object() else {
1979        if contains_header_annotation(schema) {
1980            return Err(McpToolRejectionReason::HeaderNotStaticallyReachable);
1981        }
1982        return Ok(());
1983    };
1984    if let Some(annotation) = object.get("x-mcp-header") {
1985        if !annotation_allowed {
1986            return Err(McpToolRejectionReason::HeaderNotStaticallyReachable);
1987        }
1988        let name = annotation
1989            .as_str()
1990            .ok_or(McpToolRejectionReason::HeaderNameNotString)?;
1991        if name.is_empty() || !name.chars().all(is_http_token_character) {
1992            return Err(McpToolRejectionReason::InvalidHeaderName);
1993        }
1994        if !seen.insert(name.to_ascii_lowercase()) {
1995            return Err(McpToolRejectionReason::DuplicateHeaderName);
1996        }
1997        let kind = match object.get("type").and_then(Value::as_str) {
1998            Some("string") => HeaderValueKind::String,
1999            Some("integer") => HeaderValueKind::Integer,
2000            Some("boolean") => HeaderValueKind::Boolean,
2001            _ => return Err(McpToolRejectionReason::HeaderOnNonPrimitive),
2002        };
2003        output.push(HeaderBinding {
2004            path: path.clone().into(),
2005            name: name.to_owned().into_boxed_str(),
2006            kind,
2007        });
2008    }
2009
2010    for (keyword, child) in object {
2011        if keyword == "properties" {
2012            if let Some(properties) = child.as_object() {
2013                for (property, property_schema) in properties {
2014                    path.push(property.to_owned().into_boxed_str());
2015                    scan_header_schema(property_schema, true, path, seen, output)?;
2016                    path.pop();
2017                }
2018            } else if contains_header_annotation(child) {
2019                return Err(McpToolRejectionReason::HeaderNotStaticallyReachable);
2020            }
2021        } else if keyword != "x-mcp-header" && contains_header_annotation(child) {
2022            return Err(McpToolRejectionReason::HeaderNotStaticallyReachable);
2023        }
2024    }
2025    Ok(())
2026}
2027
2028fn contains_header_annotation(value: &Value) -> bool {
2029    match value {
2030        Value::Object(object) => {
2031            object.contains_key("x-mcp-header") || object.values().any(contains_header_annotation)
2032        }
2033        Value::Array(values) => values.iter().any(contains_header_annotation),
2034        _ => false,
2035    }
2036}
2037
2038const fn is_http_token_character(character: char) -> bool {
2039    character.is_ascii_alphanumeric()
2040        || matches!(
2041            character,
2042            '!' | '#'
2043                | '$'
2044                | '%'
2045                | '&'
2046                | '\''
2047                | '*'
2048                | '+'
2049                | '-'
2050                | '.'
2051                | '^'
2052                | '_'
2053                | '`'
2054                | '|'
2055                | '~'
2056        )
2057}
2058
2059fn promoted_headers(
2060    tool: &McpTool,
2061    arguments: &Map<String, Value>,
2062) -> Result<Vec<(HeaderName, HeaderValue)>, StatelessMcpClientError> {
2063    let mut output = Vec::with_capacity(tool.headers.len());
2064    for binding in tool.headers.iter() {
2065        let Some(value) = value_at_path(arguments, &binding.path) else {
2066            continue;
2067        };
2068        if value.is_null() {
2069            continue;
2070        }
2071        let value = match binding.kind {
2072            HeaderValueKind::String => value
2073                .as_str()
2074                .map(ToOwned::to_owned)
2075                .ok_or(StatelessMcpClientError::InvalidHeaderArgument)?,
2076            HeaderValueKind::Boolean => value
2077                .as_bool()
2078                .map(|value| value.to_string())
2079                .ok_or(StatelessMcpClientError::InvalidHeaderArgument)?,
2080            HeaderValueKind::Integer => {
2081                safe_integer_string(value).ok_or(StatelessMcpClientError::InvalidHeaderArgument)?
2082            }
2083        };
2084        let name = format!("{MCP_HEADER_PARAMETER_PREFIX}{}", binding.name);
2085        let name = HeaderName::from_bytes(name.as_bytes())
2086            .map_err(|_| StatelessMcpClientError::InvalidHeaderArgument)?;
2087        let value = HeaderValue::from_str(&encode_header_value(&value))
2088            .map_err(|_| StatelessMcpClientError::InvalidHeaderArgument)?;
2089        output.push((name, value));
2090    }
2091    Ok(output)
2092}
2093
2094fn value_at_path<'a>(arguments: &'a Map<String, Value>, path: &[Box<str>]) -> Option<&'a Value> {
2095    let (first, remaining) = path.split_first()?;
2096    let mut current = arguments.get(first.as_ref())?;
2097    for component in remaining {
2098        current = current.as_object()?.get(component.as_ref())?;
2099    }
2100    Some(current)
2101}
2102
2103fn safe_integer_string(value: &Value) -> Option<String> {
2104    const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
2105    if let Some(value) = value.as_i64() {
2106        return (value.unsigned_abs() <= MAX_SAFE_INTEGER.unsigned_abs())
2107            .then(|| value.to_string());
2108    }
2109    if let Some(value) = value.as_u64() {
2110        return (value <= MAX_SAFE_INTEGER as u64).then(|| value.to_string());
2111    }
2112    let value = value.as_f64()?;
2113    if !value.is_finite() || value.fract() != 0.0 || value.abs() > 9_007_199_254_740_991.0 {
2114        return None;
2115    }
2116    Some(format!("{value:.0}"))
2117}
2118
2119fn encode_header_value(value: &str) -> String {
2120    if requires_base64(value) {
2121        format!(
2122            "{BASE64_PREFIX}{}{BASE64_SUFFIX}",
2123            BASE64_STANDARD.encode(value.as_bytes())
2124        )
2125    } else {
2126        value.to_owned()
2127    }
2128}
2129
2130fn requires_base64(value: &str) -> bool {
2131    if value.is_empty() {
2132        return false;
2133    }
2134    let bytes = value.as_bytes();
2135    matches!(bytes.first(), Some(b' ' | b'\t'))
2136        || matches!(bytes.last(), Some(b' ' | b'\t'))
2137        || bytes.iter().any(|byte| !(0x20..=0x7e).contains(byte))
2138        || (value.starts_with(BASE64_PREFIX) && value.ends_with(BASE64_SUFFIX))
2139}
2140
2141fn parse_tool_result(
2142    value: Value,
2143    client: McpClient,
2144    tool: McpTool,
2145    arguments: Map<String, Value>,
2146) -> Result<McpToolCall, StatelessMcpClientError> {
2147    let object = value
2148        .as_object()
2149        .ok_or(StatelessMcpClientError::InvalidToolResult)?;
2150    let result_type = match object.get("resultType") {
2151        Some(value) => Some(
2152            value
2153                .as_str()
2154                .ok_or(StatelessMcpClientError::InvalidToolResult)?,
2155        ),
2156        None => None,
2157    };
2158    match result_type {
2159        None | Some("complete") => {
2160            let content = object
2161                .get("content")
2162                .and_then(Value::as_array)
2163                .cloned()
2164                .ok_or(StatelessMcpClientError::InvalidToolResult)?;
2165            let is_error = match object.get("isError") {
2166                Some(value) => value
2167                    .as_bool()
2168                    .ok_or(StatelessMcpClientError::InvalidToolResult)?,
2169                None => false,
2170            };
2171            Ok(McpToolCall::Complete(McpCompleteToolResult {
2172                content,
2173                structured_content: object.get("structuredContent").cloned(),
2174                is_error,
2175                raw: value,
2176            }))
2177        }
2178        Some("input_required") => {
2179            let input_requests = match object.get("inputRequests") {
2180                Some(value) => value
2181                    .as_object()
2182                    .cloned()
2183                    .ok_or(StatelessMcpClientError::InvalidToolResult)?,
2184                None => Map::new(),
2185            };
2186            for (key, request) in &input_requests {
2187                let request = request
2188                    .as_object()
2189                    .ok_or(StatelessMcpClientError::InvalidToolResult)?;
2190                if key.is_empty()
2191                    || key.len() > 1024
2192                    || !matches!(
2193                        request.get("method").and_then(Value::as_str),
2194                        Some("elicitation/create" | "sampling/createMessage" | "roots/list")
2195                    )
2196                {
2197                    return Err(StatelessMcpClientError::InvalidToolResult);
2198                }
2199            }
2200            let request_state = match object.get("requestState") {
2201                Some(value) => Some(
2202                    value
2203                        .as_str()
2204                        .ok_or(StatelessMcpClientError::InvalidToolResult)?
2205                        .to_owned()
2206                        .into_boxed_str(),
2207                ),
2208                None => None,
2209            };
2210            Ok(McpToolCall::InputRequired(McpInputRequired {
2211                client,
2212                tool,
2213                arguments,
2214                input_requests,
2215                request_state,
2216            }))
2217        }
2218        Some(_) => Err(StatelessMcpClientError::InvalidToolResult),
2219    }
2220}
2221
2222#[cfg(test)]
2223mod tests {
2224    use std::collections::HashMap;
2225
2226    use super::*;
2227
2228    #[test]
2229    fn identity_and_options_are_bounded() {
2230        assert!(McpClientIdentity::new("stateknot", "0.0.0").is_ok());
2231        assert_eq!(
2232            McpClientIdentity::new(" stateknot", "0.0.0"),
2233            Err(McpClientIdentityError::BoundaryWhitespace)
2234        );
2235        assert_eq!(
2236            McpClientOptions::new(ProviderHttpOptions::default(), Duration::ZERO, 1, 1, 1, 1,),
2237            Err(McpClientOptionsError::ZeroTimeout)
2238        );
2239        assert_eq!(
2240            McpClientOptions::new(
2241                ProviderHttpOptions::default(),
2242                Duration::from_secs(24 * 60 * 60 + 1),
2243                1,
2244                1,
2245                1,
2246                1,
2247            ),
2248            Err(McpClientOptionsError::AboveHardMaximum)
2249        );
2250    }
2251
2252    #[test]
2253    fn nested_headers_are_validated_and_encoded_without_schema_fetches() {
2254        let descriptor = json!({
2255            "name": "deploy",
2256            "inputSchema": {
2257                "type": "object",
2258                "$defs": {
2259                    "remote": { "$ref": "https://canary.invalid/schema.json" }
2260                },
2261                "properties": {
2262                    "region": { "type": "string", "x-mcp-header": "Region" },
2263                    "options": {
2264                        "type": "object",
2265                        "properties": {
2266                            "priority": { "type": "integer", "x-mcp-header": "Priority" },
2267                            "confirm": { "type": "boolean", "x-mcp-header": "Confirm" },
2268                            "note": { "type": "string", "x-mcp-header": "Note" }
2269                        }
2270                    }
2271                }
2272            }
2273        });
2274        let tool = parse_tool(&descriptor, 7).unwrap();
2275        let arguments = json!({
2276            "region": "us-west1",
2277            "options": {
2278                "priority": 42,
2279                "confirm": false,
2280                "note": "Hello, 世界"
2281            }
2282        });
2283        let headers = promoted_headers(&tool, arguments.as_object().unwrap()).unwrap();
2284        let headers = headers
2285            .into_iter()
2286            .map(|(name, value)| (name.as_str().to_owned(), value.to_str().unwrap().to_owned()))
2287            .collect::<HashMap<_, _>>();
2288        assert_eq!(headers.get("mcp-param-region").unwrap(), "us-west1");
2289        assert_eq!(headers.get("mcp-param-priority").unwrap(), "42");
2290        assert_eq!(headers.get("mcp-param-confirm").unwrap(), "false");
2291        assert_eq!(
2292            headers.get("mcp-param-note").unwrap(),
2293            "=?base64?SGVsbG8sIOS4lueVjA==?="
2294        );
2295    }
2296
2297    #[test]
2298    fn invalid_or_unreachable_header_annotations_exclude_only_that_tool() {
2299        let duplicate = json!({
2300            "name": "duplicate",
2301            "inputSchema": {
2302                "type": "object",
2303                "properties": {
2304                    "a": { "type": "string", "x-mcp-header": "Region" },
2305                    "b": { "type": "string", "x-mcp-header": "region" }
2306                }
2307            }
2308        });
2309        assert_eq!(
2310            parse_tool(&duplicate, 1).unwrap_err().1,
2311            McpToolRejectionReason::DuplicateHeaderName
2312        );
2313
2314        let through_ref = json!({
2315            "name": "through-ref",
2316            "inputSchema": {
2317                "type": "object",
2318                "$defs": {
2319                    "tenant": { "type": "string", "x-mcp-header": "Tenant" }
2320                },
2321                "properties": { "tenant": { "$ref": "#/$defs/tenant" } }
2322            }
2323        });
2324        assert_eq!(
2325            parse_tool(&through_ref, 1).unwrap_err().1,
2326            McpToolRejectionReason::HeaderNotStaticallyReachable
2327        );
2328
2329        let malformed_properties = json!({
2330            "name": "malformed-properties",
2331            "inputSchema": {
2332                "type": "object",
2333                "properties": [{
2334                    "type": "string",
2335                    "x-mcp-header": "Tenant"
2336                }]
2337            }
2338        });
2339        assert_eq!(
2340            parse_tool(&malformed_properties, 1).unwrap_err().1,
2341            McpToolRejectionReason::HeaderNotStaticallyReachable
2342        );
2343
2344        let number = json!({
2345            "name": "number",
2346            "inputSchema": {
2347                "type": "object",
2348                "properties": {
2349                    "ratio": { "type": "number", "x-mcp-header": "Ratio" }
2350                }
2351            }
2352        });
2353        assert_eq!(
2354            parse_tool(&number, 1).unwrap_err().1,
2355            McpToolRejectionReason::HeaderOnNonPrimitive
2356        );
2357    }
2358
2359    #[test]
2360    fn parses_modern_discovery_and_matching_json_rpc() {
2361        let server = parse_discovery(&json!({
2362            "resultType": "complete",
2363            "supportedVersions": [MCP_PROTOCOL_VERSION_2026_07_28],
2364            "capabilities": { "tools": {} },
2365            "_meta": {
2366                (MCP_META_SERVER_INFO): { "name": "example", "version": "1.0.0" }
2367            },
2368            "ttlMs": 1000,
2369            "cacheScope": "private"
2370        }))
2371        .unwrap();
2372        assert_eq!(server.name(), Some("example"));
2373        assert_eq!(server.cache().ttl_ms(), Some(1000));
2374        assert!(server.supports_tools());
2375
2376        assert!(matches!(
2377            classify_rpc_message(
2378                json!({ "jsonrpc": "2.0", "id": 9, "result": { "ok": true } }),
2379                9,
2380            )
2381            .unwrap(),
2382            ParsedMessage::Result(_)
2383        ));
2384        assert!(
2385            classify_rpc_message(json!({ "jsonrpc": "2.0", "id": 8, "result": {} }), 9,).is_err()
2386        );
2387    }
2388
2389    #[test]
2390    fn unsafe_header_values_and_sentinel_are_base64_encoded() {
2391        assert_eq!(encode_header_value("plain value"), "plain value");
2392        assert_eq!(encode_header_value(""), "");
2393        assert_eq!(encode_header_value(" padded "), "=?base64?IHBhZGRlZCA=?=");
2394        assert_eq!(
2395            encode_header_value("=?base64?literal?="),
2396            "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?="
2397        );
2398        assert_eq!(safe_integer_string(&Value::from(i64::MIN)), None);
2399    }
2400}