Skip to main content

stateknot_core/
tool.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Provider- and protocol-neutral tool descriptor contracts.
5
6use std::fmt;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Deserializer, Serialize, de};
10use thiserror::Error;
11
12use crate::{
13    ByteCount, CapabilityKind, CapabilityMetadata, DurationMillis, ExecutionCount, SchemaReference,
14};
15
16/// External side-effect class declared by a trusted tool registry.
17///
18/// This value is a reviewed semantic claim, not a fact inferred from an HTTP
19/// method, provider annotation, or model output. Retry remains subject to the
20/// full execution contract, failure advice, deadline, budget, and policy.
21#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
22#[serde(rename_all = "snake_case")]
23pub enum ToolRisk {
24    /// The tool does not intentionally change externally observable state.
25    ReadOnly,
26    /// Repeating the same logical write is safe under the declared mechanism.
27    IdempotentWrite,
28    /// Repeating the write may create an additional external effect.
29    NonIdempotentWrite,
30}
31
32/// Mechanism governing repeated invocation of a tool operation.
33#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
34#[serde(rename_all = "snake_case")]
35pub enum ToolIdempotency {
36    /// Idempotency is irrelevant because the tool is read-only.
37    NotApplicable,
38    /// Identical canonical arguments are intrinsically safe to repeat.
39    Intrinsic,
40    /// The runtime must provide the same durable idempotency key on every attempt.
41    RequiredKey,
42    /// The tool cannot guarantee that a repeated write has one business effect.
43    Unsupported,
44}
45
46/// Validated side-effect and recovery semantics for one tool version.
47///
48/// Status-query support means an implementation can reconcile an ambiguous
49/// invocation outcome. Compensation support means a separately authorized
50/// recovery operation exists; it does not make the original write atomic or
51/// erase its audit history.
52#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
53#[serde(deny_unknown_fields)]
54pub struct ToolExecutionSemantics {
55    risk: ToolRisk,
56    idempotency: ToolIdempotency,
57    status_query: bool,
58    compensation: bool,
59}
60
61impl ToolExecutionSemantics {
62    /// Constructs a cross-field validated execution contract.
63    ///
64    /// # Errors
65    ///
66    /// Returns [`ToolExecutionSemanticsError`] when risk and idempotency
67    /// conflict, or when a read-only tool claims write-recovery operations.
68    pub const fn new(
69        risk: ToolRisk,
70        idempotency: ToolIdempotency,
71        status_query: bool,
72        compensation: bool,
73    ) -> Result<Self, ToolExecutionSemanticsError> {
74        let idempotency_is_valid = matches!(
75            (risk, idempotency),
76            (ToolRisk::ReadOnly, ToolIdempotency::NotApplicable)
77                | (
78                    ToolRisk::IdempotentWrite,
79                    ToolIdempotency::Intrinsic | ToolIdempotency::RequiredKey
80                )
81                | (ToolRisk::NonIdempotentWrite, ToolIdempotency::Unsupported)
82        );
83        if !idempotency_is_valid {
84            return Err(ToolExecutionSemanticsError::InvalidIdempotency { risk, idempotency });
85        }
86        if matches!(risk, ToolRisk::ReadOnly) && (status_query || compensation) {
87            return Err(ToolExecutionSemanticsError::ReadOnlyRecoverySupport {
88                status_query,
89                compensation,
90            });
91        }
92        Ok(Self {
93            risk,
94            idempotency,
95            status_query,
96            compensation,
97        })
98    }
99
100    /// Returns the reviewed external side-effect class.
101    #[must_use]
102    pub const fn risk(&self) -> ToolRisk {
103        self.risk
104    }
105
106    /// Returns the declared repeated-invocation mechanism.
107    #[must_use]
108    pub const fn idempotency(&self) -> ToolIdempotency {
109        self.idempotency
110    }
111
112    /// Returns whether ambiguous outcomes can be queried authoritatively.
113    #[must_use]
114    pub const fn supports_status_query(&self) -> bool {
115        self.status_query
116    }
117
118    /// Returns whether a separately authorized compensation operation exists.
119    #[must_use]
120    pub const fn supports_compensation(&self) -> bool {
121        self.compensation
122    }
123
124    /// Returns whether the runtime must supply a durable idempotency key.
125    #[must_use]
126    pub const fn requires_idempotency_key(&self) -> bool {
127        matches!(self.idempotency, ToolIdempotency::RequiredKey)
128    }
129}
130
131#[derive(Deserialize)]
132#[serde(deny_unknown_fields)]
133struct ToolExecutionSemanticsWire {
134    risk: ToolRisk,
135    idempotency: ToolIdempotency,
136    status_query: bool,
137    compensation: bool,
138}
139
140impl<'de> Deserialize<'de> for ToolExecutionSemantics {
141    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
142    where
143        D: Deserializer<'de>,
144    {
145        let wire = ToolExecutionSemanticsWire::deserialize(deserializer)?;
146        Self::new(
147            wire.risk,
148            wire.idempotency,
149            wire.status_query,
150            wire.compensation,
151        )
152        .map_err(de::Error::custom)
153    }
154}
155
156/// Invalid tool side-effect and recovery semantics.
157#[derive(Clone, Debug, Eq, Error, PartialEq)]
158#[non_exhaustive]
159pub enum ToolExecutionSemanticsError {
160    /// The idempotency mechanism does not match the declared risk class.
161    #[error("tool risk {risk:?} is incompatible with idempotency {idempotency:?}")]
162    InvalidIdempotency {
163        /// Declared side-effect class.
164        risk: ToolRisk,
165        /// Conflicting repeated-invocation mechanism.
166        idempotency: ToolIdempotency,
167    },
168
169    /// A read-only tool declared write-recovery behavior.
170    #[error(
171        "read-only tool cannot declare status-query={status_query} or compensation={compensation}"
172    )]
173    ReadOnlyRecoverySupport {
174        /// Invalid status-query declaration.
175        status_query: bool,
176        /// Invalid compensation declaration.
177        compensation: bool,
178    },
179}
180
181/// Broad resource access required by a tool implementation.
182///
183/// Exact destinations, paths, operations, and credential handles live in a
184/// tenant-controlled executor profile. This declaration can only cause policy
185/// to require or deny access; it never grants access by itself.
186#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
187#[serde(rename_all = "snake_case")]
188pub enum ToolResourceAccess {
189    /// No access to the resource category is required.
190    None,
191    /// The tool only reads from the resource category.
192    ReadOnly,
193    /// The tool may read and write the resource category.
194    ReadWrite,
195}
196
197/// Resource categories that must be satisfied by an executor profile.
198///
199/// `dynamic_code` means the tool executes code supplied at invocation time. It
200/// does not describe ordinary compiled tool implementation code. `StateKnot` v1
201/// does not provide a built-in arbitrary-code sandbox; policy may route such a
202/// tool to an independently operated sandbox service or deny it.
203#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
204#[serde(deny_unknown_fields)]
205pub struct ToolResourceRequirements {
206    network: ToolResourceAccess,
207    filesystem: ToolResourceAccess,
208    credentials: bool,
209    dynamic_code: bool,
210}
211
212impl ToolResourceRequirements {
213    /// Constructs explicit resource-category requirements.
214    #[must_use]
215    pub const fn new(
216        network: ToolResourceAccess,
217        filesystem: ToolResourceAccess,
218        credentials: bool,
219        dynamic_code: bool,
220    ) -> Self {
221        Self {
222            network,
223            filesystem,
224            credentials,
225            dynamic_code,
226        }
227    }
228
229    /// Constructs a tool requiring no external resource category.
230    #[must_use]
231    pub const fn none() -> Self {
232        Self::new(
233            ToolResourceAccess::None,
234            ToolResourceAccess::None,
235            false,
236            false,
237        )
238    }
239
240    /// Returns the broad network access declaration.
241    #[must_use]
242    pub const fn network(&self) -> ToolResourceAccess {
243        self.network
244    }
245
246    /// Returns the broad filesystem access declaration.
247    #[must_use]
248    pub const fn filesystem(&self) -> ToolResourceAccess {
249        self.filesystem
250    }
251
252    /// Returns whether opaque credentials must be resolved for an invocation.
253    #[must_use]
254    pub const fn requires_credentials(&self) -> bool {
255        self.credentials
256    }
257
258    /// Returns whether invocation-supplied code is executed.
259    #[must_use]
260    pub const fn executes_dynamic_code(&self) -> bool {
261        self.dynamic_code
262    }
263
264    /// Returns whether a declared resource category may be written.
265    #[must_use]
266    pub const fn has_write_access(&self) -> bool {
267        matches!(self.network, ToolResourceAccess::ReadWrite)
268            || matches!(self.filesystem, ToolResourceAccess::ReadWrite)
269    }
270}
271
272/// Cancellation behavior exposed by a tool implementation.
273#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
274#[serde(rename_all = "snake_case")]
275pub enum ToolCancellationSupport {
276    /// The implementation has no cancellation entry point.
277    Unsupported,
278    /// The implementation observes cancellation on a best-effort basis.
279    Cooperative,
280}
281
282/// Runtime-facing optional behavior supported by a tool implementation.
283///
284/// Cooperative cancellation never proves that an external effect did not
285/// occur. Progress events are observational and cannot commit tool success.
286#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
287#[serde(deny_unknown_fields)]
288pub struct ToolInvocationCapabilities {
289    cancellation: ToolCancellationSupport,
290    max_progress_events: ExecutionCount,
291}
292
293impl ToolInvocationCapabilities {
294    /// Constructs invocation behavior flags.
295    #[must_use]
296    pub const fn new(
297        cancellation: ToolCancellationSupport,
298        max_progress_events: ExecutionCount,
299    ) -> Self {
300        Self {
301            cancellation,
302            max_progress_events,
303        }
304    }
305
306    /// Returns the supported cancellation mode.
307    #[must_use]
308    pub const fn cancellation(&self) -> ToolCancellationSupport {
309        self.cancellation
310    }
311
312    /// Returns whether bounded progress events may be emitted.
313    #[must_use]
314    pub const fn supports_progress_events(&self) -> bool {
315        self.max_progress_events.get() != 0
316    }
317
318    /// Returns the maximum progress events emitted by one invocation.
319    #[must_use]
320    pub const fn max_progress_events(&self) -> ExecutionCount {
321        self.max_progress_events
322    }
323}
324
325/// Finite per-invocation execution ceilings declared by a tool version.
326///
327/// System, tenant, policy, run, and descriptor limits are intersected; these
328/// values can never widen another layer. `max_total_artifact_bytes` covers all
329/// artifacts produced by one invocation, not one artifact or a complete run.
330#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
331#[serde(deny_unknown_fields)]
332pub struct ToolExecutionLimits {
333    timeout: DurationMillis,
334    max_concurrency: ExecutionCount,
335    max_input_bytes: ByteCount,
336    max_inline_result_bytes: ByteCount,
337    max_artifacts: ExecutionCount,
338    max_total_artifact_bytes: ByteCount,
339}
340
341impl ToolExecutionLimits {
342    /// Constructs finite limits and validates unusable zero combinations.
343    ///
344    /// # Errors
345    ///
346    /// Returns [`ToolExecutionLimitsError`] when timeout, concurrency, or
347    /// input/inline result capacity is zero, or when artifact count and byte
348    /// capacity disagree about whether artifacts are permitted.
349    pub const fn new(
350        timeout: DurationMillis,
351        max_concurrency: ExecutionCount,
352        max_input_bytes: ByteCount,
353        max_inline_result_bytes: ByteCount,
354        max_artifacts: ExecutionCount,
355        max_total_artifact_bytes: ByteCount,
356    ) -> Result<Self, ToolExecutionLimitsError> {
357        if timeout.as_i64() == 0 {
358            return Err(ToolExecutionLimitsError::ZeroTimeout);
359        }
360        if max_concurrency.get() == 0 {
361            return Err(ToolExecutionLimitsError::ZeroConcurrency);
362        }
363        if max_input_bytes.get() == 0 {
364            return Err(ToolExecutionLimitsError::ZeroInputBytes);
365        }
366        if max_inline_result_bytes.get() == 0 {
367            return Err(ToolExecutionLimitsError::ZeroInlineResultBytes);
368        }
369        if (max_artifacts.get() == 0) != (max_total_artifact_bytes.get() == 0) {
370            return Err(ToolExecutionLimitsError::ArtifactCapacityMismatch {
371                max_artifacts,
372                max_total_artifact_bytes,
373            });
374        }
375        Ok(Self {
376            timeout,
377            max_concurrency,
378            max_input_bytes,
379            max_inline_result_bytes,
380            max_artifacts,
381            max_total_artifact_bytes,
382        })
383    }
384
385    /// Returns the maximum elapsed time for one invocation attempt.
386    #[must_use]
387    pub const fn timeout(&self) -> DurationMillis {
388        self.timeout
389    }
390
391    /// Returns the maximum concurrent calls for this capability version.
392    #[must_use]
393    pub const fn max_concurrency(&self) -> ExecutionCount {
394        self.max_concurrency
395    }
396
397    /// Returns the maximum compact encoded argument bytes for one invocation.
398    #[must_use]
399    pub const fn max_input_bytes(&self) -> ByteCount {
400        self.max_input_bytes
401    }
402
403    /// Returns the maximum inline result bytes from one invocation.
404    #[must_use]
405    pub const fn max_inline_result_bytes(&self) -> ByteCount {
406        self.max_inline_result_bytes
407    }
408
409    /// Returns the maximum number of artifacts from one invocation.
410    #[must_use]
411    pub const fn max_artifacts(&self) -> ExecutionCount {
412        self.max_artifacts
413    }
414
415    /// Returns the maximum total artifact bytes from one invocation.
416    #[must_use]
417    pub const fn max_total_artifact_bytes(&self) -> ByteCount {
418        self.max_total_artifact_bytes
419    }
420}
421
422#[derive(Deserialize)]
423#[serde(deny_unknown_fields)]
424struct ToolExecutionLimitsWire {
425    timeout: DurationMillis,
426    max_concurrency: ExecutionCount,
427    max_input_bytes: ByteCount,
428    max_inline_result_bytes: ByteCount,
429    max_artifacts: ExecutionCount,
430    max_total_artifact_bytes: ByteCount,
431}
432
433impl<'de> Deserialize<'de> for ToolExecutionLimits {
434    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
435    where
436        D: Deserializer<'de>,
437    {
438        let wire = ToolExecutionLimitsWire::deserialize(deserializer)?;
439        Self::new(
440            wire.timeout,
441            wire.max_concurrency,
442            wire.max_input_bytes,
443            wire.max_inline_result_bytes,
444            wire.max_artifacts,
445            wire.max_total_artifact_bytes,
446        )
447        .map_err(de::Error::custom)
448    }
449}
450
451/// Invalid per-invocation tool limits.
452#[derive(Clone, Debug, Eq, Error, PartialEq)]
453#[non_exhaustive]
454pub enum ToolExecutionLimitsError {
455    /// A zero timeout would make every invocation ineligible.
456    #[error("tool timeout must be greater than zero milliseconds")]
457    ZeroTimeout,
458
459    /// A zero concurrency ceiling would make every invocation ineligible.
460    #[error("tool max concurrency must be greater than zero")]
461    ZeroConcurrency,
462
463    /// Schema validation and invocation require a positive argument capacity.
464    #[error("tool max input bytes must be greater than zero")]
465    ZeroInputBytes,
466
467    /// A successful inline result needs a positive encoded byte capacity.
468    #[error("tool max inline result bytes must be greater than zero")]
469    ZeroInlineResultBytes,
470
471    /// Artifact count and total bytes disagreed about artifact support.
472    #[error(
473        "tool artifact capacity requires both count and bytes to be zero or both to be positive"
474    )]
475    ArtifactCapacityMismatch {
476        /// Declared maximum artifact count.
477        max_artifacts: ExecutionCount,
478        /// Declared maximum total artifact bytes.
479        max_total_artifact_bytes: ByteCount,
480    },
481}
482
483/// Immutable, protocol-neutral description of one executable tool version.
484///
485/// Schema references are identities only. Before registration, a trusted local
486/// schema registry verifies their digests, JSON Schema 2020-12 documents, and
487/// provider compatibility profile. Before selection, the tenant registry
488/// authenticates metadata ownership, applies policy, and snapshots this exact
489/// descriptor for the invocation attempt.
490#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
491#[serde(deny_unknown_fields)]
492pub struct ToolDescriptor {
493    metadata: CapabilityMetadata,
494    input_schema: SchemaReference,
495    output_schema: SchemaReference,
496    semantics: ToolExecutionSemantics,
497    resources: ToolResourceRequirements,
498    invocation: ToolInvocationCapabilities,
499    limits: ToolExecutionLimits,
500}
501
502impl ToolDescriptor {
503    /// Constructs a descriptor and validates cross-component invariants.
504    ///
505    /// # Errors
506    ///
507    /// Returns [`ToolDescriptorError`] when common metadata is not a tool or a
508    /// read-only tool declares network/filesystem write access.
509    pub fn new(
510        metadata: CapabilityMetadata,
511        input_schema: SchemaReference,
512        output_schema: SchemaReference,
513        semantics: ToolExecutionSemantics,
514        resources: ToolResourceRequirements,
515        invocation: ToolInvocationCapabilities,
516        limits: ToolExecutionLimits,
517    ) -> Result<Self, ToolDescriptorError> {
518        if metadata.kind() != CapabilityKind::Tool {
519            return Err(ToolDescriptorError::WrongCapabilityKind {
520                actual: metadata.kind(),
521            });
522        }
523        if semantics.risk() == ToolRisk::ReadOnly && resources.has_write_access() {
524            return Err(ToolDescriptorError::ReadOnlyResourceWrite {
525                network: resources.network(),
526                filesystem: resources.filesystem(),
527            });
528        }
529        Ok(Self {
530            metadata,
531            input_schema,
532            output_schema,
533            semantics,
534            resources,
535            invocation,
536            limits,
537        })
538    }
539
540    /// Returns common identity, discovery, lifecycle, scope, and extension data.
541    #[must_use]
542    pub const fn metadata(&self) -> &CapabilityMetadata {
543        &self.metadata
544    }
545
546    /// Returns the immutable input schema identity.
547    #[must_use]
548    pub const fn input_schema(&self) -> &SchemaReference {
549        &self.input_schema
550    }
551
552    /// Returns the immutable output schema identity.
553    #[must_use]
554    pub const fn output_schema(&self) -> &SchemaReference {
555        &self.output_schema
556    }
557
558    /// Returns side-effect, idempotency, and recovery semantics.
559    #[must_use]
560    pub const fn semantics(&self) -> &ToolExecutionSemantics {
561        &self.semantics
562    }
563
564    /// Returns resource categories that an executor profile must satisfy.
565    #[must_use]
566    pub const fn resources(&self) -> &ToolResourceRequirements {
567        &self.resources
568    }
569
570    /// Returns optional invocation behavior implemented by this tool.
571    #[must_use]
572    pub const fn invocation(&self) -> &ToolInvocationCapabilities {
573        &self.invocation
574    }
575
576    /// Returns finite per-invocation ceilings.
577    #[must_use]
578    pub const fn limits(&self) -> &ToolExecutionLimits {
579        &self.limits
580    }
581}
582
583impl fmt::Debug for ToolDescriptor {
584    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
585        formatter
586            .debug_struct("ToolDescriptor")
587            .field("metadata", &self.metadata)
588            .field("input_schema", &self.input_schema)
589            .field("output_schema", &self.output_schema)
590            .field("semantics", &self.semantics)
591            .field("resources", &self.resources)
592            .field("invocation", &self.invocation)
593            .field("limits", &self.limits)
594            .finish_non_exhaustive()
595    }
596}
597
598#[derive(Deserialize)]
599#[serde(deny_unknown_fields)]
600struct ToolDescriptorWire {
601    metadata: CapabilityMetadata,
602    input_schema: SchemaReference,
603    output_schema: SchemaReference,
604    semantics: ToolExecutionSemantics,
605    resources: ToolResourceRequirements,
606    invocation: ToolInvocationCapabilities,
607    limits: ToolExecutionLimits,
608}
609
610impl<'de> Deserialize<'de> for ToolDescriptor {
611    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
612    where
613        D: Deserializer<'de>,
614    {
615        let wire = ToolDescriptorWire::deserialize(deserializer)?;
616        Self::new(
617            wire.metadata,
618            wire.input_schema,
619            wire.output_schema,
620            wire.semantics,
621            wire.resources,
622            wire.invocation,
623            wire.limits,
624        )
625        .map_err(de::Error::custom)
626    }
627}
628
629/// Invalid cross-component tool descriptor.
630#[derive(Clone, Debug, Eq, Error, PartialEq)]
631#[non_exhaustive]
632pub enum ToolDescriptorError {
633    /// Common metadata classified the capability as something other than a tool.
634    #[error("tool descriptor requires kind=tool, received {actual:?}")]
635    WrongCapabilityKind {
636        /// Conflicting capability kind.
637        actual: CapabilityKind,
638    },
639
640    /// A read-only tool requested write access to a broad resource category.
641    #[error(
642        "read-only tool cannot declare network={network:?} or filesystem={filesystem:?} write access"
643    )]
644    ReadOnlyResourceWrite {
645        /// Conflicting network access.
646        network: ToolResourceAccess,
647        /// Conflicting filesystem access.
648        filesystem: ToolResourceAccess,
649    },
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655    use proptest::prelude::*;
656    use serde_json::{Value, from_value, json, to_value};
657
658    use crate::{
659        BoundedJson, CapabilityDescription, CapabilityIdentity, CapabilityLifecycle,
660        CapabilityName, CapabilityReference, CapabilityTitle, Digest, ExtensionKey, ExtensionValue,
661        Extensions, IssuerId, PrincipalIdentity, SchemaId, ScopeSet, SubjectId, Version,
662    };
663
664    fn principal() -> PrincipalIdentity {
665        PrincipalIdentity::new(
666            "https://issuer.example.com/tenant"
667                .parse::<IssuerId>()
668                .unwrap(),
669            "registry-owner".parse::<SubjectId>().unwrap(),
670        )
671    }
672
673    fn metadata(kind: CapabilityKind, secret: &str) -> CapabilityMetadata {
674        let identity = CapabilityIdentity::new(
675            principal(),
676            CapabilityReference::new(
677                "payments.capture".parse::<CapabilityName>().unwrap(),
678                Version::new(2, 1, 0),
679            ),
680        );
681        let extensions = Extensions::try_new([(
682            ExtensionKey::new("com.example.tool").unwrap(),
683            ExtensionValue::opaque(
684                BoundedJson::try_from_value(json!({ "secret": secret })).unwrap(),
685            ),
686        )])
687        .unwrap();
688        CapabilityMetadata::new(
689            identity,
690            kind,
691            Some(CapabilityTitle::new(format!("Capture payment {secret}")).unwrap()),
692            CapabilityDescription::new(format!("Capture one approved payment. {secret}")).unwrap(),
693            CapabilityLifecycle::active(),
694            ScopeSet::empty(),
695            extensions,
696        )
697        .unwrap()
698    }
699
700    fn schema(name: &str) -> SchemaReference {
701        SchemaReference::new(
702            format!("https://schemas.example.com/tools/{name}/1.0.0")
703                .parse::<SchemaId>()
704                .unwrap(),
705            Version::new(1, 0, 0),
706            Digest::sha256(name),
707        )
708    }
709
710    fn read_only_semantics() -> ToolExecutionSemantics {
711        ToolExecutionSemantics::new(
712            ToolRisk::ReadOnly,
713            ToolIdempotency::NotApplicable,
714            false,
715            false,
716        )
717        .unwrap()
718    }
719
720    fn default_limits() -> ToolExecutionLimits {
721        ToolExecutionLimits::new(
722            DurationMillis::new(30_000).unwrap(),
723            ExecutionCount::new(16),
724            ByteCount::new(64 * 1024),
725            ByteCount::new(256 * 1024),
726            ExecutionCount::new(4),
727            ByteCount::new(25 * 1024 * 1024),
728        )
729        .unwrap()
730    }
731
732    fn descriptor(secret: &str) -> ToolDescriptor {
733        ToolDescriptor::new(
734            metadata(CapabilityKind::Tool, secret),
735            schema("capture-input"),
736            schema("capture-output"),
737            ToolExecutionSemantics::new(
738                ToolRisk::IdempotentWrite,
739                ToolIdempotency::RequiredKey,
740                true,
741                true,
742            )
743            .unwrap(),
744            ToolResourceRequirements::new(
745                ToolResourceAccess::ReadWrite,
746                ToolResourceAccess::None,
747                true,
748                false,
749            ),
750            ToolInvocationCapabilities::new(
751                ToolCancellationSupport::Cooperative,
752                ExecutionCount::new(128),
753            ),
754            default_limits(),
755        )
756        .unwrap()
757    }
758
759    #[test]
760    fn tool_enums_have_closed_canonical_wire_values() {
761        for (value, expected) in [
762            (ToolRisk::ReadOnly, "read_only"),
763            (ToolRisk::IdempotentWrite, "idempotent_write"),
764            (ToolRisk::NonIdempotentWrite, "non_idempotent_write"),
765        ] {
766            assert_eq!(to_value(value).unwrap(), Value::from(expected));
767            assert_eq!(from_value::<ToolRisk>(json!(expected)).unwrap(), value);
768        }
769        for (value, expected) in [
770            (ToolIdempotency::NotApplicable, "not_applicable"),
771            (ToolIdempotency::Intrinsic, "intrinsic"),
772            (ToolIdempotency::RequiredKey, "required_key"),
773            (ToolIdempotency::Unsupported, "unsupported"),
774        ] {
775            assert_eq!(to_value(value).unwrap(), Value::from(expected));
776            assert_eq!(
777                from_value::<ToolIdempotency>(json!(expected)).unwrap(),
778                value
779            );
780        }
781        for (value, expected) in [
782            (ToolResourceAccess::None, "none"),
783            (ToolResourceAccess::ReadOnly, "read_only"),
784            (ToolResourceAccess::ReadWrite, "read_write"),
785        ] {
786            assert_eq!(to_value(value).unwrap(), Value::from(expected));
787            assert_eq!(
788                from_value::<ToolResourceAccess>(json!(expected)).unwrap(),
789                value
790            );
791        }
792        for (value, expected) in [
793            (ToolCancellationSupport::Unsupported, "unsupported"),
794            (ToolCancellationSupport::Cooperative, "cooperative"),
795        ] {
796            assert_eq!(to_value(value).unwrap(), Value::from(expected));
797            assert_eq!(
798                from_value::<ToolCancellationSupport>(json!(expected)).unwrap(),
799                value
800            );
801        }
802        assert!(from_value::<ToolRisk>(json!("unknown")).is_err());
803        assert!(from_value::<ToolIdempotency>(Value::Null).is_err());
804        assert!(from_value::<ToolResourceAccess>(json!(42)).is_err());
805    }
806
807    #[test]
808    fn execution_semantics_reject_every_incoherent_pair() {
809        let risks = [
810            ToolRisk::ReadOnly,
811            ToolRisk::IdempotentWrite,
812            ToolRisk::NonIdempotentWrite,
813        ];
814        let idempotency_modes = [
815            ToolIdempotency::NotApplicable,
816            ToolIdempotency::Intrinsic,
817            ToolIdempotency::RequiredKey,
818            ToolIdempotency::Unsupported,
819        ];
820
821        for risk in risks {
822            for idempotency in idempotency_modes {
823                let expected_valid = matches!(
824                    (risk, idempotency),
825                    (ToolRisk::ReadOnly, ToolIdempotency::NotApplicable)
826                        | (
827                            ToolRisk::IdempotentWrite,
828                            ToolIdempotency::Intrinsic | ToolIdempotency::RequiredKey
829                        )
830                        | (ToolRisk::NonIdempotentWrite, ToolIdempotency::Unsupported)
831                );
832                assert_eq!(
833                    ToolExecutionSemantics::new(risk, idempotency, false, false).is_ok(),
834                    expected_valid,
835                    "unexpected result for {risk:?}/{idempotency:?}"
836                );
837            }
838        }
839
840        for (status_query, compensation) in [(true, false), (false, true), (true, true)] {
841            assert_eq!(
842                ToolExecutionSemantics::new(
843                    ToolRisk::ReadOnly,
844                    ToolIdempotency::NotApplicable,
845                    status_query,
846                    compensation,
847                ),
848                Err(ToolExecutionSemanticsError::ReadOnlyRecoverySupport {
849                    status_query,
850                    compensation,
851                })
852            );
853        }
854    }
855
856    #[test]
857    fn execution_semantics_round_trip_and_revalidate_wire_data() {
858        let semantics = ToolExecutionSemantics::new(
859            ToolRisk::IdempotentWrite,
860            ToolIdempotency::RequiredKey,
861            true,
862            true,
863        )
864        .unwrap();
865        assert_eq!(semantics.risk(), ToolRisk::IdempotentWrite);
866        assert_eq!(semantics.idempotency(), ToolIdempotency::RequiredKey);
867        assert!(semantics.requires_idempotency_key());
868        assert!(semantics.supports_status_query());
869        assert!(semantics.supports_compensation());
870
871        let expected = json!({
872            "risk": "idempotent_write",
873            "idempotency": "required_key",
874            "status_query": true,
875            "compensation": true
876        });
877        assert_eq!(to_value(&semantics).unwrap(), expected);
878        assert_eq!(
879            from_value::<ToolExecutionSemantics>(expected).unwrap(),
880            semantics
881        );
882
883        for invalid in [
884            json!({
885                "risk": "idempotent_write",
886                "idempotency": "unsupported",
887                "status_query": false,
888                "compensation": false
889            }),
890            json!({
891                "risk": "read_only",
892                "idempotency": "not_applicable",
893                "status_query": true,
894                "compensation": false
895            }),
896            json!({
897                "risk": "read_only",
898                "idempotency": "not_applicable",
899                "status_query": false,
900                "compensation": false,
901                "safe": true
902            }),
903            Value::Null,
904        ] {
905            assert!(
906                from_value::<ToolExecutionSemantics>(invalid.clone()).is_err(),
907                "accepted semantics {invalid}"
908            );
909        }
910    }
911
912    #[test]
913    fn resource_and_invocation_capabilities_are_explicit_closed_claims() {
914        let none = ToolResourceRequirements::none();
915        assert_eq!(none.network(), ToolResourceAccess::None);
916        assert_eq!(none.filesystem(), ToolResourceAccess::None);
917        assert!(!none.requires_credentials());
918        assert!(!none.executes_dynamic_code());
919        assert!(!none.has_write_access());
920
921        let resources = ToolResourceRequirements::new(
922            ToolResourceAccess::ReadOnly,
923            ToolResourceAccess::ReadWrite,
924            true,
925            true,
926        );
927        assert!(resources.has_write_access());
928        assert!(resources.requires_credentials());
929        assert!(resources.executes_dynamic_code());
930        let encoded = to_value(&resources).unwrap();
931        assert_eq!(
932            from_value::<ToolResourceRequirements>(encoded.clone()).unwrap(),
933            resources
934        );
935        let mut unknown = encoded;
936        unknown["shell"] = json!(true);
937        assert!(from_value::<ToolResourceRequirements>(unknown).is_err());
938
939        let invocation = ToolInvocationCapabilities::new(
940            ToolCancellationSupport::Cooperative,
941            ExecutionCount::new(128),
942        );
943        assert_eq!(
944            invocation.cancellation(),
945            ToolCancellationSupport::Cooperative
946        );
947        assert!(invocation.supports_progress_events());
948        assert_eq!(invocation.max_progress_events(), ExecutionCount::new(128));
949        assert_eq!(
950            from_value::<ToolInvocationCapabilities>(to_value(&invocation).unwrap()).unwrap(),
951            invocation
952        );
953        assert!(
954            from_value::<ToolInvocationCapabilities>(json!({
955                "cancellation": "authoritative",
956                "max_progress_events": "128"
957            }))
958            .is_err()
959        );
960    }
961
962    #[test]
963    fn execution_limits_are_finite_consistent_and_closed() {
964        let limits = default_limits();
965        assert_eq!(limits.timeout(), DurationMillis::new(30_000).unwrap());
966        assert_eq!(limits.max_concurrency(), ExecutionCount::new(16));
967        assert_eq!(limits.max_input_bytes(), ByteCount::new(64 * 1024));
968        assert_eq!(limits.max_inline_result_bytes(), ByteCount::new(256 * 1024));
969        assert_eq!(limits.max_artifacts(), ExecutionCount::new(4));
970        assert_eq!(
971            limits.max_total_artifact_bytes(),
972            ByteCount::new(25 * 1024 * 1024)
973        );
974
975        let encoded = to_value(&limits).unwrap();
976        assert_eq!(encoded["timeout"], "30000");
977        assert_eq!(encoded["max_concurrency"], "16");
978        assert_eq!(encoded["max_input_bytes"], "65536");
979        assert_eq!(encoded["max_inline_result_bytes"], "262144");
980        assert_eq!(encoded["max_artifacts"], "4");
981        assert_eq!(encoded["max_total_artifact_bytes"], "26214400");
982        assert_eq!(
983            from_value::<ToolExecutionLimits>(encoded.clone()).unwrap(),
984            limits
985        );
986
987        assert_eq!(
988            ToolExecutionLimits::new(
989                DurationMillis::ZERO,
990                ExecutionCount::new(1),
991                ByteCount::new(1),
992                ByteCount::new(1),
993                ExecutionCount::ZERO,
994                ByteCount::ZERO,
995            ),
996            Err(ToolExecutionLimitsError::ZeroTimeout)
997        );
998        assert_eq!(
999            ToolExecutionLimits::new(
1000                DurationMillis::new(1).unwrap(),
1001                ExecutionCount::ZERO,
1002                ByteCount::new(1),
1003                ByteCount::new(1),
1004                ExecutionCount::ZERO,
1005                ByteCount::ZERO,
1006            ),
1007            Err(ToolExecutionLimitsError::ZeroConcurrency)
1008        );
1009        assert_eq!(
1010            ToolExecutionLimits::new(
1011                DurationMillis::new(1).unwrap(),
1012                ExecutionCount::new(1),
1013                ByteCount::ZERO,
1014                ByteCount::new(1),
1015                ExecutionCount::ZERO,
1016                ByteCount::ZERO,
1017            ),
1018            Err(ToolExecutionLimitsError::ZeroInputBytes)
1019        );
1020        assert_eq!(
1021            ToolExecutionLimits::new(
1022                DurationMillis::new(1).unwrap(),
1023                ExecutionCount::new(1),
1024                ByteCount::new(1),
1025                ByteCount::ZERO,
1026                ExecutionCount::ZERO,
1027                ByteCount::ZERO,
1028            ),
1029            Err(ToolExecutionLimitsError::ZeroInlineResultBytes)
1030        );
1031        for (max_artifacts, max_total_artifact_bytes) in [
1032            (ExecutionCount::new(1), ByteCount::ZERO),
1033            (ExecutionCount::ZERO, ByteCount::new(1)),
1034        ] {
1035            assert_eq!(
1036                ToolExecutionLimits::new(
1037                    DurationMillis::new(1).unwrap(),
1038                    ExecutionCount::new(1),
1039                    ByteCount::new(1),
1040                    ByteCount::new(1),
1041                    max_artifacts,
1042                    max_total_artifact_bytes,
1043                ),
1044                Err(ToolExecutionLimitsError::ArtifactCapacityMismatch {
1045                    max_artifacts,
1046                    max_total_artifact_bytes,
1047                })
1048            );
1049        }
1050
1051        let mut unknown = encoded;
1052        unknown["unlimited"] = json!(true);
1053        assert!(from_value::<ToolExecutionLimits>(unknown).is_err());
1054    }
1055
1056    #[test]
1057    fn descriptors_revalidate_kind_resources_and_redact_discovery_text() {
1058        let secret = "descriptor-secret";
1059        let descriptor = descriptor(secret);
1060        assert_eq!(descriptor.metadata().kind(), CapabilityKind::Tool);
1061        assert_eq!(
1062            descriptor.input_schema().id().as_str(),
1063            "https://schemas.example.com/tools/capture-input/1.0.0"
1064        );
1065        assert_eq!(
1066            descriptor.output_schema().id().as_str(),
1067            "https://schemas.example.com/tools/capture-output/1.0.0"
1068        );
1069        assert!(descriptor.semantics().requires_idempotency_key());
1070        assert!(descriptor.resources().requires_credentials());
1071        assert!(descriptor.invocation().supports_progress_events());
1072        assert_eq!(descriptor.limits(), &default_limits());
1073        assert!(!format!("{descriptor:?}").contains(secret));
1074
1075        let encoded = to_value(&descriptor).unwrap();
1076        assert_eq!(
1077            from_value::<ToolDescriptor>(encoded.clone()).unwrap(),
1078            descriptor
1079        );
1080
1081        assert_eq!(
1082            ToolDescriptor::new(
1083                metadata(CapabilityKind::Agent, secret),
1084                schema("input"),
1085                schema("output"),
1086                read_only_semantics(),
1087                ToolResourceRequirements::none(),
1088                ToolInvocationCapabilities::new(
1089                    ToolCancellationSupport::Unsupported,
1090                    ExecutionCount::ZERO,
1091                ),
1092                default_limits(),
1093            ),
1094            Err(ToolDescriptorError::WrongCapabilityKind {
1095                actual: CapabilityKind::Agent,
1096            })
1097        );
1098
1099        let write_resources = ToolResourceRequirements::new(
1100            ToolResourceAccess::ReadWrite,
1101            ToolResourceAccess::None,
1102            false,
1103            false,
1104        );
1105        assert_eq!(
1106            ToolDescriptor::new(
1107                metadata(CapabilityKind::Tool, secret),
1108                schema("input"),
1109                schema("output"),
1110                read_only_semantics(),
1111                write_resources,
1112                ToolInvocationCapabilities::new(
1113                    ToolCancellationSupport::Unsupported,
1114                    ExecutionCount::ZERO,
1115                ),
1116                default_limits(),
1117            ),
1118            Err(ToolDescriptorError::ReadOnlyResourceWrite {
1119                network: ToolResourceAccess::ReadWrite,
1120                filesystem: ToolResourceAccess::None,
1121            })
1122        );
1123
1124        let mut wrong_kind = encoded.clone();
1125        wrong_kind["metadata"]["kind"] = json!("agent");
1126        assert!(from_value::<ToolDescriptor>(wrong_kind).is_err());
1127        let mut unsafe_resources = encoded.clone();
1128        unsafe_resources["semantics"] = to_value(read_only_semantics()).unwrap();
1129        assert!(from_value::<ToolDescriptor>(unsafe_resources).is_err());
1130        let mut unknown = encoded;
1131        unknown["provider"] = json!("remote");
1132        assert!(from_value::<ToolDescriptor>(unknown).is_err());
1133    }
1134
1135    #[test]
1136    fn tool_contract_schemas_are_closed_and_require_every_semantic_field() {
1137        for schema in [
1138            to_value(schemars::schema_for!(ToolExecutionSemantics)).unwrap(),
1139            to_value(schemars::schema_for!(ToolResourceRequirements)).unwrap(),
1140            to_value(schemars::schema_for!(ToolInvocationCapabilities)).unwrap(),
1141            to_value(schemars::schema_for!(ToolExecutionLimits)).unwrap(),
1142            to_value(schemars::schema_for!(ToolDescriptor)).unwrap(),
1143        ] {
1144            assert_eq!(schema["type"], "object");
1145            assert_eq!(schema["additionalProperties"], false);
1146        }
1147
1148        let descriptor_schema = to_value(schemars::schema_for!(ToolDescriptor)).unwrap();
1149        assert_eq!(
1150            descriptor_schema["required"],
1151            json!([
1152                "metadata",
1153                "input_schema",
1154                "output_schema",
1155                "semantics",
1156                "resources",
1157                "invocation",
1158                "limits"
1159            ])
1160        );
1161    }
1162
1163    proptest! {
1164        #[test]
1165        fn every_positive_limit_tuple_round_trips_without_widening(
1166            timeout in 1_i64..=1_000_000_000_i64,
1167            concurrency in 1_u64..=1_000_000_u64,
1168            input_bytes in 1_u64..=1_000_000_000_u64,
1169            inline_bytes in 1_u64..=1_000_000_000_u64,
1170            artifact_count in 0_u64..=1_000_u64,
1171            artifact_bytes in 1_u64..=1_000_000_000_u64,
1172        ) {
1173            let artifact_bytes = if artifact_count == 0 { 0 } else { artifact_bytes };
1174            let limits = ToolExecutionLimits::new(
1175                DurationMillis::new(timeout).unwrap(),
1176                ExecutionCount::new(concurrency),
1177                ByteCount::new(input_bytes),
1178                ByteCount::new(inline_bytes),
1179                ExecutionCount::new(artifact_count),
1180                ByteCount::new(artifact_bytes),
1181            ).unwrap();
1182            let encoded = serde_json::to_vec(&limits).unwrap();
1183            let decoded = serde_json::from_slice::<ToolExecutionLimits>(&encoded).unwrap();
1184            prop_assert_eq!(decoded, limits);
1185        }
1186    }
1187}