Skip to main content

stateknot_integrations/
mcp.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Strict MCP 2026-07-28 remote-tool binding.
5//!
6//! This first production profile intentionally supports modern, stateless
7//! Streamable HTTP with complete JSON responses only. Discovery happens once
8//! while the immutable binding is built. Each admitted tool attempt then sends
9//! exactly one `tools/call` request. Stateful sessions, SSE, transparent
10//! reconnects, legacy initialization, MRTR, Tasks, progress forwarding, and
11//! artifact materialization fail closed instead of changing retry semantics.
12
13use std::{
14    collections::{HashMap, HashSet},
15    fmt,
16    sync::{Arc, RwLock},
17    time::{Duration, Instant},
18};
19
20use futures_util::{StreamExt, stream::BoxStream};
21use http::{HeaderName, HeaderValue};
22use reqwest::{StatusCode, header};
23use rmcp::{
24    ClientLifecycleMode, ClientServiceExt, RoleClient,
25    model::{
26        CallToolRequestParams, CallToolResponse, ClientCapabilities, ClientConfig,
27        ClientJsonRpcMessage, Implementation, JsonRpcMessage, PaginatedRequestParams,
28        ProtocolVersion, ServerJsonRpcMessage, Tool,
29    },
30    service::{RunningService, RunningServiceCancellationToken},
31    transport::{
32        StreamableHttpClientTransport,
33        common::client_side_sse::NeverRetry,
34        streamable_http_client::{
35            AuthRequiredError, InsufficientScopeError, SseError, StreamableHttpClient,
36            StreamableHttpClientTransportConfig, StreamableHttpError, StreamableHttpPostResponse,
37        },
38    },
39};
40use serde_json::Value;
41use sse_stream::Sse;
42use stateknot_core::{
43    BoundedJson, BoxFuture, Digest, DurationMillis, ErasedTool, Failure, FailureCategory,
44    FailureCode, FailureId, FailureMessage, FailureOrigin, GraphSchemaValidator,
45    ModelSchemaRegistry, RetryAdvice, ToolArtifacts, ToolContext, ToolDescriptor, ToolError,
46    ToolErrorPhase, ToolErrorProvenance, ToolExternalEffect, ToolInput, ToolResult, ToolRisk,
47    ToolStopReason,
48};
49use thiserror::Error;
50
51use crate::{
52    ApiKey, McpToolApproval, McpToolAuthorizationRequest, ProviderEndpoint, ProviderEndpointError,
53    ProviderHttpOptions, http::build_client, mcp_tool_descriptor_digest,
54};
55
56const MCP_PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::V_2026_07_28;
57const MCP_JSON: &str = "application/json";
58const MCP_SESSION_ID: &str = "mcp-session-id";
59
60/// Schema capabilities required by the MCP adapter.
61///
62/// The local registry remains the authority. Remote schema documents are used
63/// only as discovery evidence and must exactly match the locally pinned RFC
64/// 8785 canonical bytes.
65pub trait McpSchemaRegistry: ModelSchemaRegistry + GraphSchemaValidator {}
66
67impl<T> McpSchemaRegistry for T where T: ModelSchemaRegistry + GraphSchemaValidator {}
68
69/// Exact implementation identity expected from modern MCP discovery.
70#[derive(Clone, Eq, PartialEq)]
71pub struct McpServerIdentity {
72    name: Box<str>,
73    version: Box<str>,
74}
75
76impl McpServerIdentity {
77    /// Maximum bytes accepted for either identity component.
78    pub const MAX_COMPONENT_BYTES: usize = 256;
79
80    /// Constructs a bounded, printable exact server identity.
81    ///
82    /// # Errors
83    ///
84    /// Rejects empty, oversized, whitespace-padded, or control-containing
85    /// components.
86    pub fn new(
87        name: impl Into<String>,
88        version: impl Into<String>,
89    ) -> Result<Self, McpServerIdentityError> {
90        let name = name.into();
91        let version = version.into();
92        validate_identity_component(&name, McpServerIdentityComponent::Name)?;
93        validate_identity_component(&version, McpServerIdentityComponent::Version)?;
94        Ok(Self {
95            name: name.into_boxed_str(),
96            version: version.into_boxed_str(),
97        })
98    }
99
100    /// Returns the exact implementation name.
101    #[must_use]
102    pub fn name(&self) -> &str {
103        &self.name
104    }
105
106    /// Returns the exact implementation version.
107    #[must_use]
108    pub fn version(&self) -> &str {
109        &self.version
110    }
111
112    fn matches(&self, implementation: &Implementation) -> bool {
113        self.name() == implementation.name && self.version() == implementation.version
114    }
115}
116
117impl fmt::Debug for McpServerIdentity {
118    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
119        formatter
120            .debug_struct("McpServerIdentity")
121            .field("name", &self.name)
122            .field("version", &self.version)
123            .finish()
124    }
125}
126
127#[derive(Clone, Copy, Debug, Eq, PartialEq)]
128enum McpServerIdentityComponent {
129    Name,
130    Version,
131}
132
133/// Invalid expected MCP server identity.
134#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
135#[non_exhaustive]
136pub enum McpServerIdentityError {
137    /// A required component was empty.
138    #[error("MCP server identity component is empty")]
139    Empty,
140    /// A component exceeded its hard byte ceiling.
141    #[error("MCP server identity component is too long")]
142    TooLong,
143    /// Trimming would change a component.
144    #[error("MCP server identity component has boundary whitespace")]
145    BoundaryWhitespace,
146    /// A component contained a control character.
147    #[error("MCP server identity component contains a control character")]
148    ControlCharacter,
149}
150
151fn validate_identity_component(
152    value: &str,
153    _component: McpServerIdentityComponent,
154) -> Result<(), McpServerIdentityError> {
155    if value.is_empty() {
156        return Err(McpServerIdentityError::Empty);
157    }
158    if value.len() > McpServerIdentity::MAX_COMPONENT_BYTES {
159        return Err(McpServerIdentityError::TooLong);
160    }
161    if value.trim() != value {
162        return Err(McpServerIdentityError::BoundaryWhitespace);
163    }
164    if value.chars().any(char::is_control) {
165        return Err(McpServerIdentityError::ControlCharacter);
166    }
167    Ok(())
168}
169
170/// Bounded transport and discovery policy for one MCP binding.
171#[derive(Clone, Copy, Debug, Eq, PartialEq)]
172pub struct McpHttpOptions {
173    transport: ProviderHttpOptions,
174    startup_timeout: Duration,
175    shutdown_timeout: Duration,
176    maximum_discovery_pages: usize,
177    maximum_discovered_tools: usize,
178}
179
180impl McpHttpOptions {
181    /// Hard page ceiling for a single tool-catalog discovery.
182    pub const HARD_MAXIMUM_DISCOVERY_PAGES: usize = 64;
183    /// Hard tool ceiling for a single endpoint binding.
184    pub const HARD_MAXIMUM_DISCOVERED_TOOLS: usize = 4096;
185
186    /// Constructs explicit bounded MCP transport policy.
187    ///
188    /// # Errors
189    ///
190    /// Rejects zero or implementation-exceeding limits.
191    pub const fn new(
192        transport: ProviderHttpOptions,
193        startup_timeout: Duration,
194        shutdown_timeout: Duration,
195        maximum_discovery_pages: usize,
196        maximum_discovered_tools: usize,
197    ) -> Result<Self, McpHttpOptionsError> {
198        if startup_timeout.is_zero() || shutdown_timeout.is_zero() {
199            return Err(McpHttpOptionsError::ZeroTimeout);
200        }
201        if maximum_discovery_pages == 0 || maximum_discovered_tools == 0 {
202            return Err(McpHttpOptionsError::ZeroDiscoveryLimit);
203        }
204        if maximum_discovery_pages > Self::HARD_MAXIMUM_DISCOVERY_PAGES
205            || maximum_discovered_tools > Self::HARD_MAXIMUM_DISCOVERED_TOOLS
206        {
207            return Err(McpHttpOptionsError::AboveHardMaximum);
208        }
209        Ok(Self {
210            transport,
211            startup_timeout,
212            shutdown_timeout,
213            maximum_discovery_pages,
214            maximum_discovered_tools,
215        })
216    }
217
218    /// Returns the complete HTTP resource policy.
219    #[must_use]
220    pub const fn transport(self) -> ProviderHttpOptions {
221        self.transport
222    }
223
224    /// Returns the total startup discovery deadline.
225    #[must_use]
226    pub const fn startup_timeout(self) -> Duration {
227        self.startup_timeout
228    }
229
230    /// Returns the graceful transport shutdown bound.
231    #[must_use]
232    pub const fn shutdown_timeout(self) -> Duration {
233        self.shutdown_timeout
234    }
235
236    /// Returns the maximum accepted catalog pages.
237    #[must_use]
238    pub const fn maximum_discovery_pages(self) -> usize {
239        self.maximum_discovery_pages
240    }
241
242    /// Returns the maximum accepted tools across all pages.
243    #[must_use]
244    pub const fn maximum_discovered_tools(self) -> usize {
245        self.maximum_discovered_tools
246    }
247}
248
249impl Default for McpHttpOptions {
250    fn default() -> Self {
251        Self {
252            transport: ProviderHttpOptions::default(),
253            startup_timeout: Duration::from_secs(30),
254            shutdown_timeout: Duration::from_secs(5),
255            maximum_discovery_pages: 16,
256            maximum_discovered_tools: 1024,
257        }
258    }
259}
260
261/// Invalid MCP transport policy.
262#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
263#[non_exhaustive]
264pub enum McpHttpOptionsError {
265    /// Startup and shutdown deadlines must be positive.
266    #[error("MCP startup and shutdown timeouts must be positive")]
267    ZeroTimeout,
268    /// Catalog bounds must be positive.
269    #[error("MCP discovery limits must be positive")]
270    ZeroDiscoveryLimit,
271    /// A catalog bound exceeded the implementation ceiling.
272    #[error("MCP discovery limit exceeds the implementation maximum")]
273    AboveHardMaximum,
274}
275
276/// Attempt-scoped HTTP authorization material.
277#[derive(Clone, Debug)]
278#[non_exhaustive]
279pub enum McpAuthorization {
280    /// The endpoint is intentionally called without an Authorization header.
281    Anonymous,
282    /// The endpoint receives an RFC 6750 bearer credential.
283    Bearer(ApiKey),
284}
285
286/// Public-safe failure from an MCP authorization source.
287#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
288#[non_exhaustive]
289pub enum McpAuthorizationError {
290    /// The secret backend is temporarily unavailable.
291    #[error("MCP authorization source is unavailable")]
292    Unavailable,
293    /// Policy refused secret access for this binding or attempt.
294    #[error("MCP authorization access was denied")]
295    PermissionDenied,
296}
297
298/// Credential source for startup discovery and each admitted tool attempt.
299///
300/// Implementations should resolve secret handles rather than embedding tenant
301/// credentials in descriptors. The transport copies no secret into MCP
302/// metadata and never formats authorization material.
303pub trait McpAuthorizationProvider: Send + Sync + 'static {
304    /// Resolves authorization for bounded startup discovery.
305    fn resolve_startup(
306        &self,
307        descriptor: &ToolDescriptor,
308    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>>;
309
310    /// Resolves authorization for one exact durable attempt.
311    fn resolve_attempt(
312        &self,
313        context: &ToolContext,
314    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>>;
315}
316
317/// Explicit anonymous authorization provider.
318#[derive(Clone, Copy, Debug, Default)]
319pub struct AnonymousMcpAuthorization;
320
321impl McpAuthorizationProvider for AnonymousMcpAuthorization {
322    fn resolve_startup(
323        &self,
324        _descriptor: &ToolDescriptor,
325    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
326        Box::pin(async { Ok(McpAuthorization::Anonymous) })
327    }
328
329    fn resolve_attempt(
330        &self,
331        _context: &ToolContext,
332    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
333        Box::pin(async { Ok(McpAuthorization::Anonymous) })
334    }
335}
336
337impl crate::mcp_client::McpClientAuthorizationProvider for AnonymousMcpAuthorization {
338    fn resolve(
339        &self,
340        _request: &crate::mcp_client::McpClientAuthorizationRequest,
341    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
342        Box::pin(async { Ok(McpAuthorization::Anonymous) })
343    }
344}
345
346/// Immutable bearer authorization for controlled single-tenant bindings.
347#[derive(Clone)]
348pub struct StaticMcpBearerAuthorization {
349    key: Arc<ApiKey>,
350}
351
352impl StaticMcpBearerAuthorization {
353    /// Wraps one validated, zeroizing bearer credential.
354    #[must_use]
355    pub fn new(key: ApiKey) -> Self {
356        Self { key: Arc::new(key) }
357    }
358}
359
360impl fmt::Debug for StaticMcpBearerAuthorization {
361    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
362        formatter.write_str("StaticMcpBearerAuthorization([REDACTED])")
363    }
364}
365
366impl McpAuthorizationProvider for StaticMcpBearerAuthorization {
367    fn resolve_startup(
368        &self,
369        _descriptor: &ToolDescriptor,
370    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
371        let key = self.key.as_ref().clone();
372        Box::pin(async move { Ok(McpAuthorization::Bearer(key)) })
373    }
374
375    fn resolve_attempt(
376        &self,
377        _context: &ToolContext,
378    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
379        let key = self.key.as_ref().clone();
380        Box::pin(async move { Ok(McpAuthorization::Bearer(key)) })
381    }
382}
383
384impl crate::mcp_client::McpClientAuthorizationProvider for StaticMcpBearerAuthorization {
385    fn resolve(
386        &self,
387        _request: &crate::mcp_client::McpClientAuthorizationRequest,
388    ) -> BoxFuture<'_, Result<McpAuthorization, McpAuthorizationError>> {
389        let key = self.key.as_ref().clone();
390        Box::pin(async move { Ok(McpAuthorization::Bearer(key)) })
391    }
392}
393
394#[derive(Clone)]
395struct AuthorizationSlot {
396    inner: Arc<RwLock<McpAuthorization>>,
397}
398
399impl AuthorizationSlot {
400    fn anonymous() -> Self {
401        Self {
402            inner: Arc::new(RwLock::new(McpAuthorization::Anonymous)),
403        }
404    }
405
406    fn replace(&self, authorization: McpAuthorization) -> Result<(), StrictHttpError> {
407        *self
408            .inner
409            .write()
410            .map_err(|_| StrictHttpError::AuthorizationState)? = authorization;
411        Ok(())
412    }
413
414    fn snapshot(&self) -> Result<McpAuthorization, StrictHttpError> {
415        self.inner
416            .read()
417            .map_err(|_| StrictHttpError::AuthorizationState)
418            .map(|value| value.clone())
419    }
420}
421
422struct AuthorizationReset<'a>(&'a AuthorizationSlot);
423
424// A dropped/failed exchange may still be queued inside the SDK transport.
425// Retire an approved binding before another attempt can install credentials.
426struct ApprovedDispatchGuard(Option<RunningServiceCancellationToken>);
427
428impl Drop for ApprovedDispatchGuard {
429    fn drop(&mut self) {
430        if let Some(token) = self.0.take() {
431            token.cancel();
432        }
433    }
434}
435
436impl Drop for AuthorizationReset<'_> {
437    fn drop(&mut self) {
438        let _ = self.0.replace(McpAuthorization::Anonymous);
439    }
440}
441
442#[derive(Clone)]
443struct StrictJsonHttpClient {
444    client: reqwest::Client,
445    authorization: AuthorizationSlot,
446    approved_tool: Option<(String, Digest)>,
447    maximum_request_bytes: usize,
448    maximum_response_bytes: usize,
449}
450
451impl fmt::Debug for StrictJsonHttpClient {
452    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
453        formatter
454            .debug_struct("StrictJsonHttpClient")
455            .field("maximum_request_bytes", &self.maximum_request_bytes)
456            .field("maximum_response_bytes", &self.maximum_response_bytes)
457            .finish_non_exhaustive()
458    }
459}
460
461#[derive(Clone, Copy, Debug, Error)]
462enum StrictHttpError {
463    #[error("MCP HTTP authorization state is unavailable")]
464    AuthorizationState,
465    #[error("MCP JSON request serialization failed")]
466    RequestSerialization,
467    #[error("MCP JSON request exceeded its byte ceiling")]
468    RequestTooLarge,
469    #[error("MCP HTTP transport failed")]
470    Transport,
471    #[error("MCP HTTP response exceeded its byte ceiling")]
472    ResponseTooLarge,
473}
474
475impl StreamableHttpClient for StrictJsonHttpClient {
476    type Error = StrictHttpError;
477
478    async fn post_message(
479        &self,
480        uri: Arc<str>,
481        message: ClientJsonRpcMessage,
482        session_id: Option<Arc<str>>,
483        auth_header: Option<String>,
484        custom_headers: HashMap<HeaderName, HeaderValue>,
485    ) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
486        if session_id.is_some() {
487            return Err(StreamableHttpError::UnexpectedServerResponse(
488                "StateKnot MCP bindings require a stateless server".into(),
489            ));
490        }
491        if auth_header.is_some() {
492            return Err(StreamableHttpError::ReservedHeaderConflict(
493                "authorization".to_owned(),
494            ));
495        }
496        let body = serde_json::to_vec(&message)
497            .map_err(|_| StreamableHttpError::Client(StrictHttpError::RequestSerialization))?;
498        if body.len() > self.maximum_request_bytes {
499            return Err(StreamableHttpError::Client(
500                StrictHttpError::RequestTooLarge,
501            ));
502        }
503
504        let mut request = self
505            .client
506            .post(uri.as_ref())
507            .header(header::ACCEPT, MCP_JSON)
508            .header(header::CONTENT_TYPE, MCP_JSON);
509        match self
510            .authorization
511            .snapshot()
512            .map_err(StreamableHttpError::Client)?
513        {
514            McpAuthorization::Anonymous => {}
515            McpAuthorization::Bearer(key) => {
516                request = request.bearer_auth(key.expose_secret());
517            }
518        }
519        request = apply_protocol_headers(request, custom_headers)?;
520        let response = request
521            .body(body)
522            .send()
523            .await
524            .map_err(|_| StreamableHttpError::Client(StrictHttpError::Transport))?;
525        let status = response.status();
526        if status == StatusCode::UNAUTHORIZED {
527            return Err(StreamableHttpError::AuthRequired(AuthRequiredError::new(
528                "Bearer".to_owned(),
529            )));
530        }
531        if status == StatusCode::FORBIDDEN {
532            return Err(StreamableHttpError::InsufficientScope(
533                InsufficientScopeError::new("Bearer".to_owned(), None),
534            ));
535        }
536        if response.headers().contains_key(MCP_SESSION_ID) {
537            return Err(StreamableHttpError::UnexpectedServerResponse(
538                "StateKnot MCP bindings reject stateful sessions".into(),
539            ));
540        }
541
542        let is_control_message = matches!(
543            message,
544            ClientJsonRpcMessage::Notification(_)
545                | ClientJsonRpcMessage::Response(_)
546                | ClientJsonRpcMessage::Error(_)
547        );
548        if matches!(status, StatusCode::ACCEPTED | StatusCode::NO_CONTENT) {
549            return if is_control_message {
550                Ok(StreamableHttpPostResponse::Accepted)
551            } else {
552                Err(StreamableHttpError::UnexpectedServerResponse(
553                    "MCP request returned no complete JSON response".into(),
554                ))
555            };
556        }
557
558        let content_type_is_json = response
559            .headers()
560            .get(header::CONTENT_TYPE)
561            .and_then(|value| value.to_str().ok())
562            .is_some_and(is_json_content_type);
563        let body = bounded_response_body(response, self.maximum_response_bytes)
564            .await
565            .map_err(StreamableHttpError::Client)?;
566        if status.is_success() && body.is_empty() && is_control_message {
567            return Ok(StreamableHttpPostResponse::Accepted);
568        }
569        if !content_type_is_json {
570            return Err(StreamableHttpError::UnexpectedContentType(None));
571        }
572        if let Some((name, digest)) = &self.approved_tool {
573            verify_approved_catalog(name, *digest, &body)?;
574        }
575        let parsed = serde_json::from_slice::<ServerJsonRpcMessage>(&body)?;
576        if !status.is_success() && !matches!(parsed, JsonRpcMessage::Error(_)) {
577            return Err(StreamableHttpError::UnexpectedServerResponse(
578                "MCP endpoint returned a non-success response".into(),
579            ));
580        }
581        Ok(StreamableHttpPostResponse::Json(parsed, None))
582    }
583
584    async fn delete_session(
585        &self,
586        _uri: Arc<str>,
587        _session_id: Arc<str>,
588        _auth_header: Option<String>,
589        _custom_headers: HashMap<HeaderName, HeaderValue>,
590    ) -> Result<(), StreamableHttpError<Self::Error>> {
591        Err(StreamableHttpError::ServerDoesNotSupportDeleteSession)
592    }
593
594    async fn get_stream(
595        &self,
596        _uri: Arc<str>,
597        _session_id: Option<Arc<str>>,
598        _last_event_id: Option<String>,
599        _auth_header: Option<String>,
600        _custom_headers: HashMap<HeaderName, HeaderValue>,
601    ) -> Result<BoxStream<'static, Result<Sse, SseError>>, StreamableHttpError<Self::Error>> {
602        Err(StreamableHttpError::ServerDoesNotSupportSse)
603    }
604}
605
606fn apply_protocol_headers(
607    mut request: reqwest::RequestBuilder,
608    headers: HashMap<HeaderName, HeaderValue>,
609) -> Result<reqwest::RequestBuilder, StreamableHttpError<StrictHttpError>> {
610    for (name, value) in headers {
611        if is_reserved_header(&name) {
612            return Err(StreamableHttpError::ReservedHeaderConflict(
613                name.as_str().to_owned(),
614            ));
615        }
616        request = request.header(name, value);
617    }
618    Ok(request)
619}
620
621fn is_reserved_header(name: &HeaderName) -> bool {
622    matches!(
623        name.as_str(),
624        "accept"
625            | "authorization"
626            | "connection"
627            | "content-length"
628            | "content-type"
629            | "cookie"
630            | "host"
631            | "proxy-authorization"
632            | "set-cookie"
633            | "transfer-encoding"
634    )
635}
636
637fn is_json_content_type(value: &str) -> bool {
638    value
639        .split(';')
640        .next()
641        .is_some_and(|mime| mime.trim().eq_ignore_ascii_case(MCP_JSON))
642}
643
644async fn bounded_response_body(
645    response: reqwest::Response,
646    maximum: usize,
647) -> Result<Vec<u8>, StrictHttpError> {
648    if response
649        .content_length()
650        .is_some_and(|length| length > maximum as u64)
651    {
652        return Err(StrictHttpError::ResponseTooLarge);
653    }
654    let mut body = Vec::new();
655    let mut stream = response.bytes_stream();
656    while let Some(chunk) = stream.next().await {
657        let chunk = chunk.map_err(|_| StrictHttpError::Transport)?;
658        if body.len().saturating_add(chunk.len()) > maximum {
659            return Err(StrictHttpError::ResponseTooLarge);
660        }
661        body.extend_from_slice(&chunk);
662    }
663    Ok(body)
664}
665
666/// A connected, exact-schema MCP tool exposed through `StateKnot`'s erased tool
667/// contract.
668pub struct McpRemoteTool {
669    descriptor: ToolDescriptor,
670    remote_name: Box<str>,
671    schemas: Arc<dyn McpSchemaRegistry>,
672    authorizations: AuthorizationSource,
673    endpoint: ProviderEndpoint,
674    authorization_slot: AuthorizationSlot,
675    call_gate: tokio::sync::Mutex<()>,
676    service: RunningService<RoleClient, ClientConfig>,
677}
678
679enum AuthorizationSource {
680    ContextOnly(Arc<dyn McpAuthorizationProvider>),
681    Approved(McpToolApproval),
682}
683
684fn forbidden_approved_tool_extension(tool: &Value) -> bool {
685    fn has_header(value: &Value) -> bool {
686        match value {
687            Value::Object(fields) => {
688                fields.contains_key("x-mcp-header") || fields.values().any(has_header)
689            }
690            Value::Array(values) => values.iter().any(has_header),
691            _ => false,
692        }
693    }
694    tool.get("inputSchema").is_some_and(has_header)
695        || tool
696            .pointer("/execution/taskSupport")
697            .is_some_and(|value| value != "forbidden")
698}
699
700fn verify_approved_catalog(
701    name: &str,
702    digest: Digest,
703    body: &[u8],
704) -> Result<(), StreamableHttpError<StrictHttpError>> {
705    // Validate raw discovery before the SDK can discard extension fields.
706    let raw: Value = serde_json::from_slice(body)?;
707    if let Some(tools) = raw.pointer("/result/tools").and_then(Value::as_array) {
708        for tool in tools {
709            if tool.get("name").and_then(Value::as_str) == Some(name)
710                && (mcp_tool_descriptor_digest(tool).ok() != Some(digest)
711                    || forbidden_approved_tool_extension(tool))
712            {
713                return Err(StreamableHttpError::UnexpectedServerResponse(
714                    "MCP Tool does not match its approved execution profile".into(),
715                ));
716            }
717        }
718    }
719    Ok(())
720}
721
722impl McpRemoteTool {
723    /// Connects, performs strict modern discovery, verifies server identity,
724    /// scans a bounded catalog, and freezes exact input/output schema bytes.
725    ///
726    /// The endpoint is never contacted again for discovery during tool calls.
727    /// A server upgrade therefore requires constructing and registering a new
728    /// exact adapter binding.
729    ///
730    /// # Errors
731    ///
732    /// Returns a closed build failure for unsafe descriptor semantics,
733    /// unavailable local schemas, authorization failure, timeout, protocol
734    /// downgrade, identity/schema drift, or bounded catalog exhaustion.
735    #[allow(clippy::too_many_arguments)]
736    pub async fn connect(
737        descriptor: ToolDescriptor,
738        remote_name: impl Into<String>,
739        endpoint: ProviderEndpoint,
740        expected_server: McpServerIdentity,
741        schemas: Arc<dyn McpSchemaRegistry>,
742        authorizations: Arc<dyn McpAuthorizationProvider>,
743        options: McpHttpOptions,
744    ) -> Result<Self, McpRemoteToolBuildError> {
745        Self::connect_inner(
746            descriptor,
747            remote_name.into(),
748            endpoint,
749            expected_server,
750            schemas,
751            AuthorizationSource::ContextOnly(authorizations),
752            options,
753        )
754        .await
755    }
756
757    /// Connects a reviewed remote Tool with mandatory input-aware authorization.
758    ///
759    /// Verifies the complete raw descriptor pin, including unknown extensions,
760    /// and rejects input-to-header promotion and Task execution. Every call is
761    /// authorized after local schema validation and queue acquisition, before
762    /// installing credentials or dispatching. Use through the durable executor;
763    /// an absent durable origin event is rejected before policy evaluation.
764    ///
765    /// No remote fencing, exactly-once side effects, or external spend metering
766    /// is implied. An uncertain dispatched write still requires reconciliation.
767    /// Existing `connect` remains the explicit context-only compatibility API.
768    #[allow(clippy::too_many_arguments)]
769    pub async fn connect_authorized(
770        descriptor: ToolDescriptor,
771        remote_name: impl Into<String>,
772        endpoint: ProviderEndpoint,
773        expected_server: McpServerIdentity,
774        schemas: Arc<dyn McpSchemaRegistry>,
775        approval: McpToolApproval,
776        options: McpHttpOptions,
777    ) -> Result<Self, McpRemoteToolBuildError> {
778        Self::connect_inner(
779            descriptor,
780            remote_name.into(),
781            endpoint,
782            expected_server,
783            schemas,
784            AuthorizationSource::Approved(approval),
785            options,
786        )
787        .await
788    }
789
790    #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
791    async fn connect_inner(
792        descriptor: ToolDescriptor,
793        remote_name: String,
794        endpoint: ProviderEndpoint,
795        expected_server: McpServerIdentity,
796        schemas: Arc<dyn McpSchemaRegistry>,
797        authorizations: AuthorizationSource,
798        options: McpHttpOptions,
799    ) -> Result<Self, McpRemoteToolBuildError> {
800        validate_remote_tool_name(&remote_name)?;
801        if descriptor.semantics().requires_idempotency_key() {
802            return Err(McpRemoteToolBuildError::RequiredIdempotencyKeyUnsupported);
803        }
804        if descriptor.invocation().supports_progress_events() {
805            return Err(McpRemoteToolBuildError::ProgressUnsupported);
806        }
807        let local_input = schemas
808            .canonical_schema_bytes(descriptor.input_schema())
809            .ok_or(McpRemoteToolBuildError::InputSchemaUnavailable)?
810            .to_vec();
811        let local_output = schemas
812            .canonical_schema_bytes(descriptor.output_schema())
813            .ok_or(McpRemoteToolBuildError::OutputSchemaUnavailable)?
814            .to_vec();
815        let url = endpoint
816            .join("")
817            .map_err(McpRemoteToolBuildError::Endpoint)?;
818        let client =
819            build_client(options.transport()).map_err(|_| McpRemoteToolBuildError::HttpClient)?;
820        let authorization_slot = AuthorizationSlot::anonymous();
821        let http_client = StrictJsonHttpClient {
822            client,
823            authorization: authorization_slot.clone(),
824            approved_tool: match &authorizations {
825                AuthorizationSource::Approved(approval) => {
826                    Some((remote_name.clone(), approval.digest))
827                }
828                AuthorizationSource::ContextOnly(_) => None,
829            },
830            maximum_request_bytes: options.transport().maximum_request_bytes(),
831            maximum_response_bytes: options.transport().maximum_response_bytes(),
832        };
833        let mut transport_config =
834            StreamableHttpClientTransportConfig::with_uri(Arc::<str>::from(url.as_str()));
835        transport_config.retry_config = Arc::new(NeverRetry::default());
836        transport_config.channel_buffer_capacity = 8;
837        transport_config.max_concurrent_requests = 1;
838        transport_config.control_request_timeout = options.shutdown_timeout();
839        transport_config.session_recovery_timeout = options.shutdown_timeout();
840        transport_config.allow_stateless = true;
841        transport_config.auth_header = None;
842        transport_config.custom_headers = HashMap::new();
843        transport_config.max_sse_event_size = options.transport().maximum_response_bytes();
844        transport_config.reinit_on_expired_session = false;
845        let transport = StreamableHttpClientTransport::with_client(http_client, transport_config);
846        let startup_deadline = tokio::time::Instant::now() + options.startup_timeout();
847        let startup_authorization = startup_wait(
848            startup_deadline,
849            match &authorizations {
850                AuthorizationSource::ContextOnly(source) => source.resolve_startup(&descriptor),
851                AuthorizationSource::Approved(approval) => {
852                    approval.authorizer.resolve_startup(&descriptor)
853                }
854            },
855        )
856        .await??;
857        authorization_slot
858            .replace(startup_authorization)
859            .map_err(|_| McpRemoteToolBuildError::AuthorizationState)?;
860        let _authorization_reset = AuthorizationReset(&authorization_slot);
861
862        let client_info = ClientConfig::new(
863            ClientCapabilities::default(),
864            Implementation::new("stateknot", env!("CARGO_PKG_VERSION")),
865        )
866        .with_protocol_version(MCP_PROTOCOL_VERSION.clone());
867        let mut service = startup_wait(
868            startup_deadline,
869            client_info.serve_with_lifecycle(
870                transport,
871                ClientLifecycleMode::Discover {
872                    preferred_versions: vec![MCP_PROTOCOL_VERSION.clone()],
873                },
874            ),
875        )
876        .await?
877        .map_err(|_| McpRemoteToolBuildError::DiscoveryProtocol)?;
878
879        let verification = verify_remote_binding(
880            &service,
881            startup_deadline,
882            &expected_server,
883            &remote_name,
884            &local_input,
885            &local_output,
886            options,
887        )
888        .await;
889        if let Err(error) = verification {
890            let _ = service.close_with_timeout(options.shutdown_timeout()).await;
891            return Err(error);
892        }
893
894        Ok(Self {
895            descriptor,
896            remote_name: remote_name.into_boxed_str(),
897            schemas,
898            authorizations,
899            endpoint,
900            authorization_slot: authorization_slot.clone(),
901            call_gate: tokio::sync::Mutex::new(()),
902            service,
903        })
904    }
905
906    fn preparation_error(
907        &self,
908        context: &ToolContext,
909        category: FailureCategory,
910        code: &'static str,
911        message: &'static str,
912        retry: RetryAdvice,
913    ) -> ToolError {
914        self.error(
915            context,
916            ToolErrorPhase::Preparation,
917            category,
918            code,
919            message,
920            retry,
921            effect_before_dispatch(self.descriptor.semantics().risk()),
922        )
923    }
924
925    fn dispatched_error(
926        &self,
927        context: &ToolContext,
928        read_category: FailureCategory,
929        read_code: &'static str,
930        read_message: &'static str,
931        read_retry: RetryAdvice,
932    ) -> ToolError {
933        if self.descriptor.semantics().risk() == ToolRisk::ReadOnly {
934            self.error(
935                context,
936                ToolErrorPhase::Execution,
937                read_category,
938                read_code,
939                read_message,
940                read_retry,
941                ToolExternalEffect::NotApplicable,
942            )
943        } else {
944            self.error(
945                context,
946                ToolErrorPhase::Execution,
947                FailureCategory::AmbiguousExternalOutcome,
948                "call.outcome_unknown",
949                "The MCP write may have been applied; reconcile it before recovery.",
950                RetryAdvice::ReconcileFirst,
951                ToolExternalEffect::Unknown,
952            )
953        }
954    }
955
956    fn invalid_result(&self, context: &ToolContext) -> ToolError {
957        self.error(
958            context,
959            ToolErrorPhase::Result,
960            FailureCategory::DataCorruption,
961            "result.invalid",
962            "The MCP server returned a result outside the pinned tool contract.",
963            RetryAdvice::Never,
964            effect_after_success(self.descriptor.semantics().risk()),
965        )
966    }
967
968    #[allow(clippy::too_many_arguments)]
969    fn error(
970        &self,
971        context: &ToolContext,
972        phase: ToolErrorPhase,
973        category: FailureCategory,
974        code: &'static str,
975        message: &'static str,
976        retry: RetryAdvice,
977        effect: ToolExternalEffect,
978    ) -> ToolError {
979        let failure = Failure::new(
980            FailureId::generate(),
981            category,
982            FailureCode::new(code).expect("MCP failure codes are valid constants"),
983            FailureOrigin::new("protocol.mcp").expect("MCP failure origin is valid"),
984            FailureMessage::new(message).expect("MCP public failure messages are valid"),
985            retry,
986        )
987        .expect("MCP failure category and retry advice are coherent");
988        ToolError::new(
989            failure,
990            phase,
991            effect,
992            ToolErrorProvenance::for_invocation(context, &self.descriptor),
993        )
994        .expect("MCP phase, risk evidence, and failure category are coherent")
995    }
996
997    #[allow(clippy::too_many_lines)]
998    async fn call_inner(
999        &self,
1000        context: ToolContext,
1001        input: ToolInput,
1002    ) -> Result<ToolResult, ToolError> {
1003        input
1004            .validate_for(&context, &self.descriptor)
1005            .map_err(|_| {
1006                self.preparation_error(
1007                    &context,
1008                    FailureCategory::InvalidInput,
1009                    "input.binding_invalid",
1010                    "The MCP tool input does not match this invocation binding.",
1011                    RetryAdvice::Never,
1012                )
1013            })?;
1014        self.schemas
1015            .validate(self.descriptor.input_schema(), input.value())
1016            .map_err(|_| {
1017                self.preparation_error(
1018                    &context,
1019                    FailureCategory::InvalidInput,
1020                    "input.schema_rejected",
1021                    "The MCP tool input failed its pinned schema.",
1022                    RetryAdvice::Never,
1023                )
1024            })?;
1025
1026        let _call_guard = wait_for_tool(&context, self.call_gate.lock())
1027            .await
1028            .map_err(|reason| self.stop_before_dispatch(&context, reason))?;
1029        let authorization_future = match &self.authorizations {
1030            AuthorizationSource::ContextOnly(source) => source.resolve_attempt(&context),
1031            AuthorizationSource::Approved(approval) => {
1032                if self.service.is_closed() {
1033                    return Err(self.preparation_error(
1034                        &context,
1035                        FailureCategory::DependencyUnavailable,
1036                        "authorization.binding_retired",
1037                        "The approved MCP binding must be rebuilt before further calls.",
1038                        RetryAdvice::Never,
1039                    ));
1040                }
1041                if context.origin_event_id().is_none() {
1042                    return Err(self.preparation_error(
1043                        &context,
1044                        FailureCategory::PermissionDenied,
1045                        "authorization.durable_origin_required",
1046                        "An approved MCP call requires a durable attempt origin.",
1047                        RetryAdvice::Never,
1048                    ));
1049                }
1050                approval
1051                    .authorizer
1052                    .authorize_call(McpToolAuthorizationRequest {
1053                        context: &context,
1054                        descriptor: &self.descriptor,
1055                        input: &input,
1056                        endpoint: &self.endpoint,
1057                        remote_name: &self.remote_name,
1058                        digest: approval.digest,
1059                    })
1060            }
1061        };
1062        let authorization = wait_for_tool(&context, authorization_future)
1063            .await
1064            .map_err(|reason| self.stop_before_dispatch(&context, reason))?
1065            .map_err(|error| match error {
1066                McpAuthorizationError::Unavailable => self.preparation_error(
1067                    &context,
1068                    FailureCategory::DependencyUnavailable,
1069                    "authorization.unavailable",
1070                    "The MCP authorization source is temporarily unavailable.",
1071                    RetryAdvice::SafeAfter {
1072                        delay: DurationMillis::new(250).expect("positive constant"),
1073                    },
1074                ),
1075                McpAuthorizationError::PermissionDenied => self.preparation_error(
1076                    &context,
1077                    FailureCategory::PermissionDenied,
1078                    "authorization.permission_denied",
1079                    "MCP authorization access was denied.",
1080                    RetryAdvice::Never,
1081                ),
1082            })?;
1083        self.authorization_slot
1084            .replace(authorization)
1085            .map_err(|_| {
1086                self.preparation_error(
1087                    &context,
1088                    FailureCategory::Internal,
1089                    "authorization.state_unavailable",
1090                    "The MCP authorization state is unavailable.",
1091                    RetryAdvice::Never,
1092                )
1093            })?;
1094        let _authorization_reset = AuthorizationReset(&self.authorization_slot);
1095
1096        let arguments = input
1097            .value()
1098            .as_value()
1099            .as_object()
1100            .cloned()
1101            .expect("ToolInput construction requires an object root");
1102        let params =
1103            CallToolRequestParams::new(self.remote_name.to_string()).with_arguments(arguments);
1104        let mut dispatch_guard = ApprovedDispatchGuard(
1105            matches!(self.authorizations, AuthorizationSource::Approved(_))
1106                .then(|| self.service.cancellation_token()),
1107        );
1108        let response = wait_for_tool(&context, self.service.call_tool_once(params))
1109            .await
1110            .map_err(|reason| self.stop_after_dispatch(&context, reason))?
1111            .map_err(|_| {
1112                self.dispatched_error(
1113                    &context,
1114                    FailureCategory::DependencyUnavailable,
1115                    "call.protocol_failed",
1116                    "The MCP tool call failed at the protocol boundary.",
1117                    RetryAdvice::SafeAfter {
1118                        delay: DurationMillis::new(250).expect("positive constant"),
1119                    },
1120                )
1121            })?;
1122        let CallToolResponse::Complete(result) = response else {
1123            return Err(self.dispatched_error(
1124                &context,
1125                FailureCategory::Unsupported,
1126                "call.incomplete_unsupported",
1127                "The MCP server returned an unsupported incomplete result.",
1128                RetryAdvice::Never,
1129            ));
1130        };
1131        if !result
1132            .result_type
1133            .as_ref()
1134            .is_some_and(rmcp::model::ResultType::is_complete)
1135        {
1136            return Err(self.invalid_result(&context));
1137        }
1138        if result.is_error.unwrap_or(false) {
1139            return Err(self.dispatched_error(
1140                &context,
1141                FailureCategory::DependencyUnavailable,
1142                "call.remote_tool_error",
1143                "The remote MCP tool reported an execution failure.",
1144                RetryAdvice::Never,
1145            ));
1146        }
1147        if result
1148            .content
1149            .iter()
1150            .any(|content| content.as_text().is_none())
1151        {
1152            return Err(self.invalid_result(&context));
1153        }
1154        let structured = result
1155            .structured_content
1156            .ok_or_else(|| self.invalid_result(&context))?;
1157        let output =
1158            BoundedJson::try_from_value(structured).map_err(|_| self.invalid_result(&context))?;
1159        self.schemas
1160            .validate(self.descriptor.output_schema(), &output)
1161            .map_err(|_| self.invalid_result(&context))?;
1162        let result =
1163            ToolResult::for_invocation(&context, &self.descriptor, output, ToolArtifacts::empty());
1164        result
1165            .validate_for(&context, &self.descriptor)
1166            .map_err(|_| self.invalid_result(&context))?;
1167        dispatch_guard.0 = None;
1168        Ok(result)
1169    }
1170
1171    fn stop_before_dispatch(&self, context: &ToolContext, reason: ToolStopReason) -> ToolError {
1172        let (category, code, message) = stop_failure(reason);
1173        self.preparation_error(context, category, code, message, RetryAdvice::Never)
1174    }
1175
1176    fn stop_after_dispatch(&self, context: &ToolContext, reason: ToolStopReason) -> ToolError {
1177        let (category, code, message) = stop_failure(reason);
1178        self.dispatched_error(context, category, code, message, RetryAdvice::Never)
1179    }
1180}
1181
1182impl ErasedTool for McpRemoteTool {
1183    fn descriptor(&self) -> &ToolDescriptor {
1184        &self.descriptor
1185    }
1186
1187    fn call(
1188        &self,
1189        context: ToolContext,
1190        input: ToolInput,
1191    ) -> BoxFuture<'_, Result<ToolResult, ToolError>> {
1192        Box::pin(self.call_inner(context, input))
1193    }
1194}
1195
1196impl fmt::Debug for McpRemoteTool {
1197    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1198        formatter
1199            .debug_struct("McpRemoteTool")
1200            .field("descriptor", &self.descriptor)
1201            .field("remote_name", &self.remote_name)
1202            .field("connected", &!self.service.is_closed())
1203            .finish_non_exhaustive()
1204    }
1205}
1206
1207async fn verify_remote_binding(
1208    service: &RunningService<RoleClient, ClientConfig>,
1209    deadline: tokio::time::Instant,
1210    expected_server: &McpServerIdentity,
1211    remote_name: &str,
1212    local_input: &[u8],
1213    local_output: &[u8],
1214    options: McpHttpOptions,
1215) -> Result<(), McpRemoteToolBuildError> {
1216    let peer = service
1217        .peer_info()
1218        .ok_or(McpRemoteToolBuildError::MissingPeerInfo)?;
1219    if peer.protocol_version != MCP_PROTOCOL_VERSION {
1220        return Err(McpRemoteToolBuildError::ProtocolVersionMismatch);
1221    }
1222    if peer.capabilities.tools.is_none() {
1223        return Err(McpRemoteToolBuildError::ToolsCapabilityUnavailable);
1224    }
1225    let implementation = peer
1226        .server_info
1227        .as_ref()
1228        .ok_or(McpRemoteToolBuildError::ServerIdentityUnavailable)?;
1229    if !expected_server.matches(implementation) {
1230        return Err(McpRemoteToolBuildError::ServerIdentityMismatch);
1231    }
1232
1233    let mut cursor = None;
1234    let mut seen_cursors = HashSet::new();
1235    let mut seen_names = HashSet::new();
1236    let mut discovered = 0usize;
1237    let mut selected = None;
1238    let mut catalog_complete = false;
1239    for _ in 0..options.maximum_discovery_pages() {
1240        let result = startup_wait(
1241            deadline,
1242            service.list_tools(Some(
1243                PaginatedRequestParams::default().with_cursor(cursor.clone()),
1244            )),
1245        )
1246        .await?
1247        .map_err(|_| McpRemoteToolBuildError::ToolCatalogProtocol)?;
1248        if !result
1249            .result_type
1250            .as_ref()
1251            .is_some_and(rmcp::model::ResultType::is_complete)
1252            || result.ttl_ms.is_none()
1253            || result.cache_scope.is_none()
1254        {
1255            return Err(McpRemoteToolBuildError::ToolCatalogProtocol);
1256        }
1257        discovered = discovered
1258            .checked_add(result.tools.len())
1259            .ok_or(McpRemoteToolBuildError::ToolCatalogTooLarge)?;
1260        if discovered > options.maximum_discovered_tools() {
1261            return Err(McpRemoteToolBuildError::ToolCatalogTooLarge);
1262        }
1263        for tool in result.tools {
1264            let name = tool.name.to_string();
1265            if !seen_names.insert(name.clone()) {
1266                return Err(McpRemoteToolBuildError::DuplicateRemoteTool);
1267            }
1268            if name == remote_name {
1269                selected = Some(tool);
1270            }
1271        }
1272        let Some(next) = result.next_cursor else {
1273            catalog_complete = true;
1274            break;
1275        };
1276        if next.is_empty() || !seen_cursors.insert(next.clone()) {
1277            return Err(McpRemoteToolBuildError::InvalidPagination);
1278        }
1279        cursor = Some(next);
1280    }
1281    if !catalog_complete {
1282        return Err(McpRemoteToolBuildError::ToolCatalogPageLimit);
1283    }
1284    let selected = selected.ok_or(McpRemoteToolBuildError::RemoteToolUnavailable)?;
1285    verify_remote_schemas(&selected, local_input, local_output)
1286}
1287
1288fn verify_remote_schemas(
1289    tool: &Tool,
1290    local_input: &[u8],
1291    local_output: &[u8],
1292) -> Result<(), McpRemoteToolBuildError> {
1293    let input =
1294        serde_json_canonicalizer::to_vec(&Value::Object(tool.input_schema.as_ref().clone()))
1295            .map_err(|_| McpRemoteToolBuildError::RemoteSchemaInvalid)?;
1296    if input != local_input {
1297        return Err(McpRemoteToolBuildError::InputSchemaMismatch);
1298    }
1299    let output = tool
1300        .output_schema
1301        .as_ref()
1302        .ok_or(McpRemoteToolBuildError::RemoteOutputSchemaUnavailable)?;
1303    let output = serde_json_canonicalizer::to_vec(&Value::Object(output.as_ref().clone()))
1304        .map_err(|_| McpRemoteToolBuildError::RemoteSchemaInvalid)?;
1305    if output != local_output {
1306        return Err(McpRemoteToolBuildError::OutputSchemaMismatch);
1307    }
1308    Ok(())
1309}
1310
1311async fn startup_wait<T, F>(
1312    deadline: tokio::time::Instant,
1313    future: F,
1314) -> Result<T, McpRemoteToolBuildError>
1315where
1316    F: std::future::Future<Output = T>,
1317{
1318    tokio::time::timeout_at(deadline, future)
1319        .await
1320        .map_err(|_| McpRemoteToolBuildError::StartupTimeout)
1321}
1322
1323async fn wait_for_tool<T, F>(context: &ToolContext, future: F) -> Result<T, ToolStopReason>
1324where
1325    F: std::future::Future<Output = T>,
1326{
1327    if let Some(reason) = context.stop_reason_at(Instant::now()) {
1328        return Err(reason);
1329    }
1330    let deadline = tokio::time::Instant::from_std(context.deadline_instant());
1331    tokio::select! {
1332        biased;
1333        () = context.cancellation().cancelled() => Err(ToolStopReason::Cancelled),
1334        () = tokio::time::sleep_until(deadline) => {
1335            Err(context.stop_reason_at(Instant::now()).unwrap_or(ToolStopReason::DeadlineExceeded))
1336        }
1337        output = future => Ok(output),
1338    }
1339}
1340
1341fn validate_remote_tool_name(value: &str) -> Result<(), McpRemoteToolBuildError> {
1342    const MAX_BYTES: usize = 256;
1343    if value.is_empty()
1344        || value.len() > MAX_BYTES
1345        || value.trim() != value
1346        || value.chars().any(char::is_control)
1347    {
1348        return Err(McpRemoteToolBuildError::InvalidRemoteToolName);
1349    }
1350    Ok(())
1351}
1352
1353const fn effect_before_dispatch(risk: ToolRisk) -> ToolExternalEffect {
1354    match risk {
1355        ToolRisk::ReadOnly => ToolExternalEffect::NotApplicable,
1356        ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite => ToolExternalEffect::NotStarted,
1357    }
1358}
1359
1360const fn effect_after_success(risk: ToolRisk) -> ToolExternalEffect {
1361    match risk {
1362        ToolRisk::ReadOnly => ToolExternalEffect::NotApplicable,
1363        ToolRisk::IdempotentWrite | ToolRisk::NonIdempotentWrite => ToolExternalEffect::Applied,
1364    }
1365}
1366
1367const fn stop_failure(reason: ToolStopReason) -> (FailureCategory, &'static str, &'static str) {
1368    match reason {
1369        ToolStopReason::Cancelled => (
1370            FailureCategory::Cancelled,
1371            "call.cancelled",
1372            "The MCP tool attempt was cancelled.",
1373        ),
1374        ToolStopReason::DeadlineExceeded => (
1375            FailureCategory::DeadlineExceeded,
1376            "call.deadline_exceeded",
1377            "The MCP tool attempt exceeded its deadline.",
1378        ),
1379        _ => (
1380            FailureCategory::Internal,
1381            "call.unknown_stop_reason",
1382            "The MCP tool attempt stopped for an unsupported reason.",
1383        ),
1384    }
1385}
1386
1387/// Closed failure while constructing an exact MCP remote-tool binding.
1388#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1389#[non_exhaustive]
1390pub enum McpRemoteToolBuildError {
1391    /// The configured remote tool name was not a bounded printable value.
1392    #[error("MCP remote tool name is invalid")]
1393    InvalidRemoteToolName,
1394    /// Generic MCP cannot inject `StateKnot`'s durable idempotency key safely.
1395    #[error("MCP binding does not support descriptor-required idempotency keys")]
1396    RequiredIdempotencyKeyUnsupported,
1397    /// This adapter version does not bridge MCP progress into the durable sink.
1398    #[error("MCP binding does not support declared progress events")]
1399    ProgressUnsupported,
1400    /// The exact local input schema was absent.
1401    #[error("MCP input schema is unavailable in the local registry")]
1402    InputSchemaUnavailable,
1403    /// The exact local output schema was absent.
1404    #[error("MCP output schema is unavailable in the local registry")]
1405    OutputSchemaUnavailable,
1406    /// Endpoint normalization failed.
1407    #[error("invalid MCP endpoint: {0}")]
1408    Endpoint(ProviderEndpointError),
1409    /// The bounded, no-redirect HTTP client could not be built.
1410    #[error("MCP HTTP client construction failed")]
1411    HttpClient,
1412    /// Startup authorization was unavailable or denied.
1413    #[error(transparent)]
1414    Authorization(#[from] McpAuthorizationError),
1415    /// Shared authorization state could not be installed.
1416    #[error("MCP authorization state is unavailable")]
1417    AuthorizationState,
1418    /// The complete discovery deadline elapsed.
1419    #[error("MCP startup discovery timed out")]
1420    StartupTimeout,
1421    /// `server/discover` failed or returned an unsupported shape.
1422    #[error("MCP modern discovery failed")]
1423    DiscoveryProtocol,
1424    /// Discovery did not retain peer information.
1425    #[error("MCP discovery returned no peer information")]
1426    MissingPeerInfo,
1427    /// The negotiated version was not exactly 2026-07-28.
1428    #[error("MCP protocol version does not match 2026-07-28")]
1429    ProtocolVersionMismatch,
1430    /// The server did not advertise tools.
1431    #[error("MCP server does not advertise the tools capability")]
1432    ToolsCapabilityUnavailable,
1433    /// Modern discovery omitted implementation identity.
1434    #[error("MCP server identity is unavailable")]
1435    ServerIdentityUnavailable,
1436    /// The discovered implementation identity drifted.
1437    #[error("MCP server identity does not match the pinned binding")]
1438    ServerIdentityMismatch,
1439    /// A tools/list exchange failed or omitted required modern fields.
1440    #[error("MCP tool catalog response is invalid")]
1441    ToolCatalogProtocol,
1442    /// Catalog entries exceeded the configured bound.
1443    #[error("MCP tool catalog exceeds its tool limit")]
1444    ToolCatalogTooLarge,
1445    /// Catalog pagination did not terminate within its bound.
1446    #[error("MCP tool catalog exceeds its page limit")]
1447    ToolCatalogPageLimit,
1448    /// A cursor was empty or repeated.
1449    #[error("MCP tool catalog pagination is invalid")]
1450    InvalidPagination,
1451    /// A tool name appeared more than once.
1452    #[error("MCP tool catalog contains a duplicate name")]
1453    DuplicateRemoteTool,
1454    /// The exact configured tool was not present.
1455    #[error("MCP remote tool is unavailable")]
1456    RemoteToolUnavailable,
1457    /// Remote schema canonicalization failed.
1458    #[error("MCP remote schema is invalid")]
1459    RemoteSchemaInvalid,
1460    /// The remote input schema differed from the local pin.
1461    #[error("MCP remote input schema does not match the local pin")]
1462    InputSchemaMismatch,
1463    /// The remote tool omitted an output schema.
1464    #[error("MCP remote output schema is unavailable")]
1465    RemoteOutputSchemaUnavailable,
1466    /// The remote output schema differed from the local pin.
1467    #[error("MCP remote output schema does not match the local pin")]
1468    OutputSchemaMismatch,
1469}
1470
1471#[cfg(test)]
1472mod tests {
1473    use super::*;
1474
1475    #[test]
1476    fn identities_and_options_are_hard_bounded() {
1477        assert!(McpServerIdentity::new("server", "1.0.0").is_ok());
1478        assert_eq!(
1479            McpServerIdentity::new(" server", "1.0.0"),
1480            Err(McpServerIdentityError::BoundaryWhitespace)
1481        );
1482        assert_eq!(
1483            McpHttpOptions::new(
1484                ProviderHttpOptions::default(),
1485                Duration::ZERO,
1486                Duration::from_secs(1),
1487                1,
1488                1,
1489            ),
1490            Err(McpHttpOptionsError::ZeroTimeout)
1491        );
1492    }
1493
1494    #[test]
1495    fn reserved_headers_and_content_types_fail_closed() {
1496        assert!(is_reserved_header(&header::AUTHORIZATION));
1497        assert!(!is_reserved_header(&HeaderName::from_static("mcp-method")));
1498        assert!(is_json_content_type("application/json; charset=utf-8"));
1499        assert!(!is_json_content_type("text/event-stream"));
1500    }
1501
1502    #[test]
1503    fn credentials_are_redacted() {
1504        let value = "mcp-production-secret";
1505        let authorization = McpAuthorization::Bearer(ApiKey::new(value).unwrap());
1506        assert!(!format!("{authorization:?}").contains(value));
1507        assert!(
1508            !format!(
1509                "{:?}",
1510                StaticMcpBearerAuthorization::new(ApiKey::new(value).unwrap())
1511            )
1512            .contains(value)
1513        );
1514    }
1515}