Skip to main content

stateknot_integrations/
mcp_server_tool.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Immutable, schema-validating MCP 2026-07-28 Tool server application layer.
5//!
6//! The public API in this module is owned by `StateKnot`. The official MCP Rust
7//! SDK remains a private wire adapter so an SDK release cannot silently become
8//! the framework's domain model. Definitions and JSON Schema validators are
9//! frozen at startup; request dispatch performs decoded authorization, bounded
10//! input validation, handler execution, bounded output validation, and no
11//! network schema retrieval.
12
13use std::{borrow::Cow, collections::BTreeMap, fmt, sync::Arc, time::Duration};
14
15use base64::{Engine as _, engine::general_purpose::STANDARD};
16use jsonschema::Validator;
17use rmcp::{
18    ErrorData, RoleServer, ServerHandler,
19    model::{
20        CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ClientCapabilities,
21        ContentBlock, DiscoverResult, ElicitationCapability, Implementation, InputRequest,
22        InputRequiredResult, ListToolsResult, PaginatedRequestParams, ProgressNotificationParam,
23        ProtocolVersion, RequestStateCodec, RootsCapabilities, SamplingCapability, SealOptions,
24        ServerCapabilities, ServerConfig, Tool, ToolAnnotations,
25    },
26    service::{Peer, RequestContext},
27};
28use serde_json::{Map, Value};
29use stateknot_core::{BoxFuture, Digest};
30use thiserror::Error;
31use tokio_util::sync::CancellationToken;
32
33use crate::{McpServerPrincipal, mcp_server_principal};
34
35const JSON_SCHEMA_2020_12: &str = "https://json-schema.org/draft/2020-12/schema";
36const MEBIBYTE: usize = 1024 * 1024;
37const MAX_TOOL_NAME_BYTES: usize = 64;
38const MAX_DISPLAY_BYTES: usize = 16 * 1024;
39const MAX_SCOPE_COUNT: usize = 128;
40const MAX_SCOPE_BYTES: usize = 256;
41const MAX_CONTENT_BLOCK_BYTES: usize = 16 * MEBIBYTE;
42const MAX_BINARY_CONTENT_BYTES: usize = 12 * MEBIBYTE;
43const MAX_TEXT_CONTENT_BYTES: usize = 4 * MEBIBYTE;
44const MAX_CONTENT_BLOCKS: usize = 256;
45const MAX_STRUCTURED_CONTENT_BYTES: usize = 16 * MEBIBYTE;
46const MAX_TOOL_RESULT_BYTES: usize = 32 * MEBIBYTE;
47const MAX_INPUT_REQUEST_BYTES: usize = 2 * MEBIBYTE;
48const MAX_INPUT_REQUESTS: usize = 128;
49const MAX_INPUT_REQUEST_ID_BYTES: usize = 128;
50const MAX_REQUEST_STATE_BYTES: usize = 128 * 1024;
51const MAX_REQUEST_STATE_PAYLOAD_BYTES: usize = 64 * 1024;
52const MAX_REQUEST_STATE_BINDING_BYTES: usize = 16 * 1024;
53const MAX_REQUEST_STATE_TTL: Duration = Duration::from_secs(24 * 60 * 60);
54const MAX_PROGRESS_MESSAGE_BYTES: usize = 2048;
55
56/// MCP cache scope without exposing the wire SDK type.
57#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
58#[non_exhaustive]
59pub enum McpServerCacheScope {
60    /// The catalog is identical across authorization contexts.
61    Public,
62    /// The catalog is scoped to the requesting principal.
63    #[default]
64    Private,
65}
66
67impl From<McpServerCacheScope> for CacheScope {
68    fn from(value: McpServerCacheScope) -> Self {
69        match value {
70            McpServerCacheScope::Public => Self::Public,
71            McpServerCacheScope::Private => Self::Private,
72        }
73    }
74}
75
76/// Non-authoritative MCP Tool annotations.
77///
78/// These values are hints for clients. `StateKnot` never uses them as policy or
79/// side-effect evidence; authoritative policy belongs in the decoded
80/// authorization boundary.
81#[derive(Clone, Debug, Default, Eq, PartialEq)]
82pub struct McpServerToolAnnotations {
83    title: Option<Box<str>>,
84    read_only_hint: Option<bool>,
85    destructive_hint: Option<bool>,
86    idempotent_hint: Option<bool>,
87    open_world_hint: Option<bool>,
88}
89
90impl McpServerToolAnnotations {
91    /// Creates annotations with no hints.
92    #[must_use]
93    pub const fn new() -> Self {
94        Self {
95            title: None,
96            read_only_hint: None,
97            destructive_hint: None,
98            idempotent_hint: None,
99            open_world_hint: None,
100        }
101    }
102
103    /// Adds a bounded display title.
104    pub fn with_title(
105        mut self,
106        title: impl Into<String>,
107    ) -> Result<Self, McpServerToolDefinitionError> {
108        let title = title.into();
109        validate_display(&title)?;
110        self.title = Some(title.into_boxed_str());
111        Ok(self)
112    }
113
114    /// Sets the protocol read-only hint.
115    #[must_use]
116    pub const fn with_read_only_hint(mut self, value: bool) -> Self {
117        self.read_only_hint = Some(value);
118        self
119    }
120
121    /// Sets the protocol destructive hint.
122    #[must_use]
123    pub const fn with_destructive_hint(mut self, value: bool) -> Self {
124        self.destructive_hint = Some(value);
125        self
126    }
127
128    /// Sets the protocol idempotent hint.
129    #[must_use]
130    pub const fn with_idempotent_hint(mut self, value: bool) -> Self {
131        self.idempotent_hint = Some(value);
132        self
133    }
134
135    /// Sets the protocol open-world hint.
136    #[must_use]
137    pub const fn with_open_world_hint(mut self, value: bool) -> Self {
138        self.open_world_hint = Some(value);
139        self
140    }
141
142    fn to_protocol(&self) -> ToolAnnotations {
143        ToolAnnotations::from_raw(
144            self.title.as_deref().map(str::to_owned),
145            self.read_only_hint,
146            self.destructive_hint,
147            self.idempotent_hint,
148            self.open_world_hint,
149        )
150    }
151}
152
153/// Immutable StateKnot-owned MCP Tool definition.
154#[derive(Clone)]
155pub struct McpServerToolDefinition {
156    name: Arc<str>,
157    title: Option<Arc<str>>,
158    description: Option<Arc<str>>,
159    input_schema: Arc<Value>,
160    output_schema: Option<Arc<Value>>,
161    annotations: Option<McpServerToolAnnotations>,
162    required_scopes: Arc<[Box<str>]>,
163    canonical_schema_bytes: usize,
164}
165
166impl McpServerToolDefinition {
167    /// Creates a definition after validating its name and input schema.
168    ///
169    /// JSON Schema defaults to draft 2020-12 when `$schema` is absent. If the
170    /// keyword is present it must name that exact dialect. Network `$ref`
171    /// retrieval is not attempted; unresolved references fail registry build.
172    pub fn new(
173        name: impl Into<String>,
174        input_schema: Value,
175    ) -> Result<Self, McpServerToolDefinitionError> {
176        let name = name.into();
177        validate_tool_name(&name)?;
178        let canonical_schema_bytes = validate_schema_document(&input_schema)?;
179        Ok(Self {
180            name: Arc::from(name),
181            title: None,
182            description: None,
183            input_schema: Arc::new(input_schema),
184            output_schema: None,
185            annotations: None,
186            required_scopes: Arc::from([]),
187            canonical_schema_bytes,
188        })
189    }
190
191    /// Adds a bounded human-readable title.
192    pub fn with_title(
193        mut self,
194        title: impl Into<String>,
195    ) -> Result<Self, McpServerToolDefinitionError> {
196        let title = title.into();
197        validate_display(&title)?;
198        self.title = Some(Arc::from(title));
199        Ok(self)
200    }
201
202    /// Adds a bounded human-readable description.
203    pub fn with_description(
204        mut self,
205        description: impl Into<String>,
206    ) -> Result<Self, McpServerToolDefinitionError> {
207        let description = description.into();
208        validate_display(&description)?;
209        self.description = Some(Arc::from(description));
210        Ok(self)
211    }
212
213    /// Adds and validates an output schema.
214    pub fn with_output_schema(
215        mut self,
216        output_schema: Value,
217    ) -> Result<Self, McpServerToolDefinitionError> {
218        let bytes = validate_schema_document(&output_schema)?;
219        self.canonical_schema_bytes = self
220            .canonical_schema_bytes
221            .checked_add(bytes)
222            .ok_or(McpServerToolDefinitionError::SchemaTooLarge)?;
223        if self.canonical_schema_bytes > McpServerToolRegistryLimits::HARD_MAXIMUM_SCHEMA_BYTES * 2
224        {
225            return Err(McpServerToolDefinitionError::SchemaTooLarge);
226        }
227        self.output_schema = Some(Arc::new(output_schema));
228        Ok(self)
229    }
230
231    /// Adds non-authoritative client hints.
232    #[must_use]
233    pub fn with_annotations(mut self, annotations: McpServerToolAnnotations) -> Self {
234        self.annotations = Some(annotations);
235        self
236    }
237
238    /// Requires every listed OAuth-style scope before dispatch.
239    pub fn with_required_scopes(
240        mut self,
241        scopes: impl IntoIterator<Item = impl Into<String>>,
242    ) -> Result<Self, McpServerToolDefinitionError> {
243        let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
244        if scopes.len() > MAX_SCOPE_COUNT {
245            return Err(McpServerToolDefinitionError::TooManyScopes);
246        }
247        for scope in &scopes {
248            validate_scope(scope)?;
249        }
250        scopes.sort_unstable();
251        if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
252            return Err(McpServerToolDefinitionError::DuplicateScope);
253        }
254        self.required_scopes = scopes
255            .into_iter()
256            .map(String::into_boxed_str)
257            .collect::<Vec<_>>()
258            .into();
259        Ok(self)
260    }
261
262    /// Returns the stable tool name.
263    #[must_use]
264    pub fn name(&self) -> &str {
265        &self.name
266    }
267
268    /// Returns the optional display title.
269    #[must_use]
270    pub fn title(&self) -> Option<&str> {
271        self.title.as_deref()
272    }
273
274    /// Returns the optional description.
275    #[must_use]
276    pub fn description(&self) -> Option<&str> {
277        self.description.as_deref()
278    }
279
280    /// Returns the exact input schema.
281    #[must_use]
282    pub fn input_schema(&self) -> &Value {
283        &self.input_schema
284    }
285
286    /// Returns the optional output schema.
287    #[must_use]
288    pub fn output_schema(&self) -> Option<&Value> {
289        self.output_schema.as_deref()
290    }
291
292    /// Returns required scopes in canonical ASCII order.
293    pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
294        self.required_scopes.iter().map(AsRef::as_ref)
295    }
296
297    fn to_protocol(&self) -> Tool {
298        let input = self
299            .input_schema
300            .as_object()
301            .expect("validated MCP input schema remains an object")
302            .clone();
303        let mut tool = Tool::new_with_raw(
304            self.name.to_string(),
305            self.description
306                .as_deref()
307                .map(|value| Cow::Owned(value.to_owned())),
308            input,
309        );
310        tool.title = self.title.as_deref().map(str::to_owned);
311        if let Some(output) = &self.output_schema {
312            tool = tool.with_raw_output_schema(Arc::new(
313                output
314                    .as_object()
315                    .expect("validated MCP output schema remains an object")
316                    .clone(),
317            ));
318        }
319        if let Some(annotations) = &self.annotations {
320            tool = tool.with_annotations(annotations.to_protocol());
321        }
322        tool
323    }
324}
325
326impl fmt::Debug for McpServerToolDefinition {
327    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328        formatter
329            .debug_struct("McpServerToolDefinition")
330            .field("name", &self.name)
331            .field("title", &self.title)
332            .field("description", &self.description)
333            .field("has_output_schema", &self.output_schema.is_some())
334            .field("required_scopes", &self.required_scopes)
335            .field("canonical_schema_bytes", &self.canonical_schema_bytes)
336            .finish_non_exhaustive()
337    }
338}
339
340/// Invalid MCP Tool definition.
341#[derive(Clone, Debug, Eq, Error, PartialEq)]
342#[non_exhaustive]
343pub enum McpServerToolDefinitionError {
344    /// Names must contain 1–64 characters from the SEP-986 portable grammar.
345    #[error("invalid MCP tool name")]
346    InvalidName,
347    /// A title or description was empty, padded, oversized, or contained controls.
348    #[error("invalid MCP tool display text")]
349    InvalidDisplayText,
350    /// A schema root was not a JSON object.
351    #[error("MCP tool schema root must be an object")]
352    SchemaRootNotObject,
353    /// The schema selected a dialect other than JSON Schema 2020-12.
354    #[error("MCP tool schema must use JSON Schema 2020-12")]
355    UnsupportedSchemaDialect,
356    /// The schema violated the 2020-12 meta-schema.
357    #[error("invalid MCP JSON Schema 2020-12 document: {diagnostic}")]
358    InvalidSchema {
359        /// Bounded startup diagnostic.
360        diagnostic: Box<str>,
361    },
362    /// Canonical schema bytes exceeded the implementation ceiling.
363    #[error("MCP tool schema exceeds the hard byte ceiling")]
364    SchemaTooLarge,
365    /// More than the hard required-scope count was supplied.
366    #[error("too many required MCP tool scopes")]
367    TooManyScopes,
368    /// A required scope was outside the OAuth scope-token grammar.
369    #[error("invalid required MCP tool scope")]
370    InvalidScope,
371    /// A required scope appeared more than once.
372    #[error("duplicate required MCP tool scope")]
373    DuplicateScope,
374}
375
376fn validate_tool_name(name: &str) -> Result<(), McpServerToolDefinitionError> {
377    if name.is_empty()
378        || name.len() > MAX_TOOL_NAME_BYTES
379        || !name
380            .bytes()
381            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'/' | b'-'))
382    {
383        return Err(McpServerToolDefinitionError::InvalidName);
384    }
385    Ok(())
386}
387
388fn validate_display(value: &str) -> Result<(), McpServerToolDefinitionError> {
389    if value.is_empty()
390        || value.len() > MAX_DISPLAY_BYTES
391        || value.trim() != value
392        || value.chars().any(char::is_control)
393    {
394        return Err(McpServerToolDefinitionError::InvalidDisplayText);
395    }
396    Ok(())
397}
398
399fn validate_scope(scope: &str) -> Result<(), McpServerToolDefinitionError> {
400    if scope.is_empty()
401        || scope.len() > MAX_SCOPE_BYTES
402        || scope
403            .bytes()
404            .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
405    {
406        return Err(McpServerToolDefinitionError::InvalidScope);
407    }
408    Ok(())
409}
410
411fn validate_schema_document(value: &Value) -> Result<usize, McpServerToolDefinitionError> {
412    let object = value
413        .as_object()
414        .ok_or(McpServerToolDefinitionError::SchemaRootNotObject)?;
415    if object
416        .get("$schema")
417        .and_then(Value::as_str)
418        .is_some_and(|dialect| dialect != JSON_SCHEMA_2020_12)
419    {
420        return Err(McpServerToolDefinitionError::UnsupportedSchemaDialect);
421    }
422    jsonschema::draft202012::meta::validate(value).map_err(|source| {
423        McpServerToolDefinitionError::InvalidSchema {
424            diagnostic: bounded_diagnostic(&source.to_string()),
425        }
426    })?;
427    let canonical = serde_json_canonicalizer::to_vec(value)
428        .map_err(|_| McpServerToolDefinitionError::SchemaTooLarge)?;
429    if canonical.len() > McpServerToolRegistryLimits::HARD_MAXIMUM_SCHEMA_BYTES {
430        return Err(McpServerToolDefinitionError::SchemaTooLarge);
431    }
432    Ok(canonical.len())
433}
434
435fn bounded_diagnostic(value: &str) -> Box<str> {
436    let end = value
437        .char_indices()
438        .map(|(index, _)| index)
439        .take_while(|index| *index <= 2048)
440        .last()
441        .unwrap_or(0);
442    if value.len() <= 2048 {
443        value.to_owned().into_boxed_str()
444    } else {
445        value[..end].to_owned().into_boxed_str()
446    }
447}
448
449/// Resource ceilings for one immutable Tool registry.
450#[derive(Clone, Copy, Debug, Eq, PartialEq)]
451#[allow(clippy::struct_field_names)]
452pub struct McpServerToolRegistryLimits {
453    maximum_tools: usize,
454    maximum_schema_bytes: usize,
455    maximum_total_schema_bytes: usize,
456}
457
458impl McpServerToolRegistryLimits {
459    /// Absolute tool count ceiling.
460    pub const HARD_MAXIMUM_TOOLS: usize = 4096;
461    /// Absolute canonical byte ceiling for one input or output schema.
462    pub const HARD_MAXIMUM_SCHEMA_BYTES: usize = 8 * MEBIBYTE;
463    /// Absolute aggregate schema byte ceiling.
464    pub const HARD_MAXIMUM_TOTAL_SCHEMA_BYTES: usize = 256 * MEBIBYTE;
465
466    /// Constructs explicit positive limits within hard ceilings.
467    pub const fn new(
468        maximum_tools: usize,
469        maximum_schema_bytes: usize,
470        maximum_total_schema_bytes: usize,
471    ) -> Result<Self, McpServerToolRegistryLimitsError> {
472        if maximum_tools == 0 || maximum_schema_bytes == 0 || maximum_total_schema_bytes == 0 {
473            return Err(McpServerToolRegistryLimitsError::ZeroLimit);
474        }
475        if maximum_schema_bytes > Self::HARD_MAXIMUM_SCHEMA_BYTES
476            || maximum_total_schema_bytes > Self::HARD_MAXIMUM_TOTAL_SCHEMA_BYTES
477            || maximum_tools > Self::HARD_MAXIMUM_TOOLS
478            || maximum_total_schema_bytes < maximum_schema_bytes
479        {
480            return Err(McpServerToolRegistryLimitsError::InvalidLimit);
481        }
482        Ok(Self {
483            maximum_tools,
484            maximum_schema_bytes,
485            maximum_total_schema_bytes,
486        })
487    }
488
489    /// Returns the tool count ceiling.
490    #[must_use]
491    pub const fn maximum_tools(self) -> usize {
492        self.maximum_tools
493    }
494
495    /// Returns the per-schema byte ceiling.
496    #[must_use]
497    pub const fn maximum_schema_bytes(self) -> usize {
498        self.maximum_schema_bytes
499    }
500
501    /// Returns the aggregate schema byte ceiling.
502    #[must_use]
503    pub const fn maximum_total_schema_bytes(self) -> usize {
504        self.maximum_total_schema_bytes
505    }
506}
507
508impl Default for McpServerToolRegistryLimits {
509    fn default() -> Self {
510        Self {
511            maximum_tools: 1024,
512            maximum_schema_bytes: 2 * MEBIBYTE,
513            maximum_total_schema_bytes: 64 * MEBIBYTE,
514        }
515    }
516}
517
518/// Invalid registry resource policy.
519#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
520#[non_exhaustive]
521pub enum McpServerToolRegistryLimitsError {
522    /// Every resource ceiling must be positive.
523    #[error("MCP tool registry limits must be positive")]
524    ZeroLimit,
525    /// A limit exceeded a hard maximum or aggregate capacity was inconsistent.
526    #[error("invalid MCP tool registry limit")]
527    InvalidLimit,
528}
529
530/// One bounded protocol content block owned by `StateKnot`.
531#[derive(Clone, Debug)]
532pub struct McpServerContent {
533    inner: ContentBlock,
534    wire_bytes: usize,
535}
536
537impl McpServerContent {
538    /// Creates bounded text content.
539    pub fn text(text: impl Into<String>) -> Result<Self, McpServerContentError> {
540        let text = text.into();
541        if text.len() > MAX_TEXT_CONTENT_BYTES {
542            return Err(McpServerContentError::TooLarge);
543        }
544        Self::from_protocol(ContentBlock::text(text))
545    }
546
547    /// Creates image content from raw bytes and canonical standard Base64.
548    pub fn image(
549        data: impl AsRef<[u8]>,
550        mime_type: impl Into<String>,
551    ) -> Result<Self, McpServerContentError> {
552        let data = data.as_ref();
553        validate_binary(data)?;
554        let mime_type = validate_mime(mime_type.into(), "image")?;
555        Self::from_protocol(ContentBlock::image(STANDARD.encode(data), mime_type))
556    }
557
558    /// Creates audio content from raw bytes and canonical standard Base64.
559    pub fn audio(
560        data: impl AsRef<[u8]>,
561        mime_type: impl Into<String>,
562    ) -> Result<Self, McpServerContentError> {
563        let data = data.as_ref();
564        validate_binary(data)?;
565        let mime_type = validate_mime(mime_type.into(), "audio")?;
566        Self::from_protocol(ContentBlock::audio(STANDARD.encode(data), mime_type))
567    }
568
569    /// Validates an extension content block represented as protocol JSON.
570    ///
571    /// Prefer typed constructors for ordinary content. This escape hatch
572    /// retains future MCP variants without exposing SDK types.
573    pub fn try_from_protocol_json(value: Value) -> Result<Self, McpServerContentError> {
574        let wire_bytes = canonical_json_len(&value).map_err(|_| McpServerContentError::Invalid)?;
575        if wire_bytes > MAX_CONTENT_BLOCK_BYTES {
576            return Err(McpServerContentError::TooLarge);
577        }
578        let inner: ContentBlock =
579            serde_json::from_value(value).map_err(|_| McpServerContentError::Invalid)?;
580        validate_protocol_content(&inner)?;
581        Ok(Self { inner, wire_bytes })
582    }
583
584    fn from_protocol(inner: ContentBlock) -> Result<Self, McpServerContentError> {
585        validate_protocol_content(&inner)?;
586        let value = serde_json::to_value(&inner).map_err(|_| McpServerContentError::Invalid)?;
587        let wire_bytes = canonical_json_len(&value).map_err(|_| McpServerContentError::Invalid)?;
588        if wire_bytes > MAX_CONTENT_BLOCK_BYTES {
589            return Err(McpServerContentError::TooLarge);
590        }
591        Ok(Self { inner, wire_bytes })
592    }
593
594    pub(crate) fn protocol_clone(&self) -> ContentBlock {
595        self.inner.clone()
596    }
597
598    pub(crate) const fn wire_bytes(&self) -> usize {
599        self.wire_bytes
600    }
601}
602
603/// Invalid or oversized MCP content.
604#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
605#[non_exhaustive]
606pub enum McpServerContentError {
607    /// The content did not match an MCP content block or had invalid media data.
608    #[error("invalid MCP content block")]
609    Invalid,
610    /// The content exceeded a hard byte ceiling.
611    #[error("MCP content block is too large")]
612    TooLarge,
613}
614
615fn validate_binary(data: &[u8]) -> Result<(), McpServerContentError> {
616    if data.len() > MAX_BINARY_CONTENT_BYTES {
617        return Err(McpServerContentError::TooLarge);
618    }
619    Ok(())
620}
621
622fn validate_mime(value: String, expected_top_level: &str) -> Result<String, McpServerContentError> {
623    if value.len() > 255
624        || value.trim() != value
625        || value
626            .parse::<mime::Mime>()
627            .map_or(true, |mime| mime.type_().as_str() != expected_top_level)
628    {
629        return Err(McpServerContentError::Invalid);
630    }
631    Ok(value)
632}
633
634fn validate_protocol_content(content: &ContentBlock) -> Result<(), McpServerContentError> {
635    match content {
636        ContentBlock::Text(value) => {
637            if value.text.len() > MAX_TEXT_CONTENT_BYTES {
638                return Err(McpServerContentError::TooLarge);
639            }
640        }
641        ContentBlock::Image(value) => {
642            validate_encoded_binary(&value.data)?;
643            validate_mime(value.mime_type.clone(), "image")?;
644        }
645        ContentBlock::Audio(value) => {
646            validate_encoded_binary(&value.data)?;
647            validate_mime(value.mime_type.clone(), "audio")?;
648        }
649        ContentBlock::Resource(value) => match &value.resource {
650            rmcp::model::ResourceContents::TextResourceContents { uri, text, .. } => {
651                validate_resource_uri(uri)?;
652                if text.len() > MAX_TEXT_CONTENT_BYTES {
653                    return Err(McpServerContentError::TooLarge);
654                }
655            }
656            rmcp::model::ResourceContents::BlobResourceContents { uri, blob, .. } => {
657                validate_resource_uri(uri)?;
658                validate_encoded_binary(blob)?;
659            }
660            _ => return Err(McpServerContentError::Invalid),
661        },
662        ContentBlock::ResourceLink(value) => validate_resource_uri(&value.uri)?,
663        _ => return Err(McpServerContentError::Invalid),
664    }
665    Ok(())
666}
667
668fn validate_encoded_binary(value: &str) -> Result<(), McpServerContentError> {
669    let decoded = STANDARD
670        .decode(value)
671        .map_err(|_| McpServerContentError::Invalid)?;
672    validate_binary(&decoded)
673}
674
675fn validate_resource_uri(value: &str) -> Result<(), McpServerContentError> {
676    if value.is_empty()
677        || value.len() > 4096
678        || value.chars().any(char::is_control)
679        || value
680            .parse::<http::Uri>()
681            .map_or(true, |uri| uri.scheme().is_none())
682    {
683        return Err(McpServerContentError::Invalid);
684    }
685    Ok(())
686}
687
688/// Bounded complete MCP Tool result.
689#[derive(Clone, Debug)]
690pub struct McpServerToolResult {
691    content: Arc<[McpServerContent]>,
692    structured_content: Option<Arc<Value>>,
693    is_error: bool,
694}
695
696impl McpServerToolResult {
697    /// Creates an unstructured successful result.
698    pub fn success(
699        content: impl IntoIterator<Item = McpServerContent>,
700    ) -> Result<Self, McpServerToolResultError> {
701        Self::new(content, None, false)
702    }
703
704    /// Creates a structured successful result.
705    pub fn structured(
706        content: impl IntoIterator<Item = McpServerContent>,
707        structured_content: Value,
708    ) -> Result<Self, McpServerToolResultError> {
709        Self::new(content, Some(structured_content), false)
710    }
711
712    /// Creates a caller-visible tool-level error.
713    pub fn error(
714        content: impl IntoIterator<Item = McpServerContent>,
715    ) -> Result<Self, McpServerToolResultError> {
716        Self::new(content, None, true)
717    }
718
719    fn new(
720        content: impl IntoIterator<Item = McpServerContent>,
721        structured_content: Option<Value>,
722        is_error: bool,
723    ) -> Result<Self, McpServerToolResultError> {
724        let content = content.into_iter().collect::<Vec<_>>();
725        if content.len() > MAX_CONTENT_BLOCKS {
726            return Err(McpServerToolResultError::TooManyContentBlocks);
727        }
728        let mut total = content
729            .iter()
730            .try_fold(0_usize, |total, item| total.checked_add(item.wire_bytes));
731        let structured_content = if let Some(value) = structured_content {
732            let bytes = canonical_json_len(&value)
733                .map_err(|_| McpServerToolResultError::InvalidStructuredContent)?;
734            if bytes > MAX_STRUCTURED_CONTENT_BYTES {
735                return Err(McpServerToolResultError::TooLarge);
736            }
737            total = total.and_then(|total| total.checked_add(bytes));
738            Some(Arc::new(value))
739        } else {
740            None
741        };
742        if total.is_none_or(|total| total > MAX_TOOL_RESULT_BYTES) {
743            return Err(McpServerToolResultError::TooLarge);
744        }
745        Ok(Self {
746            content: content.into(),
747            structured_content,
748            is_error,
749        })
750    }
751
752    fn into_protocol(self) -> CallToolResult {
753        let content = self
754            .content
755            .iter()
756            .map(|value| value.inner.clone())
757            .collect();
758        let mut result = if self.is_error {
759            CallToolResult::error(content)
760        } else {
761            CallToolResult::success(content)
762        };
763        result.structured_content = self.structured_content.as_deref().cloned();
764        result
765    }
766}
767
768/// Invalid bounded Tool result.
769#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
770#[non_exhaustive]
771pub enum McpServerToolResultError {
772    /// The result contained too many content blocks.
773    #[error("too many MCP tool result content blocks")]
774    TooManyContentBlocks,
775    /// Structured content could not be canonically represented.
776    #[error("invalid MCP structured content")]
777    InvalidStructuredContent,
778    /// The result exceeded a hard byte ceiling.
779    #[error("MCP tool result is too large")]
780    TooLarge,
781}
782
783/// Validated server-initiated MRTR request without an SDK type in the API.
784#[derive(Clone, Debug)]
785pub struct McpServerInputRequest {
786    inner: InputRequest,
787}
788
789impl McpServerInputRequest {
790    /// Validates one `elicitation/create`, `sampling/createMessage`, or
791    /// `roots/list` request represented as protocol JSON.
792    pub fn try_from_protocol_json(value: Value) -> Result<Self, McpServerInputRequiredError> {
793        if canonical_json_len(&value).map_or(true, |bytes| bytes > MAX_INPUT_REQUEST_BYTES) {
794            return Err(McpServerInputRequiredError::InvalidRequest);
795        }
796        let inner = serde_json::from_value(value)
797            .map_err(|_| McpServerInputRequiredError::InvalidRequest)?;
798        Ok(Self { inner })
799    }
800}
801
802/// Bounded MRTR `input_required` result.
803#[derive(Clone, Debug)]
804pub struct McpServerInputRequired {
805    requests: Arc<BTreeMap<String, McpServerInputRequest>>,
806    request_state: Option<Box<str>>,
807}
808
809impl McpServerInputRequired {
810    /// Creates an input-required result with at least one request or state.
811    pub fn new(
812        requests: BTreeMap<String, McpServerInputRequest>,
813        request_state: Option<impl Into<String>>,
814    ) -> Result<Self, McpServerInputRequiredError> {
815        if requests.len() > MAX_INPUT_REQUESTS {
816            return Err(McpServerInputRequiredError::TooManyRequests);
817        }
818        for id in requests.keys() {
819            if id.is_empty()
820                || id.len() > MAX_INPUT_REQUEST_ID_BYTES
821                || !id
822                    .bytes()
823                    .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
824            {
825                return Err(McpServerInputRequiredError::InvalidRequestId);
826            }
827        }
828        let request_state = request_state.map(Into::into);
829        if requests.is_empty() && request_state.is_none() {
830            return Err(McpServerInputRequiredError::Empty);
831        }
832        if request_state
833            .as_ref()
834            .is_some_and(|value| value.is_empty() || value.len() > MAX_REQUEST_STATE_BYTES)
835        {
836            return Err(McpServerInputRequiredError::InvalidRequestState);
837        }
838        Ok(Self {
839            requests: Arc::new(requests),
840            request_state: request_state.map(String::into_boxed_str),
841        })
842    }
843
844    pub(crate) fn into_protocol(self) -> InputRequiredResult {
845        let requests = if self.requests.is_empty() {
846            None
847        } else {
848            Some(
849                self.requests
850                    .iter()
851                    .map(|(key, value)| (key.clone(), value.inner.clone()))
852                    .collect(),
853            )
854        };
855        InputRequiredResult::new(requests, self.request_state.map(Into::into))
856    }
857}
858
859/// Invalid MRTR input-required result.
860#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
861#[non_exhaustive]
862pub enum McpServerInputRequiredError {
863    /// Neither input requests nor request state was supplied.
864    #[error("MCP input-required result is empty")]
865    Empty,
866    /// Too many simultaneous input requests were supplied.
867    #[error("too many MCP input requests")]
868    TooManyRequests,
869    /// A request identifier was invalid.
870    #[error("invalid MCP input request identifier")]
871    InvalidRequestId,
872    /// A request did not match an allowed MRTR request envelope.
873    #[error("invalid MCP input request")]
874    InvalidRequest,
875    /// Request state was empty or oversized.
876    #[error("invalid MCP request state")]
877    InvalidRequestState,
878}
879
880/// StateKnot-owned wrapper around integrity-protected MCP `requestState`.
881///
882/// Tokens are authenticated, not encrypted. Bind them to
883/// [`McpServerToolContext::request_state_binding`] and apply a TTL. Single-use
884/// redemption remains application-owned durable state.
885#[derive(Clone)]
886pub struct McpServerRequestStateCodec {
887    inner: RequestStateCodec,
888}
889
890impl McpServerRequestStateCodec {
891    /// Builds a codec from at least 32 bytes of high-entropy key material.
892    pub fn new(key: impl Into<Vec<u8>>) -> Result<Self, McpServerRequestStateCodecBuildError> {
893        RequestStateCodec::try_new(key)
894            .map(|inner| Self { inner })
895            .map_err(|_| McpServerRequestStateCodecBuildError::InvalidConfiguration)
896    }
897
898    /// Builds a rotating keyring that emits the active `rs2` key id.
899    pub fn with_keyring<K, V>(
900        active_key_id: impl Into<String>,
901        keys: impl IntoIterator<Item = (K, V)>,
902    ) -> Result<Self, McpServerRequestStateCodecBuildError>
903    where
904        K: Into<String>,
905        V: Into<Vec<u8>>,
906    {
907        RequestStateCodec::new_with_keyring(active_key_id, keys)
908            .map(|inner| Self { inner })
909            .map_err(|_| McpServerRequestStateCodecBuildError::InvalidConfiguration)
910    }
911
912    /// Seals bounded JSON with caller binding and mandatory positive TTL.
913    pub fn seal_json(
914        &self,
915        value: &Value,
916        associated_data: &[u8],
917        ttl: Duration,
918    ) -> Result<String, McpServerRequestStateError> {
919        validate_state_operation(value, associated_data, ttl)?;
920        let options = SealOptions::new().associated_data(associated_data).ttl(ttl);
921        let sealed = self
922            .inner
923            .seal_json_with(value, &options)
924            .map_err(|_| McpServerRequestStateError::InvalidState)?;
925        if sealed.len() > MAX_REQUEST_STATE_BYTES {
926            return Err(McpServerRequestStateError::StateTooLarge);
927        }
928        Ok(sealed)
929    }
930
931    /// Opens bounded JSON with the exact same caller binding.
932    ///
933    /// All malformed, expired, unknown-key, and integrity failures collapse to
934    /// [`McpServerRequestStateError::InvalidState`] to avoid an oracle.
935    pub fn open_json(
936        &self,
937        sealed: &str,
938        associated_data: &[u8],
939    ) -> Result<Value, McpServerRequestStateError> {
940        if sealed.is_empty()
941            || sealed.len() > MAX_REQUEST_STATE_BYTES
942            || associated_data.len() > MAX_REQUEST_STATE_BINDING_BYTES
943        {
944            return Err(McpServerRequestStateError::InvalidState);
945        }
946        let value = self
947            .inner
948            .open_json_with(sealed, associated_data)
949            .map_err(|_| McpServerRequestStateError::InvalidState)?;
950        if canonical_json_len(&value).map_or(true, |bytes| bytes > MAX_REQUEST_STATE_PAYLOAD_BYTES)
951        {
952            return Err(McpServerRequestStateError::InvalidState);
953        }
954        Ok(value)
955    }
956}
957
958impl fmt::Debug for McpServerRequestStateCodec {
959    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
960        formatter
961            .debug_struct("McpServerRequestStateCodec")
962            .field("keys", &"[REDACTED]")
963            .finish()
964    }
965}
966
967/// Invalid request-state key or keyring configuration.
968#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
969#[non_exhaustive]
970pub enum McpServerRequestStateCodecBuildError {
971    /// The key was short or the keyring/key identifiers were inconsistent.
972    #[error("invalid MCP request-state key configuration")]
973    InvalidConfiguration,
974}
975
976/// Safe request-state processing failure.
977#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
978#[non_exhaustive]
979pub enum McpServerRequestStateError {
980    /// Payload, associated data, or TTL violated a hard bound.
981    #[error("invalid MCP request-state operation")]
982    InvalidOperation,
983    /// The generated token exceeded the hard transport ceiling.
984    #[error("MCP request state is too large")]
985    StateTooLarge,
986    /// State was malformed, expired, signed by an unknown key, or failed integrity.
987    #[error("invalid MCP request state")]
988    InvalidState,
989}
990
991fn validate_state_operation(
992    value: &Value,
993    associated_data: &[u8],
994    ttl: Duration,
995) -> Result<(), McpServerRequestStateError> {
996    if ttl.is_zero()
997        || ttl > MAX_REQUEST_STATE_TTL
998        || associated_data.is_empty()
999        || associated_data.len() > MAX_REQUEST_STATE_BINDING_BYTES
1000        || canonical_json_len(value).map_or(true, |bytes| bytes > MAX_REQUEST_STATE_PAYLOAD_BYTES)
1001    {
1002        return Err(McpServerRequestStateError::InvalidOperation);
1003    }
1004    Ok(())
1005}
1006
1007/// Complete or input-required Tool outcome.
1008#[derive(Clone, Debug)]
1009#[non_exhaustive]
1010pub enum McpServerToolOutcome {
1011    /// Tool execution completed, including caller-visible Tool errors.
1012    Complete(McpServerToolResult),
1013    /// The client must satisfy MRTR input and retry the same logical call.
1014    InputRequired(McpServerInputRequired),
1015}
1016
1017impl From<McpServerToolResult> for McpServerToolOutcome {
1018    fn from(value: McpServerToolResult) -> Self {
1019        Self::Complete(value)
1020    }
1021}
1022
1023impl From<McpServerInputRequired> for McpServerToolOutcome {
1024    fn from(value: McpServerInputRequired) -> Self {
1025        Self::InputRequired(value)
1026    }
1027}
1028
1029/// Handler-internal failure category with no arbitrary diagnostic leakage.
1030#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1031#[non_exhaustive]
1032pub enum McpServerToolHandlerError {
1033    /// A downstream dependency is temporarily unavailable.
1034    #[error("MCP tool dependency is unavailable")]
1035    Unavailable,
1036    /// Execution observed cooperative cancellation.
1037    #[error("MCP tool execution was cancelled")]
1038    Cancelled,
1039    /// An invariant failed inside the Tool implementation.
1040    #[error("MCP tool execution failed internally")]
1041    Internal,
1042    /// The operation requires a core capability the client did not declare.
1043    #[error("MCP client is missing a required capability")]
1044    MissingRequiredClientCapability(McpServerRequiredClientCapability),
1045}
1046
1047/// Core client capability a Tool may require before it can continue.
1048///
1049/// This StateKnot-owned enum prevents the wire SDK capability model from
1050/// becoming part of the public application API. Extensions, including Tasks,
1051/// require their own independently versioned profile.
1052#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1053#[non_exhaustive]
1054pub enum McpServerRequiredClientCapability {
1055    /// Interactive Elicitation requests.
1056    Elicitation,
1057    /// Server-initiated Sampling requests.
1058    Sampling,
1059    /// Client Roots discovery.
1060    Roots,
1061}
1062
1063/// Executes one registered Tool.
1064pub trait McpServerToolHandler: Send + Sync + 'static {
1065    /// Executes a validated, authorized request.
1066    fn call(
1067        &self,
1068        call: McpServerToolCall,
1069        context: McpServerToolContext,
1070    ) -> BoxFuture<'_, Result<McpServerToolOutcome, McpServerToolHandlerError>>;
1071}
1072
1073/// StateKnot-owned inbound Tool call.
1074#[derive(Clone, Debug)]
1075pub struct McpServerToolCall {
1076    name: Arc<str>,
1077    arguments: Arc<Map<String, Value>>,
1078    input_responses: Arc<BTreeMap<String, Value>>,
1079    request_state: Option<Arc<str>>,
1080}
1081
1082impl McpServerToolCall {
1083    /// Returns the registered Tool name.
1084    #[must_use]
1085    pub fn name(&self) -> &str {
1086        &self.name
1087    }
1088
1089    /// Returns syntactically decoded arguments.
1090    ///
1091    /// The decoded authorization policy runs before input-schema validation to
1092    /// avoid exposing schema diagnostics to a denied caller. Authorization
1093    /// code must therefore treat these values as untrusted.
1094    #[must_use]
1095    pub fn arguments(&self) -> &Map<String, Value> {
1096        &self.arguments
1097    }
1098
1099    /// Returns untrusted MRTR responses supplied by the client.
1100    #[must_use]
1101    pub fn input_responses(&self) -> &BTreeMap<String, Value> {
1102        &self.input_responses
1103    }
1104
1105    /// Returns untrusted request state echoed by the client.
1106    #[must_use]
1107    pub fn request_state(&self) -> Option<&str> {
1108        self.request_state.as_deref()
1109    }
1110}
1111
1112#[derive(Clone)]
1113struct McpServerProgressSink {
1114    peer: Peer<RoleServer>,
1115    token: rmcp::model::ProgressToken,
1116}
1117
1118/// Authenticated, request-scoped Tool execution context.
1119#[derive(Clone)]
1120pub struct McpServerToolContext {
1121    principal: McpServerPrincipal,
1122    client_name: Option<Arc<str>>,
1123    client_version: Option<Arc<str>>,
1124    client_capabilities: Arc<Value>,
1125    cancellation: CancellationToken,
1126    progress: Option<McpServerProgressSink>,
1127    request_state_binding: Arc<[u8]>,
1128}
1129
1130impl McpServerToolContext {
1131    /// Returns the authenticated principal.
1132    #[must_use]
1133    pub const fn principal(&self) -> &McpServerPrincipal {
1134        &self.principal
1135    }
1136
1137    /// Returns the validated client implementation name.
1138    #[must_use]
1139    pub fn client_name(&self) -> Option<&str> {
1140        self.client_name.as_deref()
1141    }
1142
1143    /// Returns the validated client implementation version.
1144    #[must_use]
1145    pub fn client_version(&self) -> Option<&str> {
1146        self.client_version.as_deref()
1147    }
1148
1149    /// Returns the request-scoped client capability document.
1150    #[must_use]
1151    pub fn client_capabilities(&self) -> &Value {
1152        &self.client_capabilities
1153    }
1154
1155    /// Returns associated data bound to principal, Tool, and canonical arguments.
1156    #[must_use]
1157    pub fn request_state_binding(&self) -> &[u8] {
1158        &self.request_state_binding
1159    }
1160
1161    /// Returns whether the client cancelled this request.
1162    #[must_use]
1163    pub fn is_cancelled(&self) -> bool {
1164        self.cancellation.is_cancelled()
1165    }
1166
1167    /// Waits for cooperative cancellation.
1168    pub async fn cancelled(&self) {
1169        self.cancellation.cancelled().await;
1170    }
1171
1172    /// Sends bounded progress when the request supplied a progress token.
1173    ///
1174    /// Returns `Ok(false)` when the client did not request progress.
1175    pub async fn report_progress(
1176        &self,
1177        progress: f64,
1178        total: Option<f64>,
1179        message: Option<&str>,
1180    ) -> Result<bool, McpServerToolProgressError> {
1181        if !progress.is_finite()
1182            || progress < 0.0
1183            || total.is_some_and(|value| !value.is_finite() || value <= 0.0 || progress > value)
1184            || message.is_some_and(|value| {
1185                value.len() > MAX_PROGRESS_MESSAGE_BYTES || value.chars().any(char::is_control)
1186            })
1187        {
1188            return Err(McpServerToolProgressError::InvalidProgress);
1189        }
1190        let Some(sink) = &self.progress else {
1191            return Ok(false);
1192        };
1193        let mut notification = ProgressNotificationParam::new(sink.token.clone(), progress);
1194        if let Some(total) = total {
1195            notification = notification.with_total(total);
1196        }
1197        if let Some(message) = message {
1198            notification = notification.with_message(message);
1199        }
1200        sink.peer
1201            .notify_progress(notification)
1202            .await
1203            .map_err(|_| McpServerToolProgressError::TransportClosed)?;
1204        Ok(true)
1205    }
1206}
1207
1208impl fmt::Debug for McpServerToolContext {
1209    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1210        formatter
1211            .debug_struct("McpServerToolContext")
1212            .field("principal", &self.principal)
1213            .field("client_name", &self.client_name)
1214            .field("client_version", &self.client_version)
1215            .field("cancelled", &self.cancellation.is_cancelled())
1216            .field("progress_requested", &self.progress.is_some())
1217            .field("request_state_binding", &"[DIGEST]")
1218            .finish_non_exhaustive()
1219    }
1220}
1221
1222/// Progress notification failure.
1223#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1224#[non_exhaustive]
1225pub enum McpServerToolProgressError {
1226    /// Progress, total, or message violated protocol bounds.
1227    #[error("invalid MCP progress notification")]
1228    InvalidProgress,
1229    /// The client transport closed before notification delivery.
1230    #[error("MCP client transport is closed")]
1231    TransportClosed,
1232}
1233
1234/// Owned facts for decoded Tool authorization.
1235#[derive(Clone, Debug)]
1236pub struct McpServerToolAuthorizationRequest {
1237    principal: McpServerPrincipal,
1238    definition: McpServerToolDefinition,
1239    call: McpServerToolCall,
1240}
1241
1242impl McpServerToolAuthorizationRequest {
1243    /// Returns the authenticated principal.
1244    #[must_use]
1245    pub const fn principal(&self) -> &McpServerPrincipal {
1246        &self.principal
1247    }
1248
1249    /// Returns the immutable registered definition.
1250    #[must_use]
1251    pub const fn definition(&self) -> &McpServerToolDefinition {
1252        &self.definition
1253    }
1254
1255    /// Returns the decoded, resource-bounded call.
1256    ///
1257    /// Arguments remain untrusted until authorization succeeds.
1258    #[must_use]
1259    pub const fn call(&self) -> &McpServerToolCall {
1260        &self.call
1261    }
1262}
1263
1264/// Decoded per-call authorization policy.
1265pub trait McpServerToolAuthorization: Send + Sync + 'static {
1266    /// Authorizes one call after Tool lookup and resource-bound checks, but
1267    /// before input-schema validation.
1268    fn authorize(
1269        &self,
1270        request: McpServerToolAuthorizationRequest,
1271    ) -> BoxFuture<'_, Result<(), McpServerToolAuthorizationError>>;
1272}
1273
1274/// Explicit policy that admits every scope-qualified Tool call.
1275#[derive(Clone, Copy, Debug, Default)]
1276pub struct AllowMcpServerToolAuthorization;
1277
1278impl McpServerToolAuthorization for AllowMcpServerToolAuthorization {
1279    fn authorize(
1280        &self,
1281        _request: McpServerToolAuthorizationRequest,
1282    ) -> BoxFuture<'_, Result<(), McpServerToolAuthorizationError>> {
1283        Box::pin(async { Ok(()) })
1284    }
1285}
1286
1287/// Public-safe decoded authorization failure.
1288#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1289#[non_exhaustive]
1290pub enum McpServerToolAuthorizationError {
1291    /// Policy denied this call.
1292    #[error("MCP tool call is forbidden")]
1293    Forbidden,
1294    /// The policy authority is temporarily unavailable.
1295    #[error("MCP tool authorization is unavailable")]
1296    Unavailable,
1297}
1298
1299struct PendingTool {
1300    definition: McpServerToolDefinition,
1301    handler: Arc<dyn McpServerToolHandler>,
1302}
1303
1304struct RegisteredTool {
1305    definition: McpServerToolDefinition,
1306    protocol: Tool,
1307    input_validator: Validator,
1308    output_validator: Option<Validator>,
1309    handler: Arc<dyn McpServerToolHandler>,
1310}
1311
1312/// Startup-only builder for an immutable executable Tool registry.
1313pub struct McpServerToolRegistryBuilder {
1314    limits: McpServerToolRegistryLimits,
1315    pending: BTreeMap<String, PendingTool>,
1316    total_schema_bytes: usize,
1317}
1318
1319impl McpServerToolRegistryBuilder {
1320    /// Creates an empty builder with explicit ceilings.
1321    #[must_use]
1322    pub fn new(limits: McpServerToolRegistryLimits) -> Self {
1323        Self {
1324            limits,
1325            pending: BTreeMap::new(),
1326            total_schema_bytes: 0,
1327        }
1328    }
1329
1330    /// Creates an empty builder with production defaults.
1331    #[must_use]
1332    pub fn with_default_limits() -> Self {
1333        Self::new(McpServerToolRegistryLimits::default())
1334    }
1335
1336    /// Registers one definition and handler without mutating on failure.
1337    pub fn register<H>(
1338        &mut self,
1339        definition: McpServerToolDefinition,
1340        handler: H,
1341    ) -> Result<(), McpServerToolRegistryError>
1342    where
1343        H: McpServerToolHandler,
1344    {
1345        self.register_shared(definition, Arc::new(handler))
1346    }
1347
1348    /// Registers one definition with an already shared handler.
1349    pub fn register_shared(
1350        &mut self,
1351        definition: McpServerToolDefinition,
1352        handler: Arc<dyn McpServerToolHandler>,
1353    ) -> Result<(), McpServerToolRegistryError> {
1354        if self.pending.len() == self.limits.maximum_tools {
1355            return Err(McpServerToolRegistryError::TooManyTools);
1356        }
1357        if self.pending.contains_key(definition.name()) {
1358            return Err(McpServerToolRegistryError::DuplicateTool);
1359        }
1360        let input_bytes = canonical_json_len(definition.input_schema())
1361            .map_err(|_| McpServerToolRegistryError::SchemaTooLarge)?;
1362        let output_bytes = definition
1363            .output_schema()
1364            .map(canonical_json_len)
1365            .transpose()
1366            .map_err(|_| McpServerToolRegistryError::SchemaTooLarge)?
1367            .unwrap_or(0);
1368        if input_bytes > self.limits.maximum_schema_bytes
1369            || output_bytes > self.limits.maximum_schema_bytes
1370        {
1371            return Err(McpServerToolRegistryError::SchemaTooLarge);
1372        }
1373        let added = input_bytes
1374            .checked_add(output_bytes)
1375            .ok_or(McpServerToolRegistryError::TotalSchemaBytesTooLarge)?;
1376        let total = self
1377            .total_schema_bytes
1378            .checked_add(added)
1379            .ok_or(McpServerToolRegistryError::TotalSchemaBytesTooLarge)?;
1380        if total > self.limits.maximum_total_schema_bytes {
1381            return Err(McpServerToolRegistryError::TotalSchemaBytesTooLarge);
1382        }
1383        self.pending.insert(
1384            definition.name().to_owned(),
1385            PendingTool {
1386                definition,
1387                handler,
1388            },
1389        );
1390        self.total_schema_bytes = total;
1391        Ok(())
1392    }
1393
1394    /// Eagerly compiles every validator in offline mode and freezes the catalog.
1395    pub fn build(self) -> Result<McpServerToolRegistry, McpServerToolRegistryError> {
1396        if self.pending.is_empty() {
1397            return Err(McpServerToolRegistryError::Empty);
1398        }
1399        let mut registered = BTreeMap::new();
1400        let mut digest_material = Vec::new();
1401        for (name, pending) in self.pending {
1402            let input_validator = compile_schema(name.as_str(), pending.definition.input_schema())?;
1403            let output_validator = pending
1404                .definition
1405                .output_schema()
1406                .map(|schema| compile_schema(name.as_str(), schema))
1407                .transpose()?;
1408            append_digest_part(&mut digest_material, name.as_bytes());
1409            let input = serde_json_canonicalizer::to_vec(pending.definition.input_schema())
1410                .map_err(|_| McpServerToolRegistryError::SchemaTooLarge)?;
1411            append_digest_part(&mut digest_material, &input);
1412            if let Some(output) = pending.definition.output_schema() {
1413                let output = serde_json_canonicalizer::to_vec(output)
1414                    .map_err(|_| McpServerToolRegistryError::SchemaTooLarge)?;
1415                append_digest_part(&mut digest_material, &output);
1416            } else {
1417                append_digest_part(&mut digest_material, &[]);
1418            }
1419            let protocol = pending.definition.to_protocol();
1420            registered.insert(
1421                name,
1422                Arc::new(RegisteredTool {
1423                    definition: pending.definition,
1424                    protocol,
1425                    input_validator,
1426                    output_validator,
1427                    handler: pending.handler,
1428                }),
1429            );
1430        }
1431        let digest = Digest::sha256(digest_material).to_string();
1432        Ok(McpServerToolRegistry {
1433            inner: Arc::new(McpServerToolRegistryInner {
1434                tools: registered,
1435                digest: Arc::from(
1436                    digest
1437                        .strip_prefix("sha256:")
1438                        .expect("StateKnot SHA-256 digest has stable prefix"),
1439                ),
1440                total_schema_bytes: self.total_schema_bytes,
1441            }),
1442        })
1443    }
1444}
1445
1446impl Default for McpServerToolRegistryBuilder {
1447    fn default() -> Self {
1448        Self::with_default_limits()
1449    }
1450}
1451
1452impl fmt::Debug for McpServerToolRegistryBuilder {
1453    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1454        formatter
1455            .debug_struct("McpServerToolRegistryBuilder")
1456            .field("limits", &self.limits)
1457            .field("tool_count", &self.pending.len())
1458            .field("total_schema_bytes", &self.total_schema_bytes)
1459            .finish_non_exhaustive()
1460    }
1461}
1462
1463fn compile_schema(
1464    tool_name: &str,
1465    schema: &Value,
1466) -> Result<Validator, McpServerToolRegistryError> {
1467    jsonschema::draft202012::options()
1468        .should_validate_formats(true)
1469        .offline()
1470        .build(schema)
1471        .map_err(|source| McpServerToolRegistryError::SchemaCompilation {
1472            tool_name: tool_name.to_owned().into_boxed_str(),
1473            diagnostic: bounded_diagnostic(&source.to_string()),
1474        })
1475}
1476
1477pub(crate) fn append_digest_part(target: &mut Vec<u8>, value: &[u8]) {
1478    target.extend_from_slice(&(value.len() as u64).to_be_bytes());
1479    target.extend_from_slice(value);
1480}
1481
1482/// Immutable executable Tool registry.
1483#[derive(Clone)]
1484pub struct McpServerToolRegistry {
1485    inner: Arc<McpServerToolRegistryInner>,
1486}
1487
1488struct McpServerToolRegistryInner {
1489    tools: BTreeMap<String, Arc<RegisteredTool>>,
1490    digest: Arc<str>,
1491    total_schema_bytes: usize,
1492}
1493
1494impl McpServerToolRegistry {
1495    /// Returns the registered Tool count.
1496    #[must_use]
1497    pub fn len(&self) -> usize {
1498        self.inner.tools.len()
1499    }
1500
1501    /// Returns whether no Tool is registered.
1502    #[must_use]
1503    pub fn is_empty(&self) -> bool {
1504        self.inner.tools.is_empty()
1505    }
1506
1507    /// Returns one StateKnot-owned definition.
1508    #[must_use]
1509    pub fn get(&self, name: &str) -> Option<&McpServerToolDefinition> {
1510        self.inner.tools.get(name).map(|entry| &entry.definition)
1511    }
1512
1513    /// Iterates definitions in stable ASCII name order.
1514    pub fn definitions(&self) -> impl ExactSizeIterator<Item = &McpServerToolDefinition> {
1515        self.inner.tools.values().map(|entry| &entry.definition)
1516    }
1517
1518    /// Returns retained canonical input/output schema bytes.
1519    #[must_use]
1520    pub fn total_schema_bytes(&self) -> usize {
1521        self.inner.total_schema_bytes
1522    }
1523
1524    fn contains_scoped_tools(&self) -> bool {
1525        self.inner
1526            .tools
1527            .values()
1528            .any(|entry| !entry.definition.required_scopes.is_empty())
1529    }
1530}
1531
1532impl fmt::Debug for McpServerToolRegistry {
1533    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1534        formatter
1535            .debug_struct("McpServerToolRegistry")
1536            .field("tool_count", &self.len())
1537            .field("catalog_digest", &self.inner.digest)
1538            .field("total_schema_bytes", &self.total_schema_bytes())
1539            .finish_non_exhaustive()
1540    }
1541}
1542
1543/// Startup failure for an executable registry.
1544#[derive(Clone, Debug, Eq, Error, PartialEq)]
1545#[non_exhaustive]
1546pub enum McpServerToolRegistryError {
1547    /// At least one Tool is required.
1548    #[error("MCP tool registry is empty")]
1549    Empty,
1550    /// A name appeared more than once.
1551    #[error("duplicate MCP tool")]
1552    DuplicateTool,
1553    /// The configured Tool count ceiling was reached.
1554    #[error("too many MCP tools")]
1555    TooManyTools,
1556    /// An input or output schema exceeded the configured ceiling.
1557    #[error("MCP tool schema is too large")]
1558    SchemaTooLarge,
1559    /// Aggregate schema bytes exceeded the configured ceiling.
1560    #[error("MCP tool aggregate schema bytes are too large")]
1561    TotalSchemaBytesTooLarge,
1562    /// Offline validator compilation failed, including unresolved `$ref`.
1563    #[error("failed to compile schema for MCP tool {tool_name}: {diagnostic}")]
1564    SchemaCompilation {
1565        /// Tool whose schema failed.
1566        tool_name: Box<str>,
1567        /// Bounded startup diagnostic.
1568        diagnostic: Box<str>,
1569    },
1570}
1571
1572/// Stable service identity, pagination, and cache policy.
1573#[derive(Clone, Debug, Eq, PartialEq)]
1574pub struct McpServerApplicationOptions {
1575    pub(crate) server_name: Arc<str>,
1576    pub(crate) server_version: Arc<str>,
1577    pub(crate) instructions: Option<Arc<str>>,
1578    pub(crate) page_size: usize,
1579    pub(crate) cache_ttl_ms: u64,
1580    pub(crate) cache_scope: McpServerCacheScope,
1581}
1582
1583impl McpServerApplicationOptions {
1584    /// Hard page size ceiling.
1585    pub const HARD_MAXIMUM_PAGE_SIZE: usize = 256;
1586    /// Hard cache TTL ceiling.
1587    pub const HARD_MAXIMUM_CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60);
1588
1589    /// Constructs explicit service metadata and catalog policy.
1590    pub fn new(
1591        server_name: impl Into<String>,
1592        server_version: impl Into<String>,
1593        page_size: usize,
1594        cache_ttl: Duration,
1595        cache_scope: McpServerCacheScope,
1596    ) -> Result<Self, McpServerApplicationOptionsError> {
1597        let server_name = server_name.into();
1598        let server_version = server_version.into();
1599        validate_service_component(&server_name)?;
1600        validate_service_component(&server_version)?;
1601        if page_size == 0 || page_size > Self::HARD_MAXIMUM_PAGE_SIZE {
1602            return Err(McpServerApplicationOptionsError::InvalidPageSize);
1603        }
1604        if cache_ttl > Self::HARD_MAXIMUM_CACHE_TTL {
1605            return Err(McpServerApplicationOptionsError::InvalidCacheTtl);
1606        }
1607        Ok(Self {
1608            server_name: Arc::from(server_name),
1609            server_version: Arc::from(server_version),
1610            instructions: None,
1611            page_size,
1612            cache_ttl_ms: u64::try_from(cache_ttl.as_millis())
1613                .map_err(|_| McpServerApplicationOptionsError::InvalidCacheTtl)?,
1614            cache_scope,
1615        })
1616    }
1617
1618    /// Adds bounded client guidance.
1619    pub fn with_instructions(
1620        mut self,
1621        instructions: impl Into<String>,
1622    ) -> Result<Self, McpServerApplicationOptionsError> {
1623        let instructions = instructions.into();
1624        if instructions.is_empty()
1625            || instructions.len() > MAX_DISPLAY_BYTES
1626            || instructions.trim() != instructions
1627            || instructions
1628                .chars()
1629                .any(|character| character.is_control() && !matches!(character, '\n' | '\r' | '\t'))
1630        {
1631            return Err(McpServerApplicationOptionsError::InvalidInstructions);
1632        }
1633        self.instructions = Some(Arc::from(instructions));
1634        Ok(self)
1635    }
1636}
1637
1638fn validate_service_component(value: &str) -> Result<(), McpServerApplicationOptionsError> {
1639    if value.is_empty()
1640        || value.len() > 256
1641        || value.trim() != value
1642        || value.chars().any(char::is_control)
1643    {
1644        return Err(McpServerApplicationOptionsError::InvalidIdentity);
1645    }
1646    Ok(())
1647}
1648
1649/// Invalid Tool service configuration.
1650#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1651#[non_exhaustive]
1652pub enum McpServerApplicationOptionsError {
1653    /// Server name or version was invalid.
1654    #[error("invalid MCP server identity")]
1655    InvalidIdentity,
1656    /// The page size was zero or exceeded the hard maximum.
1657    #[error("invalid MCP tool catalog page size")]
1658    InvalidPageSize,
1659    /// Cache TTL exceeded the hard maximum.
1660    #[error("invalid MCP tool catalog cache TTL")]
1661    InvalidCacheTtl,
1662    /// Instructions were empty, padded, oversized, or contained unsafe controls.
1663    #[error("invalid MCP server instructions")]
1664    InvalidInstructions,
1665}
1666
1667/// Production MCP Tool handler backed by an immutable `StateKnot` registry.
1668#[derive(Clone)]
1669pub struct McpServerToolService {
1670    registry: McpServerToolRegistry,
1671    options: McpServerApplicationOptions,
1672    authorization: Arc<dyn McpServerToolAuthorization>,
1673}
1674
1675impl McpServerToolService {
1676    /// Creates a service with an explicit decoded authorization policy.
1677    pub fn new<A>(
1678        registry: McpServerToolRegistry,
1679        options: McpServerApplicationOptions,
1680        authorization: A,
1681    ) -> Result<Self, McpServerToolServiceBuildError>
1682    where
1683        A: McpServerToolAuthorization,
1684    {
1685        Self::with_shared_authorization(registry, options, Arc::new(authorization))
1686    }
1687
1688    /// Creates a service with an already shared authorization policy.
1689    pub fn with_shared_authorization(
1690        registry: McpServerToolRegistry,
1691        options: McpServerApplicationOptions,
1692        authorization: Arc<dyn McpServerToolAuthorization>,
1693    ) -> Result<Self, McpServerToolServiceBuildError> {
1694        if registry.contains_scoped_tools()
1695            && matches!(options.cache_scope, McpServerCacheScope::Public)
1696        {
1697            return Err(McpServerToolServiceBuildError::PublicCacheWithScopedTools);
1698        }
1699        Ok(Self {
1700            registry,
1701            options,
1702            authorization,
1703        })
1704    }
1705
1706    fn page(
1707        &self,
1708        principal: &McpServerPrincipal,
1709        cursor: Option<&str>,
1710    ) -> Result<(Vec<Tool>, Option<String>), ErrorData> {
1711        let scope_tag = self.catalog_scope_tag(principal);
1712        let start = cursor.map_or(Ok(0), |cursor| self.parse_cursor(cursor, &scope_tag))?;
1713        let visible = self
1714            .registry
1715            .inner
1716            .tools
1717            .values()
1718            .filter(|entry| {
1719                entry
1720                    .definition
1721                    .required_scopes()
1722                    .all(|scope| principal.has_scope(scope))
1723            })
1724            .collect::<Vec<_>>();
1725        if start > visible.len() {
1726            return Err(ErrorData::invalid_params(
1727                "Invalid tool catalog cursor",
1728                None,
1729            ));
1730        }
1731        let end = start
1732            .saturating_add(self.options.page_size)
1733            .min(visible.len());
1734        let tools = visible
1735            .iter()
1736            .skip(start)
1737            .take(end - start)
1738            .map(|entry| entry.protocol.clone())
1739            .collect();
1740        let next = (end < visible.len()).then(|| self.cursor(&scope_tag, end));
1741        Ok((tools, next))
1742    }
1743
1744    fn catalog_scope_tag(&self, principal: &McpServerPrincipal) -> String {
1745        if matches!(self.options.cache_scope, McpServerCacheScope::Public) {
1746            return "public".to_owned();
1747        }
1748        let mut material = principal.subject().as_bytes().to_vec();
1749        for scope in principal.scopes() {
1750            append_digest_part(&mut material, scope.as_bytes());
1751        }
1752        let digest = Digest::sha256(material).to_string();
1753        digest
1754            .strip_prefix("sha256:")
1755            .expect("StateKnot SHA-256 digest has stable prefix")
1756            .to_owned()
1757    }
1758
1759    fn cursor(&self, scope_tag: &str, offset: usize) -> String {
1760        format!("v1.{}.{}.{}", self.registry.inner.digest, scope_tag, offset)
1761    }
1762
1763    fn parse_cursor(&self, cursor: &str, scope_tag: &str) -> Result<usize, ErrorData> {
1764        if cursor.len() > 192 {
1765            return Err(ErrorData::invalid_params(
1766                "Invalid tool catalog cursor",
1767                None,
1768            ));
1769        }
1770        let mut parts = cursor.split('.');
1771        let valid_version = parts.next() == Some("v1");
1772        let valid_digest = parts.next() == Some(self.registry.inner.digest.as_ref());
1773        let valid_scope = parts.next() == Some(scope_tag);
1774        let offset = parts.next().and_then(|value| value.parse::<usize>().ok());
1775        if !valid_version
1776            || !valid_digest
1777            || !valid_scope
1778            || parts.next().is_some()
1779            || offset.is_none()
1780        {
1781            return Err(ErrorData::invalid_params(
1782                "Invalid tool catalog cursor",
1783                None,
1784            ));
1785        }
1786        Ok(offset.expect("validated cursor offset exists"))
1787    }
1788
1789    async fn dispatch(
1790        &self,
1791        request: CallToolRequestParams,
1792        context: RequestContext<RoleServer>,
1793    ) -> Result<CallToolResponse, ErrorData> {
1794        let Some(registered) = self
1795            .registry
1796            .inner
1797            .tools
1798            .get(request.name.as_ref())
1799            .cloned()
1800        else {
1801            return Err(unavailable_tool());
1802        };
1803        let principal = mcp_server_principal(&context)
1804            .cloned()
1805            .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1806        if registered
1807            .definition
1808            .required_scopes()
1809            .any(|scope| !principal.has_scope(scope))
1810        {
1811            return Err(unavailable_tool());
1812        }
1813
1814        let arguments = request.arguments.unwrap_or_default();
1815        let input_responses = request.input_responses.unwrap_or_default();
1816        validate_inbound_mrtr(&input_responses, request.request_state.as_deref())?;
1817        let call = McpServerToolCall {
1818            name: Arc::from(request.name.into_owned()),
1819            arguments: Arc::new(arguments),
1820            input_responses: Arc::new(input_responses),
1821            request_state: request.request_state.map(Arc::from),
1822        };
1823        let authorization_request = McpServerToolAuthorizationRequest {
1824            principal: principal.clone(),
1825            definition: registered.definition.clone(),
1826            call: call.clone(),
1827        };
1828        match self.authorization.authorize(authorization_request).await {
1829            Ok(()) => {}
1830            Err(McpServerToolAuthorizationError::Forbidden) => return Err(unavailable_tool()),
1831            Err(McpServerToolAuthorizationError::Unavailable) => {
1832                return Err(ErrorData::internal_error(
1833                    "MCP tool authorization is unavailable",
1834                    None,
1835                ));
1836            }
1837        }
1838
1839        let argument_value = Value::Object((*call.arguments).clone());
1840        if !registered.input_validator.is_valid(&argument_value) {
1841            return Err(ErrorData::invalid_params(
1842                "Tool arguments do not match input schema",
1843                None,
1844            ));
1845        }
1846
1847        let tool_context = build_tool_context(&context, principal, &call)?;
1848        let outcome = registered
1849            .handler
1850            .call(call, tool_context)
1851            .await
1852            .map_err(handler_error_result)?;
1853        match outcome {
1854            McpServerToolOutcome::Complete(result) => {
1855                if !result.is_error
1856                    && let Some(validator) = &registered.output_validator
1857                {
1858                    let Some(structured) = result.structured_content.as_deref() else {
1859                        return Err(ErrorData::internal_error(
1860                            "MCP tool omitted required structured output",
1861                            None,
1862                        ));
1863                    };
1864                    if !validator.is_valid(structured) {
1865                        return Err(ErrorData::internal_error(
1866                            "MCP tool output failed schema validation",
1867                            None,
1868                        ));
1869                    }
1870                }
1871                Ok(result.into_protocol().into())
1872            }
1873            McpServerToolOutcome::InputRequired(result) => Ok(result.into_protocol().into()),
1874        }
1875    }
1876}
1877
1878impl fmt::Debug for McpServerToolService {
1879    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1880        formatter
1881            .debug_struct("McpServerToolService")
1882            .field("registry", &self.registry)
1883            .field("options", &self.options)
1884            .field("authorization", &"[POLICY]")
1885            .finish_non_exhaustive()
1886    }
1887}
1888
1889impl ServerHandler for McpServerToolService {
1890    fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
1891        Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
1892    }
1893
1894    fn get_info(&self) -> ServerConfig {
1895        let mut info = ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
1896            .with_server_info(Implementation::new(
1897                self.options.server_name.to_string(),
1898                self.options.server_version.to_string(),
1899            ));
1900        if let Some(instructions) = &self.options.instructions {
1901            info = info.with_instructions(instructions.to_string());
1902        }
1903        info
1904    }
1905
1906    async fn discover(
1907        &self,
1908        _context: RequestContext<RoleServer>,
1909    ) -> Result<DiscoverResult, ErrorData> {
1910        Ok(
1911            DiscoverResult::from_server_info(vec![ProtocolVersion::V_2026_07_28], self.get_info())
1912                .with_ttl_ms(self.options.cache_ttl_ms)
1913                .with_cache_scope(self.options.cache_scope.into()),
1914        )
1915    }
1916
1917    fn get_tool(&self, name: &str) -> Option<Tool> {
1918        self.registry
1919            .inner
1920            .tools
1921            .get(name)
1922            .map(|entry| entry.protocol.clone())
1923    }
1924
1925    async fn list_tools(
1926        &self,
1927        request: Option<PaginatedRequestParams>,
1928        context: RequestContext<RoleServer>,
1929    ) -> Result<ListToolsResult, ErrorData> {
1930        let principal = mcp_server_principal(&context)
1931            .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1932        let (tools, next_cursor) = self.page(
1933            principal,
1934            request.as_ref().and_then(|value| value.cursor.as_deref()),
1935        )?;
1936        let mut result = ListToolsResult::with_all_items(tools)
1937            .with_ttl_ms(self.options.cache_ttl_ms)
1938            .with_cache_scope(self.options.cache_scope.into());
1939        result.next_cursor = next_cursor;
1940        Ok(result)
1941    }
1942
1943    async fn call_tool(
1944        &self,
1945        request: CallToolRequestParams,
1946        context: RequestContext<RoleServer>,
1947    ) -> Result<CallToolResponse, ErrorData> {
1948        self.dispatch(request, context).await
1949    }
1950}
1951
1952/// Invalid combination of frozen catalog and service policy.
1953#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1954#[non_exhaustive]
1955pub enum McpServerToolServiceBuildError {
1956    /// A catalog with scope-restricted entries cannot be shared-cacheable.
1957    #[error("scope-restricted MCP tools require a private catalog cache")]
1958    PublicCacheWithScopedTools,
1959}
1960
1961fn unavailable_tool() -> ErrorData {
1962    ErrorData::invalid_params("Unknown or unavailable tool", None)
1963}
1964
1965pub(crate) fn validate_inbound_mrtr(
1966    responses: &BTreeMap<String, Value>,
1967    request_state: Option<&str>,
1968) -> Result<(), ErrorData> {
1969    if responses.len() > MAX_INPUT_REQUESTS
1970        || request_state.is_some_and(|value| {
1971            value.is_empty()
1972                || value.len() > MAX_REQUEST_STATE_BYTES
1973                || value.chars().any(char::is_control)
1974        })
1975    {
1976        return Err(ErrorData::invalid_params(
1977            "Invalid MCP input response",
1978            None,
1979        ));
1980    }
1981    let value = serde_json::to_value(responses)
1982        .map_err(|_| ErrorData::invalid_params("Invalid MCP input response", None))?;
1983    if canonical_json_len(&value).map_or(true, |bytes| bytes > 8 * MEBIBYTE) {
1984        return Err(ErrorData::invalid_params(
1985            "Invalid MCP input response",
1986            None,
1987        ));
1988    }
1989    Ok(())
1990}
1991
1992fn build_tool_context(
1993    context: &RequestContext<RoleServer>,
1994    principal: McpServerPrincipal,
1995    call: &McpServerToolCall,
1996) -> Result<McpServerToolContext, ErrorData> {
1997    let client = context.client_info();
1998    if let Some(client) = &client {
1999        validate_client_component(&client.name)?;
2000        validate_client_component(&client.version)?;
2001    }
2002    let capabilities = context.client_capabilities().unwrap_or_default();
2003    let capabilities_value = serde_json::to_value(&capabilities)
2004        .map_err(|_| ErrorData::internal_error("Failed to retain client capabilities", None))?;
2005    let binding = request_state_binding(&principal, call)?;
2006    let progress = context
2007        .meta
2008        .get_progress_token()
2009        .map(|token| McpServerProgressSink {
2010            peer: context.peer.clone(),
2011            token,
2012        });
2013    Ok(McpServerToolContext {
2014        principal,
2015        client_name: client.as_ref().map(|value| Arc::from(value.name.as_str())),
2016        client_version: client
2017            .as_ref()
2018            .map(|value| Arc::from(value.version.as_str())),
2019        client_capabilities: Arc::new(capabilities_value),
2020        cancellation: context.ct.clone(),
2021        progress,
2022        request_state_binding: binding.into(),
2023    })
2024}
2025
2026fn validate_client_component(value: &str) -> Result<(), ErrorData> {
2027    if value.is_empty()
2028        || value.len() > 512
2029        || value.trim() != value
2030        || value.chars().any(char::is_control)
2031    {
2032        return Err(ErrorData::invalid_params(
2033            "Invalid MCP client identity",
2034            None,
2035        ));
2036    }
2037    Ok(())
2038}
2039
2040fn request_state_binding(
2041    principal: &McpServerPrincipal,
2042    call: &McpServerToolCall,
2043) -> Result<Vec<u8>, ErrorData> {
2044    let arguments = serde_json_canonicalizer::to_vec(&Value::Object((*call.arguments).clone()))
2045        .map_err(|_| ErrorData::internal_error("Failed to bind MCP request state", None))?;
2046    let mut material = b"stateknot/mcp-server/request-state/v1".to_vec();
2047    append_digest_part(&mut material, principal.subject().as_bytes());
2048    append_digest_part(&mut material, call.name().as_bytes());
2049    append_digest_part(&mut material, &arguments);
2050    Ok(Digest::sha256(material).as_bytes().to_vec())
2051}
2052
2053fn handler_error_result(error: McpServerToolHandlerError) -> ErrorData {
2054    match error {
2055        McpServerToolHandlerError::Unavailable => {
2056            ErrorData::internal_error("MCP tool dependency is unavailable", None)
2057        }
2058        McpServerToolHandlerError::Cancelled => {
2059            ErrorData::internal_error("MCP tool execution was cancelled", None)
2060        }
2061        McpServerToolHandlerError::Internal => {
2062            ErrorData::internal_error("MCP tool execution failed", None)
2063        }
2064        McpServerToolHandlerError::MissingRequiredClientCapability(capability) => {
2065            let mut required = ClientCapabilities::default();
2066            match capability {
2067                McpServerRequiredClientCapability::Elicitation => {
2068                    required.elicitation = Some(ElicitationCapability::default());
2069                }
2070                McpServerRequiredClientCapability::Sampling => {
2071                    required.sampling = Some(SamplingCapability::default());
2072                }
2073                McpServerRequiredClientCapability::Roots => {
2074                    required.roots = Some(RootsCapabilities::default());
2075                }
2076            }
2077            ErrorData::missing_required_client_capability(required)
2078        }
2079    }
2080}
2081
2082fn canonical_json_len(value: &Value) -> Result<usize, serde_json::Error> {
2083    serde_json_canonicalizer::to_vec(value).map(|bytes| bytes.len())
2084}
2085
2086#[cfg(test)]
2087mod tests {
2088    use std::sync::atomic::{AtomicUsize, Ordering};
2089
2090    use bytes::Bytes;
2091    use http::{Request, StatusCode};
2092    use http_body_util::{BodyExt as _, Full};
2093    use serde_json::json;
2094    use tower_service::Service as _;
2095
2096    use super::*;
2097    use crate::{McpServerAuthentication, McpServerHttpOptions, McpServerHttpService};
2098
2099    #[derive(Clone)]
2100    struct EchoHandler {
2101        calls: Arc<AtomicUsize>,
2102    }
2103
2104    impl McpServerToolHandler for EchoHandler {
2105        fn call(
2106            &self,
2107            call: McpServerToolCall,
2108            execution_context: McpServerToolContext,
2109        ) -> BoxFuture<'_, Result<McpServerToolOutcome, McpServerToolHandlerError>> {
2110            self.calls.fetch_add(1, Ordering::SeqCst);
2111            let subject = execution_context.principal().subject().to_owned();
2112            let value = call
2113                .arguments()
2114                .get("value")
2115                .cloned()
2116                .unwrap_or(Value::Null);
2117            Box::pin(async move {
2118                let block = McpServerContent::text(format!("{subject}:{value}"))
2119                    .map_err(|_| McpServerToolHandlerError::Internal)?;
2120                McpServerToolResult::structured([block], json!({ "echo": value }))
2121                    .map(Into::into)
2122                    .map_err(|_| McpServerToolHandlerError::Internal)
2123            })
2124        }
2125    }
2126
2127    #[derive(Clone, Copy)]
2128    struct MissingCapabilityHandler;
2129
2130    impl McpServerToolHandler for MissingCapabilityHandler {
2131        fn call(
2132            &self,
2133            _call: McpServerToolCall,
2134            _context: McpServerToolContext,
2135        ) -> BoxFuture<'_, Result<McpServerToolOutcome, McpServerToolHandlerError>> {
2136            Box::pin(async {
2137                Err(McpServerToolHandlerError::MissingRequiredClientCapability(
2138                    McpServerRequiredClientCapability::Sampling,
2139                ))
2140            })
2141        }
2142    }
2143
2144    #[derive(Clone)]
2145    struct DenyAuthorization {
2146        calls: Arc<AtomicUsize>,
2147    }
2148
2149    impl McpServerToolAuthorization for DenyAuthorization {
2150        fn authorize(
2151            &self,
2152            _request: McpServerToolAuthorizationRequest,
2153        ) -> BoxFuture<'_, Result<(), McpServerToolAuthorizationError>> {
2154            self.calls.fetch_add(1, Ordering::SeqCst);
2155            Box::pin(async { Err(McpServerToolAuthorizationError::Forbidden) })
2156        }
2157    }
2158
2159    fn echo_definition(name: &str) -> McpServerToolDefinition {
2160        McpServerToolDefinition::new(
2161            name,
2162            json!({
2163                "$schema": JSON_SCHEMA_2020_12,
2164                "type": "object",
2165                "properties": { "value": { "type": "string" } },
2166                "required": ["value"],
2167                "additionalProperties": false
2168            }),
2169        )
2170        .unwrap()
2171        .with_output_schema(json!({
2172            "$schema": JSON_SCHEMA_2020_12,
2173            "type": "object",
2174            "properties": { "echo": { "type": "string" } },
2175            "required": ["echo"],
2176            "additionalProperties": false
2177        }))
2178        .unwrap()
2179    }
2180
2181    fn tool_service<A>(
2182        definitions: impl IntoIterator<Item = McpServerToolDefinition>,
2183        handler_calls: &Arc<AtomicUsize>,
2184        authorization: A,
2185    ) -> McpServerHttpService<McpServerToolService>
2186    where
2187        A: McpServerToolAuthorization,
2188    {
2189        let mut builder = McpServerToolRegistryBuilder::default();
2190        for definition in definitions {
2191            builder
2192                .register(
2193                    definition,
2194                    EchoHandler {
2195                        calls: handler_calls.clone(),
2196                    },
2197                )
2198                .unwrap();
2199        }
2200        let options = McpServerApplicationOptions::new(
2201            "stateknot-tool-test",
2202            "0.0.0",
2203            1,
2204            Duration::from_secs(60),
2205            McpServerCacheScope::Private,
2206        )
2207        .unwrap();
2208        let handler =
2209            McpServerToolService::new(builder.build().unwrap(), options, authorization).unwrap();
2210        McpServerHttpService::new(
2211            handler,
2212            McpServerHttpOptions::loopback(32124).unwrap(),
2213            McpServerAuthentication::anonymous_loopback(),
2214        )
2215        .unwrap()
2216    }
2217
2218    fn protocol_request(
2219        method: &str,
2220        mut params: Value,
2221        name: Option<&str>,
2222    ) -> Request<Full<Bytes>> {
2223        params.as_object_mut().unwrap().insert(
2224            "_meta".to_owned(),
2225            json!({
2226                "io.modelcontextprotocol/protocolVersion": "2026-07-28",
2227                "io.modelcontextprotocol/clientInfo": {
2228                    "name": "stateknot-tool-test-client",
2229                    "version": "0.0.0"
2230                },
2231                "io.modelcontextprotocol/clientCapabilities": {}
2232            }),
2233        );
2234        let body = serde_json::to_vec(&json!({
2235            "jsonrpc": "2.0",
2236            "id": 1,
2237            "method": method,
2238            "params": params
2239        }))
2240        .unwrap();
2241        let mut builder = Request::builder()
2242            .method("POST")
2243            .uri("http://127.0.0.1:32124/mcp")
2244            .header("host", "127.0.0.1:32124")
2245            .header("origin", "http://127.0.0.1:32124")
2246            .header("content-type", "application/json")
2247            .header("accept", "application/json, text/event-stream")
2248            .header("mcp-protocol-version", "2026-07-28")
2249            .header("mcp-method", method);
2250        if let Some(name) = name {
2251            builder = builder.header("mcp-name", name);
2252        }
2253        builder.body(Full::new(Bytes::from(body))).unwrap()
2254    }
2255
2256    async fn invoke(
2257        service: &mut McpServerHttpService<McpServerToolService>,
2258        method: &str,
2259        params: Value,
2260        name: Option<&str>,
2261    ) -> (StatusCode, Value) {
2262        let response = service
2263            .call(protocol_request(method, params, name))
2264            .await
2265            .unwrap();
2266        let status = response.status();
2267        let bytes = response.into_body().collect().await.unwrap().to_bytes();
2268        let value = serde_json::from_slice(&bytes).unwrap_or_else(|error| {
2269            panic!(
2270                "invalid MCP response ({status}): {}; {error}",
2271                String::from_utf8_lossy(&bytes)
2272            )
2273        });
2274        (status, value)
2275    }
2276
2277    #[test]
2278    fn registry_is_sorted_offline_and_rejects_remote_refs() {
2279        let calls = Arc::new(AtomicUsize::new(0));
2280        let mut builder = McpServerToolRegistryBuilder::default();
2281        for name in ["zeta", "alpha"] {
2282            builder
2283                .register(
2284                    echo_definition(name),
2285                    EchoHandler {
2286                        calls: calls.clone(),
2287                    },
2288                )
2289                .unwrap();
2290        }
2291        let registry = builder.build().unwrap();
2292        assert_eq!(
2293            registry
2294                .definitions()
2295                .map(McpServerToolDefinition::name)
2296                .collect::<Vec<_>>(),
2297            ["alpha", "zeta"]
2298        );
2299
2300        let mut remote = McpServerToolRegistryBuilder::default();
2301        remote
2302            .register(
2303                McpServerToolDefinition::new(
2304                    "remote",
2305                    json!({
2306                        "$schema": JSON_SCHEMA_2020_12,
2307                        "$ref": "https://schemas.example.test/remote.json"
2308                    }),
2309                )
2310                .unwrap(),
2311                EchoHandler { calls },
2312            )
2313            .unwrap();
2314        assert!(matches!(
2315            remote.build(),
2316            Err(McpServerToolRegistryError::SchemaCompilation { .. })
2317        ));
2318    }
2319
2320    #[test]
2321    fn content_and_results_are_bounded() {
2322        assert!(McpServerContent::image([1_u8, 2, 3], "image/png").is_ok());
2323        assert!(matches!(
2324            McpServerContent::audio([1_u8], "image/png"),
2325            Err(McpServerContentError::Invalid)
2326        ));
2327        assert!(matches!(
2328            McpServerContent::text("x".repeat(MAX_TEXT_CONTENT_BYTES + 1)),
2329            Err(McpServerContentError::TooLarge)
2330        ));
2331    }
2332
2333    #[test]
2334    fn request_state_is_bound_expires_and_redacts_keys() {
2335        let codec = McpServerRequestStateCodec::new([7_u8; 32]).unwrap();
2336        assert!(!format!("{codec:?}").contains("777"));
2337        let binding = b"tenant-a|tool-a";
2338        let sealed = codec
2339            .seal_json(&json!({ "round": 1 }), binding, Duration::from_secs(60))
2340            .unwrap();
2341        assert_eq!(
2342            codec.open_json(&sealed, binding).unwrap(),
2343            json!({ "round": 1 })
2344        );
2345        assert!(matches!(
2346            codec.open_json(&sealed, b"tenant-b|tool-a"),
2347            Err(McpServerRequestStateError::InvalidState)
2348        ));
2349        assert!(matches!(
2350            codec.seal_json(&json!({}), binding, Duration::ZERO),
2351            Err(McpServerRequestStateError::InvalidOperation)
2352        ));
2353    }
2354
2355    #[test]
2356    fn tool_names_and_scopes_fail_closed() {
2357        assert!(matches!(
2358            McpServerToolDefinition::new("not allowed", json!({ "type": "object" })),
2359            Err(McpServerToolDefinitionError::InvalidName)
2360        ));
2361        assert!(matches!(
2362            echo_definition("echo").with_required_scopes(["tool:call", "tool:call"]),
2363            Err(McpServerToolDefinitionError::DuplicateScope)
2364        ));
2365    }
2366
2367    #[tokio::test]
2368    async fn frozen_registry_pages_and_dispatches_through_the_http_boundary() {
2369        let handler_calls = Arc::new(AtomicUsize::new(0));
2370        let mut service = tool_service(
2371            [echo_definition("zeta"), echo_definition("alpha")],
2372            &handler_calls,
2373            AllowMcpServerToolAuthorization,
2374        );
2375
2376        let (status, first) = invoke(&mut service, "tools/list", json!({}), None).await;
2377        assert_eq!(status, StatusCode::OK);
2378        assert_eq!(first.pointer("/result/tools/0/name"), Some(&json!("alpha")));
2379        assert_eq!(first.pointer("/result/ttlMs"), Some(&json!(60_000)));
2380        assert_eq!(first.pointer("/result/cacheScope"), Some(&json!("private")));
2381        let cursor = first
2382            .pointer("/result/nextCursor")
2383            .and_then(Value::as_str)
2384            .unwrap();
2385        let (status, second) = invoke(
2386            &mut service,
2387            "tools/list",
2388            json!({ "cursor": cursor }),
2389            None,
2390        )
2391        .await;
2392        assert_eq!(status, StatusCode::OK);
2393        assert_eq!(second.pointer("/result/tools/0/name"), Some(&json!("zeta")));
2394        assert!(second.pointer("/result/nextCursor").is_none());
2395
2396        let (status, invalid) = invoke(
2397            &mut service,
2398            "tools/call",
2399            json!({ "name": "alpha", "arguments": { "value": 7 } }),
2400            Some("alpha"),
2401        )
2402        .await;
2403        assert_eq!(status, StatusCode::BAD_REQUEST);
2404        assert_eq!(invalid.pointer("/error/code"), Some(&json!(-32602)));
2405        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
2406
2407        let (status, valid) = invoke(
2408            &mut service,
2409            "tools/call",
2410            json!({ "name": "alpha", "arguments": { "value": "ok" } }),
2411            Some("alpha"),
2412        )
2413        .await;
2414        assert_eq!(status, StatusCode::OK);
2415        assert_eq!(
2416            valid.pointer("/result/structuredContent/echo"),
2417            Some(&json!("ok"))
2418        );
2419        assert_eq!(valid.pointer("/result/isError"), Some(&json!(false)));
2420        assert_eq!(handler_calls.load(Ordering::SeqCst), 1);
2421    }
2422
2423    #[tokio::test]
2424    async fn decoded_authorization_precedes_schema_diagnostics_and_dispatch() {
2425        let handler_calls = Arc::new(AtomicUsize::new(0));
2426        let authorization_calls = Arc::new(AtomicUsize::new(0));
2427        let mut service = tool_service(
2428            [echo_definition("protected")],
2429            &handler_calls,
2430            DenyAuthorization {
2431                calls: authorization_calls.clone(),
2432            },
2433        );
2434        let (status, denied) = invoke(
2435            &mut service,
2436            "tools/call",
2437            json!({ "name": "protected", "arguments": { "value": 7 } }),
2438            Some("protected"),
2439        )
2440        .await;
2441        assert_eq!(status, StatusCode::BAD_REQUEST);
2442        assert_eq!(denied.pointer("/error/code"), Some(&json!(-32602)));
2443        assert_eq!(
2444            denied.pointer("/error/message"),
2445            Some(&json!("Unknown or unavailable tool"))
2446        );
2447        assert_eq!(authorization_calls.load(Ordering::SeqCst), 1);
2448        assert_eq!(handler_calls.load(Ordering::SeqCst), 0);
2449    }
2450
2451    #[tokio::test]
2452    async fn handler_can_report_a_missing_core_client_capability() {
2453        let mut builder = McpServerToolRegistryBuilder::default();
2454        builder
2455            .register(echo_definition("needs_sampling"), MissingCapabilityHandler)
2456            .unwrap();
2457        let options = McpServerApplicationOptions::new(
2458            "stateknot-capability-test",
2459            "0.0.0",
2460            10,
2461            Duration::from_secs(60),
2462            McpServerCacheScope::Private,
2463        )
2464        .unwrap();
2465        let handler = McpServerToolService::new(
2466            builder.build().unwrap(),
2467            options,
2468            AllowMcpServerToolAuthorization,
2469        )
2470        .unwrap();
2471        let mut service = McpServerHttpService::new(
2472            handler,
2473            McpServerHttpOptions::loopback(32124).unwrap(),
2474            McpServerAuthentication::anonymous_loopback(),
2475        )
2476        .unwrap();
2477
2478        let (status, response) = invoke(
2479            &mut service,
2480            "tools/call",
2481            json!({ "name": "needs_sampling", "arguments": { "value": "ok" } }),
2482            Some("needs_sampling"),
2483        )
2484        .await;
2485        assert_eq!(status, StatusCode::BAD_REQUEST);
2486        assert_eq!(response.pointer("/error/code"), Some(&json!(-32021)));
2487        assert_eq!(
2488            response.pointer("/error/data/requiredCapabilities/sampling"),
2489            Some(&json!({}))
2490        );
2491    }
2492}