Skip to main content

stateknot_integrations/
mcp_server.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Production Streamable HTTP boundary for MCP 2026-07-28 servers.
5//!
6//! The official Rust SDK owns JSON-RPC and protocol serialization. This module
7//! owns the deployment invariants that an application must not have to rebuild:
8//! one stateless protocol revision, strict Host and Origin allowlists, bounded
9//! bodies and execution, overload rejection, redacted bearer authentication,
10//! caller-provided admission control, request-principal propagation, and
11//! cooperative shutdown.
12
13use std::{
14    convert::Infallible,
15    fmt,
16    sync::Arc,
17    task::{Context, Poll},
18    time::Duration,
19};
20
21use bytes::Bytes;
22use http::{
23    HeaderValue, Request, Response, StatusCode,
24    header::{AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, PRAGMA, RETRY_AFTER, WWW_AUTHENTICATE},
25    request::Parts,
26    uri::Authority,
27};
28use http_body::Body;
29use http_body_util::{BodyExt as _, Full, combinators::BoxBody};
30use rmcp::{
31    RoleServer, ServerHandler,
32    model::ProtocolVersion,
33    service::RequestContext,
34    transport::{
35        StreamableHttpServerConfig, StreamableHttpService,
36        streamable_http_server::session::never::NeverSessionManager,
37    },
38};
39use stateknot_core::BoxFuture;
40use thiserror::Error;
41use tokio::sync::Semaphore;
42use tokio_util::sync::CancellationToken;
43use tower_service::Service;
44use zeroize::Zeroizing;
45
46const MCP_METHOD_HEADER: &str = "mcp-method";
47const MCP_NAME_HEADER: &str = "mcp-name";
48const MAX_HINT_BYTES: usize = 1024;
49
50type McpHttpResponse = Response<BoxBody<Bytes, Infallible>>;
51
52/// An inbound RFC 6750 bearer credential.
53///
54/// The value is zeroized on final drop and its `Debug` representation is
55/// always redacted. An authenticator must call [`Self::expose_secret`] only for
56/// verification and must not retain, log, or return the plaintext value.
57#[derive(Clone)]
58pub struct McpServerBearerCredential(Zeroizing<String>);
59
60impl McpServerBearerCredential {
61    /// Maximum accepted credential length in bytes.
62    pub const MAX_BYTES: usize = 8192;
63
64    /// Validates an RFC 6750 `b64token` value.
65    pub fn new(value: impl Into<String>) -> Result<Self, McpServerBearerCredentialError> {
66        let value = Zeroizing::new(value.into());
67        if value.is_empty() {
68            return Err(McpServerBearerCredentialError::Empty);
69        }
70        if value.len() > Self::MAX_BYTES {
71            return Err(McpServerBearerCredentialError::TooLong);
72        }
73
74        let mut padding = false;
75        for byte in value.bytes() {
76            if byte == b'=' {
77                padding = true;
78                continue;
79            }
80            if padding || !is_b64_token_byte(byte) {
81                return Err(McpServerBearerCredentialError::InvalidSyntax);
82            }
83        }
84        Ok(Self(value))
85    }
86
87    /// Borrows the credential for immediate verification.
88    #[must_use]
89    pub fn expose_secret(&self) -> &str {
90        self.0.as_str()
91    }
92}
93
94impl fmt::Debug for McpServerBearerCredential {
95    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
96        formatter.write_str("McpServerBearerCredential([REDACTED])")
97    }
98}
99
100fn is_b64_token_byte(byte: u8) -> bool {
101    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'+' | b'/')
102}
103
104/// Invalid inbound bearer credential syntax.
105#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
106#[non_exhaustive]
107pub enum McpServerBearerCredentialError {
108    /// No credential was supplied after the scheme.
109    #[error("MCP bearer credential is empty")]
110    Empty,
111    /// The credential exceeded the hard byte ceiling.
112    #[error("MCP bearer credential is too long")]
113    TooLong,
114    /// The credential is not an RFC 6750 `b64token`.
115    #[error("MCP bearer credential has invalid syntax")]
116    InvalidSyntax,
117}
118
119/// Authenticated identity injected into an MCP request context.
120#[derive(Clone, Debug, Eq, PartialEq)]
121pub struct McpServerPrincipal {
122    subject: Arc<str>,
123    scopes: Arc<[Box<str>]>,
124}
125
126impl McpServerPrincipal {
127    /// Maximum subject length in bytes.
128    pub const MAX_SUBJECT_BYTES: usize = 512;
129    /// Maximum number of normalized scopes.
130    pub const MAX_SCOPES: usize = 128;
131    /// Maximum scope length in bytes.
132    pub const MAX_SCOPE_BYTES: usize = 256;
133
134    /// Constructs a bounded principal and canonicalizes scopes by ASCII order.
135    pub fn new(
136        subject: impl Into<String>,
137        scopes: impl IntoIterator<Item = impl Into<String>>,
138    ) -> Result<Self, McpServerPrincipalError> {
139        let subject = subject.into();
140        validate_display_value(&subject, Self::MAX_SUBJECT_BYTES)
141            .map_err(|_| McpServerPrincipalError::InvalidSubject)?;
142
143        let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
144        if scopes.len() > Self::MAX_SCOPES {
145            return Err(McpServerPrincipalError::TooManyScopes);
146        }
147        for scope in &scopes {
148            validate_scope(scope)?;
149        }
150        scopes.sort_unstable();
151        if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
152            return Err(McpServerPrincipalError::DuplicateScope);
153        }
154
155        Ok(Self {
156            subject: Arc::from(subject),
157            scopes: scopes
158                .into_iter()
159                .map(String::into_boxed_str)
160                .collect::<Vec<_>>()
161                .into(),
162        })
163    }
164
165    fn anonymous() -> Self {
166        Self {
167            subject: Arc::from("anonymous"),
168            scopes: Arc::from([]),
169        }
170    }
171
172    /// Returns the stable subject identifier.
173    #[must_use]
174    pub fn subject(&self) -> &str {
175        &self.subject
176    }
177
178    /// Returns canonical scopes in exact ASCII order.
179    pub fn scopes(&self) -> impl ExactSizeIterator<Item = &str> {
180        self.scopes.iter().map(AsRef::as_ref)
181    }
182
183    /// Returns whether the exact scope was granted.
184    #[must_use]
185    pub fn has_scope(&self, scope: &str) -> bool {
186        self.scopes
187            .binary_search_by(|candidate| candidate.as_ref().cmp(scope))
188            .is_ok()
189    }
190}
191
192/// Invalid authenticated principal.
193#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
194#[non_exhaustive]
195pub enum McpServerPrincipalError {
196    /// The subject is empty, padded, oversized, or contains a control character.
197    #[error("invalid MCP principal subject")]
198    InvalidSubject,
199    /// More than the hard scope ceiling was supplied.
200    #[error("too many MCP principal scopes")]
201    TooManyScopes,
202    /// A scope is empty, oversized, or outside the OAuth scope-token grammar.
203    #[error("invalid MCP principal scope")]
204    InvalidScope,
205    /// A scope appeared more than once.
206    #[error("duplicate MCP principal scope")]
207    DuplicateScope,
208}
209
210fn validate_scope(scope: &str) -> Result<(), McpServerPrincipalError> {
211    if scope.is_empty()
212        || scope.len() > McpServerPrincipal::MAX_SCOPE_BYTES
213        || scope
214            .bytes()
215            .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
216    {
217        return Err(McpServerPrincipalError::InvalidScope);
218    }
219    Ok(())
220}
221
222#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
223enum McpServerTextError {
224    #[error("value is empty")]
225    Empty,
226    #[error("value is too long")]
227    TooLong,
228    #[error("value has boundary whitespace")]
229    BoundaryWhitespace,
230    #[error("value contains a control character")]
231    ControlCharacter,
232}
233
234fn validate_display_value(value: &str, maximum: usize) -> Result<(), McpServerTextError> {
235    if value.is_empty() {
236        return Err(McpServerTextError::Empty);
237    }
238    if value.len() > maximum {
239        return Err(McpServerTextError::TooLong);
240    }
241    if value.trim() != value {
242        return Err(McpServerTextError::BoundaryWhitespace);
243    }
244    if value.chars().any(char::is_control) {
245        return Err(McpServerTextError::ControlCharacter);
246    }
247    Ok(())
248}
249
250/// Public-safe facts passed to a bearer authenticator.
251#[derive(Debug)]
252pub struct McpServerAuthenticationRequest {
253    credential: McpServerBearerCredential,
254    transport_method_hint: Option<Box<str>>,
255    transport_name_hint: Option<Box<str>>,
256}
257
258impl McpServerAuthenticationRequest {
259    /// Returns the redacted credential container.
260    #[must_use]
261    pub const fn credential(&self) -> &McpServerBearerCredential {
262        &self.credential
263    }
264
265    /// Returns the untrusted `Mcp-Method` transport hint.
266    ///
267    /// Authentication may use this for telemetry, but authorization must use
268    /// the decoded method after the transport has validated standard headers.
269    #[must_use]
270    pub fn transport_method_hint(&self) -> Option<&str> {
271        self.transport_method_hint.as_deref()
272    }
273
274    /// Returns the untrusted `Mcp-Name` transport hint.
275    #[must_use]
276    pub fn transport_name_hint(&self) -> Option<&str> {
277        self.transport_name_hint.as_deref()
278    }
279}
280
281/// Public-safe authentication failure.
282#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
283#[non_exhaustive]
284pub enum McpServerAuthenticationError {
285    /// The credential is unknown, expired, revoked, or otherwise invalid.
286    #[error("MCP bearer credential is invalid")]
287    InvalidCredential,
288    /// The authenticated identity is not permitted to access this resource.
289    #[error("MCP access is forbidden")]
290    Forbidden,
291    /// The identity provider or credential backend is temporarily unavailable.
292    #[error("MCP authentication service is unavailable")]
293    Unavailable,
294}
295
296/// Verifies one inbound bearer credential.
297pub trait McpServerAuthenticator: Send + Sync + 'static {
298    /// Authenticates the request and returns a bounded principal.
299    fn authenticate(
300        &self,
301        request: McpServerAuthenticationRequest,
302    ) -> BoxFuture<'_, Result<McpServerPrincipal, McpServerAuthenticationError>>;
303}
304
305/// A validated RFC 6750 challenge emitted without reflecting request input.
306#[derive(Clone, Debug, Eq, PartialEq)]
307pub struct McpServerBearerChallenge {
308    value: HeaderValue,
309}
310
311impl McpServerBearerChallenge {
312    /// Builds a Bearer challenge with an optional RFC 9728 resource-metadata URL.
313    pub fn new(
314        realm: impl Into<String>,
315        resource_metadata: Option<impl Into<String>>,
316    ) -> Result<Self, McpServerBearerChallengeError> {
317        let realm = realm.into();
318        validate_challenge_component(&realm)?;
319        let resource_metadata = resource_metadata.map(Into::into);
320        if let Some(value) = &resource_metadata {
321            validate_challenge_component(value)?;
322            let uri = value
323                .parse::<http::Uri>()
324                .map_err(|_| McpServerBearerChallengeError::InvalidResourceMetadata)?;
325            if !matches!(uri.scheme_str(), Some("https")) || uri.authority().is_none() {
326                return Err(McpServerBearerChallengeError::InvalidResourceMetadata);
327            }
328        }
329
330        let rendered = resource_metadata.map_or_else(
331            || format!("Bearer realm=\"{realm}\""),
332            |metadata| format!("Bearer realm=\"{realm}\", resource_metadata=\"{metadata}\""),
333        );
334        let value = HeaderValue::from_str(&rendered)
335            .map_err(|_| McpServerBearerChallengeError::InvalidHeader)?;
336        Ok(Self { value })
337    }
338}
339
340fn validate_challenge_component(value: &str) -> Result<(), McpServerBearerChallengeError> {
341    if value.is_empty()
342        || value.len() > 4096
343        || value
344            .bytes()
345            .any(|byte| !(b' '..=b'~').contains(&byte) || matches!(byte, b'"' | b'\\'))
346    {
347        return Err(McpServerBearerChallengeError::InvalidComponent);
348    }
349    Ok(())
350}
351
352/// Invalid static Bearer challenge configuration.
353#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
354#[non_exhaustive]
355pub enum McpServerBearerChallengeError {
356    /// A challenge component was empty, oversized, non-ASCII, or quote-unsafe.
357    #[error("invalid MCP Bearer challenge component")]
358    InvalidComponent,
359    /// Resource metadata must be an absolute HTTPS URL.
360    #[error("invalid MCP protected-resource metadata URL")]
361    InvalidResourceMetadata,
362    /// The complete challenge could not be represented as an HTTP header.
363    #[error("invalid MCP Bearer challenge header")]
364    InvalidHeader,
365}
366
367#[derive(Clone)]
368enum McpServerAuthenticationMode {
369    AnonymousLoopback,
370    Bearer {
371        authenticator: Arc<dyn McpServerAuthenticator>,
372        challenge: McpServerBearerChallenge,
373    },
374}
375
376/// Authentication policy for an MCP HTTP service.
377#[derive(Clone)]
378pub struct McpServerAuthentication {
379    mode: McpServerAuthenticationMode,
380}
381
382impl McpServerAuthentication {
383    /// Allows an anonymous principal only when every configured host is loopback.
384    #[must_use]
385    pub const fn anonymous_loopback() -> Self {
386        Self {
387            mode: McpServerAuthenticationMode::AnonymousLoopback,
388        }
389    }
390
391    /// Requires a Bearer credential and delegates verification.
392    #[must_use]
393    pub fn bearer<A>(authenticator: A, challenge: McpServerBearerChallenge) -> Self
394    where
395        A: McpServerAuthenticator,
396    {
397        Self::bearer_shared(Arc::new(authenticator), challenge)
398    }
399
400    /// Requires a Bearer credential using an already shared authenticator.
401    #[must_use]
402    pub fn bearer_shared(
403        authenticator: Arc<dyn McpServerAuthenticator>,
404        challenge: McpServerBearerChallenge,
405    ) -> Self {
406        Self {
407            mode: McpServerAuthenticationMode::Bearer {
408                authenticator,
409                challenge,
410            },
411        }
412    }
413}
414
415impl fmt::Debug for McpServerAuthentication {
416    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
417        match &self.mode {
418            McpServerAuthenticationMode::AnonymousLoopback => {
419                formatter.write_str("McpServerAuthentication::AnonymousLoopback")
420            }
421            McpServerAuthenticationMode::Bearer { .. } => {
422                formatter.write_str("McpServerAuthentication::Bearer([REDACTED])")
423            }
424        }
425    }
426}
427
428/// Authenticated, transport-level facts passed to admission control.
429#[derive(Clone, Debug)]
430pub struct McpServerAdmissionRequest {
431    principal: McpServerPrincipal,
432    transport_method_hint: Option<Box<str>>,
433    transport_name_hint: Option<Box<str>>,
434}
435
436impl McpServerAdmissionRequest {
437    /// Returns the authenticated principal.
438    #[must_use]
439    pub const fn principal(&self) -> &McpServerPrincipal {
440        &self.principal
441    }
442
443    /// Returns the untrusted transport method hint.
444    #[must_use]
445    pub fn transport_method_hint(&self) -> Option<&str> {
446        self.transport_method_hint.as_deref()
447    }
448
449    /// Returns the untrusted transport name hint.
450    #[must_use]
451    pub fn transport_name_hint(&self) -> Option<&str> {
452        self.transport_name_hint.as_deref()
453    }
454}
455
456/// Public-safe admission failure.
457#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
458#[non_exhaustive]
459pub enum McpServerAdmissionError {
460    /// Policy denied this authenticated request.
461    #[error("MCP request is forbidden")]
462    Forbidden,
463    /// A quota or rate limit was reached.
464    #[error("MCP request is rate limited")]
465    RateLimited {
466        /// Minimum delay before a new request should be attempted.
467        retry_after: Duration,
468    },
469    /// The policy backend is temporarily unavailable.
470    #[error("MCP admission service is unavailable")]
471    Unavailable,
472}
473
474/// Caller-owned admission boundary for shared quota and coarse request policy.
475///
476/// The built-in semaphore protects one process. Cross-replica quotas belong in
477/// this trait so production deployments can use one authoritative policy store.
478/// Tool/resource/prompt authorization must still run in the decoded handler;
479/// transport hints have not yet been validated against the JSON-RPC body.
480pub trait McpServerAdmissionControl: Send + Sync + 'static {
481    /// Admits or rejects one authenticated request.
482    fn admit(
483        &self,
484        request: McpServerAdmissionRequest,
485    ) -> BoxFuture<'_, Result<(), McpServerAdmissionError>>;
486}
487
488/// Explicit admission policy that accepts every authenticated request.
489#[derive(Clone, Copy, Debug, Default)]
490pub struct AllowMcpServerAdmission;
491
492impl McpServerAdmissionControl for AllowMcpServerAdmission {
493    fn admit(
494        &self,
495        _request: McpServerAdmissionRequest,
496    ) -> BoxFuture<'_, Result<(), McpServerAdmissionError>> {
497        Box::pin(async { Ok(()) })
498    }
499}
500
501/// Strict bounded Streamable HTTP policy.
502#[derive(Clone, Debug, Eq, PartialEq)]
503pub struct McpServerHttpOptions {
504    allowed_hosts: Arc<[Box<str>]>,
505    allowed_origins: Arc<[Box<str>]>,
506    maximum_request_body_bytes: usize,
507    maximum_concurrent_requests: usize,
508    request_timeout: Duration,
509}
510
511impl McpServerHttpOptions {
512    /// Maximum number of Host or Origin entries.
513    pub const HARD_MAXIMUM_ALLOWLIST_ENTRIES: usize = 128;
514    /// Maximum accepted request body ceiling.
515    pub const HARD_MAXIMUM_REQUEST_BODY_BYTES: usize = 64 * 1024 * 1024;
516    /// Maximum local in-flight request ceiling.
517    pub const HARD_MAXIMUM_CONCURRENT_REQUESTS: usize = 4096;
518    /// Maximum request deadline.
519    pub const HARD_MAXIMUM_REQUEST_TIMEOUT: Duration = Duration::from_secs(24 * 60 * 60);
520
521    /// Constructs an explicit public or private deployment policy.
522    pub fn new(
523        allowed_hosts: impl IntoIterator<Item = impl Into<String>>,
524        allowed_origins: impl IntoIterator<Item = impl Into<String>>,
525        maximum_request_body_bytes: usize,
526        maximum_concurrent_requests: usize,
527        request_timeout: Duration,
528    ) -> Result<Self, McpServerHttpOptionsError> {
529        let allowed_hosts = allowed_hosts
530            .into_iter()
531            .map(Into::into)
532            .collect::<Vec<_>>();
533        let allowed_origins = allowed_origins
534            .into_iter()
535            .map(Into::into)
536            .collect::<Vec<_>>();
537
538        validate_allowed_hosts(&allowed_hosts)?;
539        validate_allowed_origins(&allowed_origins)?;
540        if maximum_request_body_bytes == 0
541            || maximum_concurrent_requests == 0
542            || request_timeout.is_zero()
543        {
544            return Err(McpServerHttpOptionsError::ZeroLimit);
545        }
546        if maximum_request_body_bytes > Self::HARD_MAXIMUM_REQUEST_BODY_BYTES
547            || maximum_concurrent_requests > Self::HARD_MAXIMUM_CONCURRENT_REQUESTS
548            || request_timeout.as_nanos() > Self::HARD_MAXIMUM_REQUEST_TIMEOUT.as_nanos()
549        {
550            return Err(McpServerHttpOptionsError::AboveHardMaximum);
551        }
552
553        Ok(Self {
554            allowed_hosts: allowed_hosts
555                .into_iter()
556                .map(String::into_boxed_str)
557                .collect::<Vec<_>>()
558                .into(),
559            allowed_origins: allowed_origins
560                .into_iter()
561                .map(String::into_boxed_str)
562                .collect::<Vec<_>>()
563                .into(),
564            maximum_request_body_bytes,
565            maximum_concurrent_requests,
566            request_timeout,
567        })
568    }
569
570    /// Constructs a strict development or conformance policy for one loopback port.
571    pub fn loopback(port: u16) -> Result<Self, McpServerHttpOptionsError> {
572        Self::new(
573            [
574                format!("127.0.0.1:{port}"),
575                format!("localhost:{port}"),
576                format!("[::1]:{port}"),
577            ],
578            [
579                format!("http://127.0.0.1:{port}"),
580                format!("http://localhost:{port}"),
581                format!("http://[::1]:{port}"),
582            ],
583            4 * 1024 * 1024,
584            128,
585            Duration::from_secs(30),
586        )
587    }
588
589    /// Returns allowed HTTP Host authorities.
590    pub fn allowed_hosts(&self) -> impl ExactSizeIterator<Item = &str> {
591        self.allowed_hosts.iter().map(AsRef::as_ref)
592    }
593
594    /// Returns allowed browser origins.
595    pub fn allowed_origins(&self) -> impl ExactSizeIterator<Item = &str> {
596        self.allowed_origins.iter().map(AsRef::as_ref)
597    }
598
599    /// Returns the streaming body ceiling.
600    #[must_use]
601    pub const fn maximum_request_body_bytes(&self) -> usize {
602        self.maximum_request_body_bytes
603    }
604
605    /// Returns the local in-flight request ceiling.
606    #[must_use]
607    pub const fn maximum_concurrent_requests(&self) -> usize {
608        self.maximum_concurrent_requests
609    }
610
611    /// Returns the deadline for authentication, admission, and handler dispatch.
612    #[must_use]
613    pub const fn request_timeout(&self) -> Duration {
614        self.request_timeout
615    }
616
617    fn is_loopback_only(&self) -> bool {
618        self.allowed_hosts.iter().all(|allowed| {
619            Authority::try_from(allowed.as_ref()).is_ok_and(|authority| {
620                matches!(
621                    authority
622                        .host()
623                        .trim_matches(|character| matches!(character, '[' | ']'))
624                        .to_ascii_lowercase()
625                        .as_str(),
626                    "localhost" | "127.0.0.1" | "::1"
627                )
628            })
629        })
630    }
631}
632
633fn validate_allowed_hosts(values: &[String]) -> Result<(), McpServerHttpOptionsError> {
634    if values.is_empty() || values.len() > McpServerHttpOptions::HARD_MAXIMUM_ALLOWLIST_ENTRIES {
635        return Err(McpServerHttpOptionsError::InvalidHostAllowlist);
636    }
637    for value in values {
638        if value.trim() != value
639            || value.len() > 1024
640            || value.contains('*')
641            || Authority::try_from(value.as_str()).is_err()
642        {
643            return Err(McpServerHttpOptionsError::InvalidHostAllowlist);
644        }
645    }
646    if has_duplicates(values) {
647        return Err(McpServerHttpOptionsError::DuplicateAllowlistEntry);
648    }
649    Ok(())
650}
651
652fn validate_allowed_origins(values: &[String]) -> Result<(), McpServerHttpOptionsError> {
653    if values.is_empty() || values.len() > McpServerHttpOptions::HARD_MAXIMUM_ALLOWLIST_ENTRIES {
654        return Err(McpServerHttpOptionsError::InvalidOriginAllowlist);
655    }
656    for value in values {
657        let Ok(uri) = value.parse::<http::Uri>() else {
658            return Err(McpServerHttpOptionsError::InvalidOriginAllowlist);
659        };
660        if value.trim() != value
661            || value.len() > 2048
662            || !matches!(uri.scheme_str(), Some("http" | "https"))
663            || uri.authority().is_none()
664            || !matches!(uri.path(), "" | "/")
665            || uri.query().is_some()
666        {
667            return Err(McpServerHttpOptionsError::InvalidOriginAllowlist);
668        }
669    }
670    if has_duplicates(values) {
671        return Err(McpServerHttpOptionsError::DuplicateAllowlistEntry);
672    }
673    Ok(())
674}
675
676fn has_duplicates(values: &[String]) -> bool {
677    let mut sorted = values.to_vec();
678    sorted.sort_unstable();
679    sorted.windows(2).any(|pair| pair[0] == pair[1])
680}
681
682/// Invalid MCP HTTP deployment policy.
683#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
684#[non_exhaustive]
685pub enum McpServerHttpOptionsError {
686    /// Host validation cannot be disabled and wildcards are rejected.
687    #[error("invalid MCP Host allowlist")]
688    InvalidHostAllowlist,
689    /// Origin validation cannot be disabled and entries must be HTTP(S) origins.
690    #[error("invalid MCP Origin allowlist")]
691    InvalidOriginAllowlist,
692    /// An allowlist entry appeared more than once.
693    #[error("duplicate MCP allowlist entry")]
694    DuplicateAllowlistEntry,
695    /// A body, concurrency, or time limit was zero.
696    #[error("MCP server resource limits must be positive")]
697    ZeroLimit,
698    /// A resource limit exceeded the implementation hard maximum.
699    #[error("MCP server resource limit exceeds the hard maximum")]
700    AboveHardMaximum,
701}
702
703/// Construction failure for the production MCP service.
704#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
705#[non_exhaustive]
706pub enum McpServerHttpServiceBuildError {
707    /// The handler advertised a revision outside the frozen server profile.
708    #[error("MCP server handler must support exactly protocol version 2026-07-28")]
709    UnsupportedProtocolProfile,
710    /// Anonymous serving is confined to literal loopback hosts.
711    #[error("anonymous MCP serving is allowed only on loopback hosts")]
712    AnonymousNonLoopback,
713}
714
715/// Cloneable production HTTP service for one MCP handler.
716///
717/// The service implements Tower's [`Service`] and can be mounted directly by
718/// Axum, Hyper, or another compatible server. Its transport is always
719/// stateless: legacy sessions and `initialize` are disabled.
720pub struct McpServerHttpService<H> {
721    inner: StreamableHttpService<H, NeverSessionManager>,
722    options: McpServerHttpOptions,
723    authentication: McpServerAuthentication,
724    admission: Arc<dyn McpServerAdmissionControl>,
725    concurrency: Arc<Semaphore>,
726    shutdown: CancellationToken,
727}
728
729impl<H> Clone for McpServerHttpService<H> {
730    fn clone(&self) -> Self {
731        Self {
732            inner: self.inner.clone(),
733            options: self.options.clone(),
734            authentication: self.authentication.clone(),
735            admission: self.admission.clone(),
736            concurrency: self.concurrency.clone(),
737            shutdown: self.shutdown.clone(),
738        }
739    }
740}
741
742impl<H> fmt::Debug for McpServerHttpService<H> {
743    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
744        formatter
745            .debug_struct("McpServerHttpService")
746            .field("options", &self.options)
747            .field("authentication", &self.authentication)
748            .field("shutting_down", &self.shutdown.is_cancelled())
749            .finish_non_exhaustive()
750    }
751}
752
753impl<H> McpServerHttpService<H>
754where
755    H: ServerHandler + Clone + Send + Sync + 'static,
756{
757    /// Builds a strict service with permissive authenticated admission.
758    pub fn new(
759        handler: H,
760        options: McpServerHttpOptions,
761        authentication: McpServerAuthentication,
762    ) -> Result<Self, McpServerHttpServiceBuildError> {
763        Self::with_admission_control(
764            handler,
765            options,
766            authentication,
767            Arc::new(AllowMcpServerAdmission),
768        )
769    }
770
771    /// Builds a strict service with caller-owned shared admission control.
772    pub fn with_admission_control(
773        handler: H,
774        options: McpServerHttpOptions,
775        authentication: McpServerAuthentication,
776        admission: Arc<dyn McpServerAdmissionControl>,
777    ) -> Result<Self, McpServerHttpServiceBuildError> {
778        let supported = handler.supported_protocol_versions();
779        if supported.as_ref() != [ProtocolVersion::V_2026_07_28] {
780            return Err(McpServerHttpServiceBuildError::UnsupportedProtocolProfile);
781        }
782        if matches!(
783            &authentication.mode,
784            McpServerAuthenticationMode::AnonymousLoopback
785        ) && !options.is_loopback_only()
786        {
787            return Err(McpServerHttpServiceBuildError::AnonymousNonLoopback);
788        }
789
790        let shutdown = CancellationToken::new();
791        let config = StreamableHttpServerConfig::default()
792            .with_legacy_session_mode(false)
793            .with_json_response(true)
794            .with_stateless_protocol_metadata_required(true)
795            .with_allowed_hosts(options.allowed_hosts().map(str::to_owned))
796            .with_allowed_origins(options.allowed_origins().map(str::to_owned))
797            .with_max_request_body_bytes(options.maximum_request_body_bytes())
798            .with_cancellation_token(shutdown.clone());
799        let shared_handler = Arc::new(handler);
800        let inner = StreamableHttpService::new(
801            move || Ok(shared_handler.as_ref().clone()),
802            Arc::new(NeverSessionManager::default()),
803            config,
804        );
805        let maximum_concurrent_requests = options.maximum_concurrent_requests();
806        Ok(Self {
807            inner,
808            options,
809            authentication,
810            admission,
811            concurrency: Arc::new(Semaphore::new(maximum_concurrent_requests)),
812            shutdown,
813        })
814    }
815
816    /// Stops accepting new work and cancels active transport contexts.
817    pub fn shutdown(&self) {
818        self.shutdown.cancel();
819    }
820
821    /// Returns whether shutdown has begun.
822    #[must_use]
823    pub fn is_shutting_down(&self) -> bool {
824        self.shutdown.is_cancelled()
825    }
826
827    async fn handle<B>(&self, mut request: Request<B>) -> McpHttpResponse
828    where
829        B: Body + Send + 'static,
830        B::Error: fmt::Display,
831        B::Data: Send + 'static,
832    {
833        if self.shutdown.is_cancelled() {
834            return public_error(
835                StatusCode::SERVICE_UNAVAILABLE,
836                "Service unavailable",
837                Some(1),
838            );
839        }
840
841        let Ok(_permit) = self.concurrency.clone().try_acquire_owned() else {
842            return public_error(StatusCode::TOO_MANY_REQUESTS, "Too many requests", Some(1));
843        };
844
845        let method_hint = bounded_header_hint(request.headers(), MCP_METHOD_HEADER);
846        let name_hint = bounded_header_hint(request.headers(), MCP_NAME_HEADER);
847        let operation = async {
848            let principal = match &self.authentication.mode {
849                McpServerAuthenticationMode::AnonymousLoopback => McpServerPrincipal::anonymous(),
850                McpServerAuthenticationMode::Bearer {
851                    authenticator,
852                    challenge,
853                } => {
854                    let Ok(credential) = parse_bearer(request.headers()) else {
855                        return unauthorized(challenge);
856                    };
857                    let authentication_request = McpServerAuthenticationRequest {
858                        credential,
859                        transport_method_hint: method_hint.clone(),
860                        transport_name_hint: name_hint.clone(),
861                    };
862                    match authenticator.authenticate(authentication_request).await {
863                        Ok(principal) => principal,
864                        Err(McpServerAuthenticationError::InvalidCredential) => {
865                            return unauthorized(challenge);
866                        }
867                        Err(McpServerAuthenticationError::Forbidden) => {
868                            return forbidden(Some(challenge));
869                        }
870                        Err(McpServerAuthenticationError::Unavailable) => {
871                            return public_error(
872                                StatusCode::SERVICE_UNAVAILABLE,
873                                "Service unavailable",
874                                Some(1),
875                            );
876                        }
877                    }
878                }
879            };
880
881            let admission_request = McpServerAdmissionRequest {
882                principal: principal.clone(),
883                transport_method_hint: method_hint,
884                transport_name_hint: name_hint,
885            };
886            match self.admission.admit(admission_request).await {
887                Ok(()) => {}
888                Err(McpServerAdmissionError::Forbidden) => return forbidden(None),
889                Err(McpServerAdmissionError::RateLimited { retry_after }) => {
890                    return public_error(
891                        StatusCode::TOO_MANY_REQUESTS,
892                        "Too many requests",
893                        Some(retry_after_seconds(retry_after)),
894                    );
895                }
896                Err(McpServerAdmissionError::Unavailable) => {
897                    return public_error(
898                        StatusCode::SERVICE_UNAVAILABLE,
899                        "Service unavailable",
900                        Some(1),
901                    );
902                }
903            }
904
905            request.extensions_mut().insert(principal);
906            self.inner.handle(request).await
907        };
908
909        match tokio::time::timeout(self.options.request_timeout(), operation).await {
910            Ok(response) => response,
911            Err(_) => public_error(StatusCode::GATEWAY_TIMEOUT, "Request timed out", None),
912        }
913    }
914}
915
916impl<B, H> Service<Request<B>> for McpServerHttpService<H>
917where
918    B: Body + Send + 'static,
919    B::Error: fmt::Display,
920    B::Data: Send + 'static,
921    H: ServerHandler + Clone + Send + Sync + 'static,
922{
923    type Response = McpHttpResponse;
924    type Error = Infallible;
925    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
926
927    fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
928        Poll::Ready(Ok(()))
929    }
930
931    fn call(&mut self, request: Request<B>) -> Self::Future {
932        let service = self.clone();
933        Box::pin(async move { Ok(service.handle(request).await) })
934    }
935}
936
937fn parse_bearer(headers: &http::HeaderMap) -> Result<McpServerBearerCredential, ()> {
938    let mut values = headers.get_all(AUTHORIZATION).iter();
939    let value = values.next().ok_or(())?;
940    if values.next().is_some() {
941        return Err(());
942    }
943    let value = value.to_str().map_err(|_| ())?;
944    let (scheme, credential) = value.split_once(' ').ok_or(())?;
945    if !scheme.eq_ignore_ascii_case("Bearer") || credential.contains(' ') {
946        return Err(());
947    }
948    McpServerBearerCredential::new(credential).map_err(|_| ())
949}
950
951fn bounded_header_hint(headers: &http::HeaderMap, name: &'static str) -> Option<Box<str>> {
952    let value = headers.get(name)?.to_str().ok()?;
953    if value.is_empty() || value.len() > MAX_HINT_BYTES || value.chars().any(char::is_control) {
954        return None;
955    }
956    Some(value.to_owned().into_boxed_str())
957}
958
959fn retry_after_seconds(duration: Duration) -> u64 {
960    duration.as_secs().clamp(1, 24 * 60 * 60)
961}
962
963fn unauthorized(challenge: &McpServerBearerChallenge) -> McpHttpResponse {
964    let mut response = public_error(StatusCode::UNAUTHORIZED, "Unauthorized", None);
965    response
966        .headers_mut()
967        .insert(WWW_AUTHENTICATE, challenge.value.clone());
968    response
969}
970
971fn forbidden(challenge: Option<&McpServerBearerChallenge>) -> McpHttpResponse {
972    let mut response = public_error(StatusCode::FORBIDDEN, "Forbidden", None);
973    if let Some(challenge) = challenge {
974        response
975            .headers_mut()
976            .insert(WWW_AUTHENTICATE, challenge.value.clone());
977    }
978    response
979}
980
981fn public_error(
982    status: StatusCode,
983    message: &'static str,
984    retry_after: Option<u64>,
985) -> McpHttpResponse {
986    let mut response = Response::builder()
987        .status(status)
988        .header(CONTENT_TYPE, "text/plain; charset=utf-8")
989        .header(CACHE_CONTROL, "no-store")
990        .header(PRAGMA, "no-cache")
991        .body(Full::new(Bytes::from_static(message.as_bytes())).boxed())
992        .expect("static MCP HTTP response is valid");
993    if let Some(seconds) = retry_after {
994        response.headers_mut().insert(
995            RETRY_AFTER,
996            HeaderValue::from_str(&seconds.to_string()).expect("bounded seconds are header-safe"),
997        );
998    }
999    response
1000}
1001
1002/// Returns the authenticated principal injected by [`McpServerHttpService`].
1003///
1004/// A handler mounted without this service receives `None` and should fail
1005/// closed whenever its deployment requires authentication.
1006#[must_use]
1007pub fn mcp_server_principal(context: &RequestContext<RoleServer>) -> Option<&McpServerPrincipal> {
1008    context
1009        .extensions
1010        .get::<Parts>()
1011        .and_then(|parts| parts.extensions.get::<McpServerPrincipal>())
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use std::borrow::Cow;
1017    use std::sync::atomic::{AtomicBool, Ordering};
1018
1019    use http_body_util::BodyExt as _;
1020    use rmcp::{
1021        ErrorData,
1022        model::{DiscoverResult, Implementation, ServerCapabilities, ServerConfig},
1023    };
1024    use serde_json::json;
1025
1026    use super::*;
1027
1028    #[derive(Clone)]
1029    struct TestHandler {
1030        saw_principal: Arc<AtomicBool>,
1031    }
1032
1033    impl ServerHandler for TestHandler {
1034        fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
1035            Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
1036        }
1037
1038        fn get_info(&self) -> ServerConfig {
1039            ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
1040                .with_server_info(Implementation::new("stateknot-test", "0.0.0"))
1041        }
1042
1043        async fn discover(
1044            &self,
1045            context: RequestContext<RoleServer>,
1046        ) -> Result<DiscoverResult, ErrorData> {
1047            self.saw_principal.store(
1048                mcp_server_principal(&context).is_some_and(|value| value.subject() == "tenant-a"),
1049                Ordering::SeqCst,
1050            );
1051            Ok(DiscoverResult::from_server_info(
1052                vec![ProtocolVersion::V_2026_07_28],
1053                self.get_info(),
1054            ))
1055        }
1056    }
1057
1058    #[derive(Clone, Copy)]
1059    struct StaticAuthenticator;
1060
1061    impl McpServerAuthenticator for StaticAuthenticator {
1062        fn authenticate(
1063            &self,
1064            request: McpServerAuthenticationRequest,
1065        ) -> BoxFuture<'_, Result<McpServerPrincipal, McpServerAuthenticationError>> {
1066            let accepted = request.credential().expose_secret() == "test-token";
1067            Box::pin(async move {
1068                if accepted {
1069                    McpServerPrincipal::new("tenant-a", ["mcp:invoke"])
1070                        .map_err(|_| McpServerAuthenticationError::Unavailable)
1071                } else {
1072                    Err(McpServerAuthenticationError::InvalidCredential)
1073                }
1074            })
1075        }
1076    }
1077
1078    fn test_request(authorization: Option<&str>) -> Request<Full<Bytes>> {
1079        let body = serde_json::to_vec(&json!({
1080            "jsonrpc": "2.0",
1081            "id": 1,
1082            "method": "server/discover",
1083            "params": {
1084                "_meta": {
1085                    "io.modelcontextprotocol/protocolVersion": "2026-07-28",
1086                    "io.modelcontextprotocol/clientInfo": {
1087                        "name": "stateknot-test-client",
1088                        "version": "0.0.0"
1089                    },
1090                    "io.modelcontextprotocol/clientCapabilities": {}
1091                }
1092            }
1093        }))
1094        .unwrap();
1095        let mut builder = Request::builder()
1096            .method("POST")
1097            .uri("http://127.0.0.1:32123/mcp")
1098            .header("host", "127.0.0.1:32123")
1099            .header("origin", "http://127.0.0.1:32123")
1100            .header("content-type", "application/json")
1101            .header("accept", "application/json, text/event-stream")
1102            .header("mcp-protocol-version", "2026-07-28")
1103            .header("mcp-method", "server/discover");
1104        if let Some(authorization) = authorization {
1105            builder = builder.header(AUTHORIZATION, authorization);
1106        }
1107        builder.body(Full::new(Bytes::from(body))).unwrap()
1108    }
1109
1110    fn bearer_service(saw_principal: Arc<AtomicBool>) -> McpServerHttpService<TestHandler> {
1111        let challenge = McpServerBearerChallenge::new(
1112            "stateknot-test",
1113            Some("https://auth.example.test/.well-known/oauth-protected-resource"),
1114        )
1115        .unwrap();
1116        McpServerHttpService::new(
1117            TestHandler { saw_principal },
1118            McpServerHttpOptions::loopback(32123).unwrap(),
1119            McpServerAuthentication::bearer(StaticAuthenticator, challenge),
1120        )
1121        .unwrap()
1122    }
1123
1124    #[tokio::test]
1125    async fn bearer_authentication_is_fail_closed_and_injects_principal() {
1126        let observed = Arc::new(AtomicBool::new(false));
1127        let mut service = bearer_service(observed.clone());
1128
1129        let missing = service.call(test_request(None)).await.unwrap();
1130        assert_eq!(missing.status(), StatusCode::UNAUTHORIZED);
1131        assert!(missing.headers().contains_key(WWW_AUTHENTICATE));
1132        assert!(!observed.load(Ordering::SeqCst));
1133
1134        let invalid = service
1135            .call(test_request(Some("Bearer wrong-token")))
1136            .await
1137            .unwrap();
1138        assert_eq!(invalid.status(), StatusCode::UNAUTHORIZED);
1139        assert!(!observed.load(Ordering::SeqCst));
1140
1141        let accepted = service
1142            .call(test_request(Some("Bearer test-token")))
1143            .await
1144            .unwrap();
1145        assert_eq!(accepted.status(), StatusCode::OK);
1146        assert!(observed.load(Ordering::SeqCst));
1147        let bytes = accepted.into_body().collect().await.unwrap().to_bytes();
1148        let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
1149        assert_eq!(payload.pointer("/id"), Some(&json!(1)));
1150        assert_eq!(
1151            payload.pointer("/result/supportedVersions/0"),
1152            Some(&json!("2026-07-28"))
1153        );
1154    }
1155
1156    #[test]
1157    fn deployment_policy_rejects_unsafe_configuration() {
1158        assert!(matches!(
1159            McpServerHttpOptions::new(
1160                std::iter::empty::<String>(),
1161                ["https://app.example.test"],
1162                1,
1163                1,
1164                Duration::from_secs(1),
1165            ),
1166            Err(McpServerHttpOptionsError::InvalidHostAllowlist)
1167        ));
1168        assert!(matches!(
1169            McpServerHttpOptions::new(
1170                ["*.example.test"],
1171                ["https://app.example.test"],
1172                1,
1173                1,
1174                Duration::from_secs(1),
1175            ),
1176            Err(McpServerHttpOptionsError::InvalidHostAllowlist)
1177        ));
1178
1179        let public = McpServerHttpOptions::new(
1180            ["mcp.example.test"],
1181            ["https://app.example.test"],
1182            1024,
1183            8,
1184            Duration::from_secs(5),
1185        )
1186        .unwrap();
1187        let handler = TestHandler {
1188            saw_principal: Arc::new(AtomicBool::new(false)),
1189        };
1190        assert!(matches!(
1191            McpServerHttpService::new(
1192                handler,
1193                public,
1194                McpServerAuthentication::anonymous_loopback(),
1195            ),
1196            Err(McpServerHttpServiceBuildError::AnonymousNonLoopback)
1197        ));
1198    }
1199
1200    #[test]
1201    fn credentials_and_principals_are_bounded_and_redacted() {
1202        let credential = McpServerBearerCredential::new("abc.def_123~+/=").unwrap();
1203        assert_eq!(credential.expose_secret(), "abc.def_123~+/=");
1204        assert!(!format!("{credential:?}").contains("abc.def"));
1205        assert!(matches!(
1206            McpServerBearerCredential::new("bad token"),
1207            Err(McpServerBearerCredentialError::InvalidSyntax)
1208        ));
1209
1210        let principal = McpServerPrincipal::new("tenant-a", ["write", "read"]).unwrap();
1211        assert_eq!(principal.scopes().collect::<Vec<_>>(), ["read", "write"]);
1212        assert!(principal.has_scope("read"));
1213        assert!(matches!(
1214            McpServerPrincipal::new("tenant-a", ["read", "read"]),
1215            Err(McpServerPrincipalError::DuplicateScope)
1216        ));
1217    }
1218}