Skip to main content

mcp_twill/
builder.rs

1use std::{
2    collections::{BTreeMap, BTreeSet},
3    future::Future,
4    marker::PhantomData,
5    sync::Arc,
6};
7
8use async_trait::async_trait;
9use serde::de::DeserializeOwned;
10use serde_json::Value;
11
12use crate::{
13    Alternative, ApplicationResultContract, ApplicationResultDialect, ArgSpec, ArgType,
14    ArgumentSchemaDecl, CapabilityDecl, CommandContext, CommandExample, CommandGuidance,
15    CommandHandler, CommandOutput, CommandRegistry, CommandSpec, ConfirmationPresentation,
16    DynamicApplicationDialect, Fallback, FrameworkError, OutputContract, PermissionSpec,
17    ProgressPhaseSpec, ResourceDecl, Result, StdinContract, TypeDecl, WorkspaceDecl,
18    resource::{ReadResource, ResolveResource, Resource, ResourceDialect},
19};
20
21pub mod arg {
22    use super::ArgBuilder;
23    use crate::{ArgType, ArgumentSchemaUse};
24    use serde_json::{Value, json};
25
26    pub fn string(name: impl Into<String>) -> ArgBuilder {
27        ArgBuilder::new(name, ArgType::String)
28    }
29
30    pub fn path(name: impl Into<String>, workspace: impl Into<String>) -> ArgBuilder {
31        ArgBuilder::new(name, ArgType::Path).workspace(workspace)
32    }
33
34    pub fn boolean(name: impl Into<String>) -> ArgBuilder {
35        ArgBuilder::new(name, ArgType::Bool)
36    }
37
38    pub fn number(name: impl Into<String>) -> ArgBuilder {
39        ArgBuilder::new(name, ArgType::Number)
40    }
41
42    pub fn integer(name: impl Into<String>) -> ArgBuilder {
43        ArgBuilder::new(name, ArgType::Integer)
44    }
45
46    pub fn json(name: impl Into<String>) -> ArgBuilder {
47        ArgBuilder::new(name, ArgType::Json)
48    }
49
50    pub fn enumerated(
51        name: impl Into<String>,
52        values: impl IntoIterator<Item = impl AsRef<str>>,
53    ) -> ArgBuilder {
54        let mut builder = ArgBuilder::new(name, ArgType::String);
55        builder.spec.schema = Some(ArgumentSchemaUse::inline(json!({
56            "type": "string",
57            "enum": values
58                .into_iter()
59                .map(|value| Value::String(value.as_ref().to_string()))
60                .collect::<Vec<_>>(),
61        })));
62        builder.generated_schema = true;
63        builder
64    }
65
66    pub fn named_schema(name: impl Into<String>, schema: impl Into<String>) -> ArgBuilder {
67        let mut builder = ArgBuilder::new(name, ArgType::Json);
68        builder.spec.schema = Some(ArgumentSchemaUse::named(schema));
69        builder
70    }
71
72    pub fn inline_schema(name: impl Into<String>, schema: impl Into<Value>) -> ArgBuilder {
73        ArgBuilder::new(name, ArgType::Json).with_inline_schema(schema)
74    }
75
76    /// An argument whose values match a declared named type (see
77    /// `ServerBuilder::declare_type`).
78    pub fn named(name: impl Into<String>, type_name: impl Into<String>) -> ArgBuilder {
79        ArgBuilder::new(name, ArgType::Named(type_name.into()))
80    }
81}
82
83impl CommandRegistry {
84    pub fn build(
85        name: impl Into<String>,
86        description: impl Into<String>,
87        build: impl FnOnce(&mut ServerBuilder),
88    ) -> Result<Self> {
89        let mut builder = ServerBuilder::new(name, description);
90        build(&mut builder);
91        builder.finish()
92    }
93}
94
95pub struct ServerBuilder {
96    name: String,
97    description: String,
98    preamble: Option<String>,
99    workspaces: Vec<WorkspaceDecl>,
100    capabilities: Vec<CapabilityDecl>,
101    types: Vec<TypeDecl>,
102    argument_schemas: Vec<ArgumentSchemaDecl>,
103    resources: Vec<ResourceDecl>,
104    resource_bindings: Vec<Box<dyn FnOnce(CommandRegistry) -> CommandRegistry>>,
105    guidance: Vec<CommandGuidance>,
106    commands: Vec<BuiltCommand>,
107    command_paths: BTreeSet<Vec<String>>,
108    errors: Vec<FrameworkError>,
109}
110
111struct BuiltCommand {
112    spec: CommandSpec,
113    handler: BuiltHandler,
114}
115
116enum BuiltHandler {
117    Legacy {
118        handler: SharedCommandHandler,
119        typed_arguments: bool,
120    },
121    Constrained(crate::ConstrainedHandlerRegistration),
122    Result(crate::results::ResultHandlerRegistration),
123    Dynamic(crate::results::DynamicHandlerRegistration),
124}
125
126impl ServerBuilder {
127    fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
128        Self {
129            name: name.into(),
130            description: description.into(),
131            preamble: None,
132            workspaces: Vec::new(),
133            capabilities: Vec::new(),
134            types: Vec::new(),
135            argument_schemas: Vec::new(),
136            resources: Vec::new(),
137            resource_bindings: Vec::new(),
138            guidance: Vec::new(),
139            commands: Vec::new(),
140            command_paths: BTreeSet::new(),
141            errors: Vec::new(),
142        }
143    }
144
145    /// Declares server-level operating guidance: posture and conventions
146    /// that apply across commands. Projects into server help, the MCP
147    /// `instructions` field, and the `getting_started` prompt. Command
148    /// routing belongs on the commands themselves (`use_when`,
149    /// `alternative`, `fallback`), not here.
150    pub fn preamble(&mut self, text: impl Into<String>) -> &mut Self {
151        if self.preamble.is_some() {
152            self.errors.push(FrameworkError::Build(format!(
153                "server `{}` assigns `preamble` more than once",
154                self.name
155            )));
156            return self;
157        }
158        self.preamble = Some(text.into());
159        self
160    }
161
162    pub fn workspace(&mut self, workspace: WorkspaceDecl) -> &mut Self {
163        self.workspaces.push(workspace);
164        self
165    }
166
167    pub fn capability(&mut self, capability: CapabilityDecl) -> &mut Self {
168        self.capabilities.push(capability);
169        self
170    }
171
172    pub fn declare_type(&mut self, decl: TypeDecl) -> &mut Self {
173        self.types.push(decl);
174        self
175    }
176
177    pub fn argument_schema(&mut self, decl: ArgumentSchemaDecl) -> &mut Self {
178        self.argument_schemas.push(decl);
179        self
180    }
181
182    /// Declares a server-held resource (RFC 0012). Declaring one derives a
183    /// reference argument type (`{name}-ref`) and a capability (`{name}`);
184    /// the lifecycle edges derive from handler signatures, never from the
185    /// declaration.
186    pub fn resource(&mut self, decl: ResourceDecl) -> &mut Self {
187        self.resources.push(decl);
188        self
189    }
190
191    /// Binds the resolver that turns references to `T` into live values.
192    /// Required for any resource a command requires or releases.
193    pub fn resolver<T: Resource>(&mut self, resolver: impl ResolveResource<T>) -> &mut Self {
194        self.resource_bindings
195            .push(Box::new(move |registry| registry.with_resolver(resolver)));
196        self
197    }
198
199    /// Binds a typed resolver whose declared application failures are
200    /// validated against every consuming command's RFC 0014 contract.
201    pub fn resolver_with_errors<T: Resource>(
202        &mut self,
203        resolver: impl crate::ResolveResourceWithErrors<T>,
204    ) -> &mut Self {
205        self.resource_bindings.push(Box::new(move |registry| {
206            registry.with_resolver_with_errors(resolver)
207        }));
208        self
209    }
210
211    /// Binds a reader for `T`. On MCP, a bound reader turns grants into
212    /// `resource_link` content parts and serves `resources/read` for minted
213    /// URIs; without one, the URI in the structured payload is the whole
214    /// story.
215    pub fn reader<T: Resource>(&mut self, reader: impl ReadResource<T>) -> &mut Self {
216        self.resource_bindings
217            .push(Box::new(move |registry| registry.with_reader(reader)));
218        self
219    }
220
221    pub fn guidance(&mut self, guidance: CommandGuidance) -> &mut Self {
222        self.guidance.push(guidance);
223        self
224    }
225
226    pub fn command(
227        &mut self,
228        path: impl IntoCommandPath,
229        build: impl FnOnce(&mut CommandBuilder),
230    ) -> &mut Self {
231        let path = path.into_command_path();
232        if path.is_empty() {
233            self.errors
234                .push(FrameworkError::Build("command path is empty".to_string()));
235            return self;
236        }
237
238        if !self.command_paths.insert(path.clone()) {
239            self.errors.push(FrameworkError::Build(format!(
240                "duplicate command `{}`",
241                path.join(" ")
242            )));
243            return self;
244        }
245
246        let mut command = CommandBuilder::new(path);
247        build(&mut command);
248        let workspace_names = self
249            .workspaces
250            .iter()
251            .map(|workspace| workspace.name.as_str())
252            .collect::<BTreeSet<_>>();
253
254        match command.finish(&workspace_names) {
255            Ok(command) => self.commands.push(command),
256            Err(error) => self.errors.push(error),
257        }
258        self
259    }
260
261    fn finish(mut self) -> Result<CommandRegistry> {
262        if let Some(error) = self.errors.drain(..).next() {
263            return Err(error);
264        }
265
266        self.project_resource_signatures()?;
267
268        let mut registry = CommandRegistry::new(self.name, self.description);
269        if let Some(preamble) = self.preamble.take() {
270            registry = registry.declare_preamble(preamble);
271        }
272        for workspace in self.workspaces.drain(..) {
273            registry = registry.declare_workspace(workspace);
274        }
275        for capability in self.capabilities.drain(..) {
276            registry = registry.declare_capability(capability);
277        }
278        for decl in self.types.drain(..) {
279            registry = registry.declare_type(decl);
280        }
281        for decl in self.argument_schemas.drain(..) {
282            registry = registry.declare_argument_schema(decl);
283        }
284        for decl in &self.resources {
285            registry = registry.declare_resource(decl.clone());
286        }
287        for binding in self.resource_bindings {
288            registry = binding(registry);
289        }
290        for guidance in self.guidance.drain(..) {
291            registry = registry.declare_guidance(guidance);
292        }
293        for command in self.commands {
294            registry = match command.handler {
295                BuiltHandler::Legacy {
296                    handler,
297                    typed_arguments,
298                } => registry.register_legacy_registration(
299                    command.spec,
300                    handler.inner,
301                    typed_arguments,
302                ),
303                BuiltHandler::Constrained(handler) => {
304                    registry.register_constrained_registration(command.spec, handler)
305                }
306                BuiltHandler::Result(handler) => {
307                    registry.register_result_registration(command.spec, handler)
308                }
309                BuiltHandler::Dynamic(handler) => {
310                    registry.register_dynamic_registration(command.spec, handler)
311                }
312            };
313        }
314        registry.validate_types()?;
315        registry.validate_argument_schemas()?;
316        registry.validate_presentations()?;
317        registry.validate_workspaces()?;
318        registry.validate_capabilities()?;
319        registry.validate_examples()?;
320        registry.validate_guidance()?;
321        registry.validate_resources()?;
322        registry.validate_results()?;
323        Ok(registry)
324    }
325
326    /// Projects signature-derived resource facts onto command specs, with
327    /// every declaration in view: a required or released resource surfaces
328    /// as a required carrier argument of the derived reference type, and a
329    /// hand-written capability edge repeating a signature-derived fact
330    /// deduplicates to the derived one.
331    fn project_resource_signatures(&mut self) -> Result<()> {
332        let hand_declared_capabilities = self
333            .capabilities
334            .iter()
335            .map(|capability| capability.name.as_str())
336            .collect::<BTreeSet<_>>();
337        if let Some(resource) = self
338            .resources
339            .iter()
340            .find(|resource| hand_declared_capabilities.contains(resource.name.as_str()))
341        {
342            return Err(FrameworkError::Build(format!(
343                "resource `{}` derives capability `{}`, which is also declared explicitly; the resource owns that name",
344                resource.name, resource.name
345            )));
346        }
347        let decls = self
348            .resources
349            .iter()
350            .map(|decl| (decl.name.clone(), decl.clone()))
351            .collect::<BTreeMap<_, _>>();
352        for command in &mut self.commands {
353            let spec = &mut command.spec;
354            let inject_carriers = matches!(&command.handler, BuiltHandler::Legacy { .. });
355            let mut injected = BTreeSet::new();
356            let resolved = spec
357                .requires_resources
358                .iter()
359                .chain(&spec.optional_resources)
360                .chain(&spec.releases)
361                .cloned()
362                .collect::<Vec<_>>();
363            for resource in resolved {
364                if !injected.insert(resource.clone()) {
365                    continue;
366                }
367                // Undeclared resources are `validate_resources` errors; skip
368                // injection so that check names the real problem.
369                let Some(decl) = decls.get(&resource) else {
370                    continue;
371                };
372                if !inject_carriers {
373                    continue;
374                }
375                let carrier = decl.carrier_name();
376                // A hand-written argument under the carrier name would
377                // shadow the injected one with a different type or
378                // optionality, so the advertised schema would drift from
379                // the signature-derived requirement.
380                if spec.args.iter().any(|arg| arg.name == carrier) {
381                    return Err(FrameworkError::Build(format!(
382                        "command `{}` hand-declares argument `{carrier}`, which is the injected carrier for resource `{}`; remove the argument or rename the carrier with `carrier` on the resource declaration",
383                        spec.name(),
384                        decl.name
385                    )));
386                }
387                spec.args.push(ArgSpec {
388                    name: carrier,
389                    value_type: ArgType::ResourceRef(resource.clone()),
390                    required: spec.requires_resources.contains(&resource)
391                        || spec.releases.contains(&resource),
392                    summary: decl.reference_summary(),
393                    workspace: None,
394                    repeated: false,
395                    schema: decl.reference_schema.clone(),
396                    requires_arguments: Vec::new(),
397                });
398            }
399            let covered_requires = spec
400                .requires_resources
401                .iter()
402                .chain(&spec.releases)
403                .filter(|resource| decls.contains_key(*resource))
404                .cloned()
405                .collect::<BTreeSet<_>>();
406            spec.requires
407                .retain(|capability| !decls.contains_key(capability));
408            spec.requires.extend(covered_requires);
409            let covered_provides = spec
410                .grants
411                .iter()
412                .filter(|resource| decls.contains_key(*resource))
413                .cloned()
414                .collect::<BTreeSet<_>>();
415            spec.provides
416                .retain(|capability| !decls.contains_key(capability));
417            spec.provides.extend(covered_provides);
418        }
419        Ok(())
420    }
421}
422
423pub struct CommandBuilder {
424    path: Vec<String>,
425    summary: Option<String>,
426    description: Option<String>,
427    invocation_message: Option<String>,
428    confirmation: Option<ConfirmationPresentation>,
429    args: Vec<ArgSpec>,
430    permissions: Vec<PermissionSpec>,
431    examples: Vec<CommandExample>,
432    output: Option<OutputContract>,
433    result_contract: Option<ApplicationResultContract>,
434    stdin: Option<StdinContract>,
435    progress: Vec<ProgressPhaseSpec>,
436    idempotent: bool,
437    task_support: crate::TaskSupportSpec,
438    workspaces: Vec<String>,
439    optional_workspaces: Vec<String>,
440    uses_conversation_identity: bool,
441    requires: Vec<String>,
442    provides: Vec<String>,
443    use_when: Option<String>,
444    alternatives: Vec<Alternative>,
445    fallback: Option<Fallback>,
446    requires_resources: Vec<String>,
447    optional_resources: Vec<String>,
448    grants: Vec<String>,
449    releases: Vec<String>,
450    enumerates: Vec<String>,
451    handler: Option<BuiltHandler>,
452    errors: Vec<FrameworkError>,
453}
454
455impl CommandBuilder {
456    fn new(path: Vec<String>) -> Self {
457        Self {
458            path,
459            summary: None,
460            description: None,
461            invocation_message: None,
462            confirmation: None,
463            args: Vec::new(),
464            permissions: Vec::new(),
465            examples: Vec::new(),
466            output: None,
467            result_contract: None,
468            stdin: None,
469            progress: Vec::new(),
470            idempotent: false,
471            task_support: crate::TaskSupportSpec::Optional,
472            workspaces: Vec::new(),
473            optional_workspaces: Vec::new(),
474            uses_conversation_identity: false,
475            requires: Vec::new(),
476            provides: Vec::new(),
477            use_when: None,
478            alternatives: Vec::new(),
479            fallback: None,
480            requires_resources: Vec::new(),
481            optional_resources: Vec::new(),
482            grants: Vec::new(),
483            releases: Vec::new(),
484            enumerates: Vec::new(),
485            handler: None,
486            errors: Vec::new(),
487        }
488    }
489
490    pub fn summary(&mut self, summary: impl Into<String>) -> &mut Self {
491        self.summary = Some(summary.into());
492        self
493    }
494
495    pub fn description(&mut self, description: impl Into<String>) -> &mut Self {
496        self.description = Some(description.into());
497        self
498    }
499
500    pub fn invocation_message(&mut self, message: impl Into<String>) -> &mut Self {
501        if self.invocation_message.is_some() {
502            self.errors.push(FrameworkError::Build(format!(
503                "command `{}` assigns `invocation_message` more than once",
504                self.path.join(" ")
505            )));
506            return self;
507        }
508        self.invocation_message = Some(message.into());
509        self
510    }
511
512    pub fn confirmation(&mut self, presentation: ConfirmationPresentation) -> &mut Self {
513        if self.confirmation.is_some() {
514            self.errors.push(FrameworkError::Build(format!(
515                "command `{}` assigns `confirmation` more than once",
516                self.path.join(" ")
517            )));
518            return self;
519        }
520        self.confirmation = Some(presentation);
521        self
522    }
523
524    pub fn arg(&mut self, arg: ArgBuilder) -> &mut Self {
525        self.args.push(arg.finish());
526        self
527    }
528
529    pub fn read(&mut self, scope: impl Into<String>, description: impl Into<String>) -> &mut Self {
530        self.permissions
531            .push(PermissionSpec::read(scope, description));
532        self
533    }
534
535    pub fn write(&mut self, scope: impl Into<String>, description: impl Into<String>) -> &mut Self {
536        self.permissions
537            .push(PermissionSpec::write(scope, description));
538        self
539    }
540
541    /// Declares that re-issuing this command with identical arguments is
542    /// safe. Projects into the catalog and the invocation plan, where a
543    /// runtime host's retry policy reads it. The framework cannot verify the
544    /// handler actually deduplicates; the declaration is the author's promise.
545    pub fn idempotent(&mut self) -> &mut Self {
546        self.idempotent = true;
547        self
548    }
549
550    pub fn task_support(&mut self, support: crate::TaskSupportSpec) -> &mut Self {
551        self.task_support = support;
552        self
553    }
554
555    /// Declares that this command requires the named workspace resolved,
556    /// without taking a path argument. The resolved root reaches the handler
557    /// through the plan (`CommandContext::workspace_root`); it is never
558    /// caller-supplied. Planning fails when the workspace does not resolve.
559    pub fn uses_workspace(&mut self, name: impl Into<String>) -> &mut Self {
560        self.workspaces.push(name.into());
561        self
562    }
563
564    /// Declares that the handler can consume the named host workspace when
565    /// available. Planning and dispatch remain valid when it is absent.
566    pub fn uses_optional_workspace(&mut self, name: impl Into<String>) -> &mut Self {
567        self.optional_workspaces.push(name.into());
568        self
569    }
570
571    /// Declares optional host-supplied conversation identity for this
572    /// handler. Absence remains valid.
573    pub fn uses_conversation_identity(&mut self) -> &mut Self {
574        self.uses_conversation_identity = true;
575        self
576    }
577
578    /// Declares that this command requires the named capability. The
579    /// capability's carrier argument must be declared on this command as a
580    /// required argument; registration fails otherwise.
581    pub fn requires(&mut self, capability: impl Into<String>) -> &mut Self {
582        self.requires.push(capability.into());
583        self
584    }
585
586    /// Declares that this command establishes the named capability. Steering
587    /// and help derive "establish it with ..." guidance from this declaration.
588    pub fn provides(&mut self, capability: impl Into<String>) -> &mut Self {
589        self.provides.push(capability.into());
590        self
591    }
592
593    /// One sentence: when this command is the right choice. Positive
594    /// polarity; mutually exclusive with `fallback`.
595    pub fn use_when(&mut self, text: impl Into<String>) -> &mut Self {
596        if self.use_when.is_some() {
597            self.errors.push(FrameworkError::Build(format!(
598                "command `{}` assigns `use_when` more than once",
599                self.path.join(" ")
600            )));
601            return self;
602        }
603        self.use_when = Some(text.into());
604        self
605    }
606
607    /// Declares a routing edge to the command serving a neighboring case,
608    /// with the condition that routes there.
609    pub fn alternative(
610        &mut self,
611        command: impl Into<String>,
612        when: impl Into<String>,
613    ) -> &mut Self {
614        self.alternatives.push(Alternative {
615            command: command.into(),
616            when: when.into(),
617        });
618        self
619    }
620
621    /// Marks this command as an escape hatch: the commands to exhaust
622    /// first and the condition that justifies bypassing them. Mutually
623    /// exclusive with `use_when`. Preferences are copied from borrowed or
624    /// owned string-like items into the catalog declaration.
625    pub fn fallback(
626        &mut self,
627        prefer: impl IntoIterator<Item = impl AsRef<str>>,
628        when: impl Into<String>,
629    ) -> &mut Self {
630        if self.fallback.is_some() {
631            self.errors.push(FrameworkError::Build(format!(
632                "command `{}` assigns `fallback` more than once",
633                self.path.join(" ")
634            )));
635            return self;
636        }
637        self.fallback = Some(Fallback {
638            prefer: prefer
639                .into_iter()
640                .map(|preferred| preferred.as_ref().to_string())
641                .collect(),
642            when: when.into(),
643        });
644        self
645    }
646
647    pub fn delete(
648        &mut self,
649        scope: impl Into<String>,
650        description: impl Into<String>,
651    ) -> &mut Self {
652        self.permissions
653            .push(PermissionSpec::delete(scope, description));
654        self
655    }
656
657    pub fn exec(&mut self, scope: impl Into<String>, description: impl Into<String>) -> &mut Self {
658        self.permissions
659            .push(PermissionSpec::exec(scope, description));
660        self
661    }
662
663    pub fn network(
664        &mut self,
665        scope: impl Into<String>,
666        description: impl Into<String>,
667    ) -> &mut Self {
668        self.permissions
669            .push(PermissionSpec::network(scope, description));
670        self
671    }
672
673    pub fn example(&mut self, command: impl Into<String>, summary: impl Into<String>) -> &mut Self {
674        self.examples.push(CommandExample::new(command, summary));
675        self
676    }
677
678    pub fn output(&mut self, output: OutputContract) -> &mut Self {
679        if self.output.is_some() {
680            self.errors.push(FrameworkError::Build(format!(
681                "command `{}` assigns `output` more than once",
682                self.path.join(" ")
683            )));
684            return self;
685        }
686        let mut output = output;
687        if let Some(application) = output.application.take() {
688            self.install_result_contract(application);
689        }
690        self.output = Some(output);
691        self
692    }
693
694    pub fn result_contract(&mut self, contract: ApplicationResultContract) -> &mut Self {
695        self.install_result_contract(contract);
696        self
697    }
698
699    fn install_result_contract(&mut self, contract: ApplicationResultContract) {
700        if self.result_contract.is_some() {
701            self.errors.push(FrameworkError::Build(format!(
702                "command `{}` assigns `result_contract` more than once",
703                self.path.join(" ")
704            )));
705        } else {
706            self.result_contract = Some(contract);
707        }
708    }
709
710    fn install_handler(&mut self, handler: BuiltHandler) {
711        if self.handler.is_some() {
712            self.errors.push(FrameworkError::Build(format!(
713                "command `{}` installs more than one handler",
714                self.path.join(" ")
715            )));
716        } else {
717            self.handler = Some(handler);
718        }
719    }
720
721    pub fn stdin(&mut self, mime_type: impl Into<String>, summary: impl Into<String>) -> &mut Self {
722        self.stdin = Some(StdinContract {
723            mime_type: mime_type.into(),
724            summary: summary.into(),
725        });
726        self
727    }
728
729    pub fn progress_phase(
730        &mut self,
731        name: impl Into<String>,
732        summary: impl Into<String>,
733    ) -> &mut Self {
734        self.progress.push(ProgressPhaseSpec {
735            name: name.into(),
736            summary: summary.into(),
737        });
738        self
739    }
740
741    pub fn example_with_args(
742        &mut self,
743        command: impl Into<String>,
744        summary: impl Into<String>,
745        args: Value,
746    ) -> &mut Self {
747        let mut example = CommandExample::new(command, summary);
748        match args {
749            Value::Object(map) => {
750                example.args = map.into_iter().collect::<BTreeMap<_, _>>();
751                self.examples.push(example);
752            }
753            _ => self.errors.push(FrameworkError::Build(format!(
754                "example for `{}` must use a JSON object for args",
755                self.path.join(" ")
756            ))),
757        }
758        self
759    }
760
761    /// Installs the handler and reads the command's resource footprint from
762    /// its type (RFC 0012): `Res<T>`/`Release<T>` parameters become require
763    /// and release edges, `Granted<T>`/`Listed<T>` outputs become grant and
764    /// enumerate edges. Plain `Fn(CommandContext)` handlers carry no
765    /// resource facts and register unchanged.
766    pub fn handle<M, H>(&mut self, handler: H) -> &mut Self
767    where
768        H: ResourceDialect<M>,
769    {
770        let optional = H::optional_resources();
771        let resource_uses = H::resource_uses();
772        if let Err(error) = crate::registry::validate_result_resource_modes_for_name(
773            &self.path.join(" "),
774            &resource_uses,
775            &optional,
776        ) {
777            self.errors.push(error);
778        }
779        for resource_use in resource_uses {
780            if resource_use.released {
781                self.releases.push(resource_use.resource.to_string());
782            } else if optional.contains(&resource_use.resource) {
783                self.optional_resources
784                    .push(resource_use.resource.to_string());
785            } else {
786                self.requires_resources
787                    .push(resource_use.resource.to_string());
788            }
789        }
790        self.grants
791            .extend(H::granted().into_iter().map(ToOwned::to_owned));
792        self.enumerates
793            .extend(H::enumerated().into_iter().map(ToOwned::to_owned));
794        self.install_handler(BuiltHandler::Legacy {
795            handler: SharedCommandHandler::from_arc(handler.into_command_handler()),
796            typed_arguments: H::accepts_arguments(),
797        });
798        self
799    }
800
801    pub fn handle_constrained<M, H>(&mut self, handler: H) -> &mut Self
802    where
803        H: crate::ConstrainedCommandDialect<M>,
804    {
805        let registration = handler.into_constrained_registration();
806        self.apply_result_resource_edges(
807            &registration.resource_uses,
808            &registration.optional_resources,
809            &registration.granted,
810            &registration.enumerated,
811        );
812        self.install_handler(BuiltHandler::Constrained(registration));
813        self
814    }
815
816    pub fn handle_result<M, H>(&mut self, handler: H) -> &mut Self
817    where
818        H: ApplicationResultDialect<M>,
819    {
820        let registration = handler.into_result_registration();
821        self.apply_result_resource_edges(
822            &registration.resource_uses,
823            &registration.optional_resources,
824            &registration.granted,
825            &registration.enumerated,
826        );
827        self.install_handler(BuiltHandler::Result(registration));
828        self
829    }
830
831    pub fn handle_dynamic<M, H>(&mut self, handler: H) -> &mut Self
832    where
833        H: DynamicApplicationDialect<M>,
834    {
835        let registration = handler.into_dynamic_registration();
836        self.apply_result_resource_edges(
837            &registration.resource_uses,
838            &registration.optional_resources,
839            &registration.granted,
840            &registration.enumerated,
841        );
842        self.install_handler(BuiltHandler::Dynamic(registration));
843        self
844    }
845
846    fn apply_result_resource_edges(
847        &mut self,
848        uses: &[crate::resource::ResourceUse],
849        optional_resources: &[&'static str],
850        granted: &[&'static str],
851        enumerated: &[&'static str],
852    ) {
853        for resource_use in uses {
854            if resource_use.released {
855                self.releases.push(resource_use.resource.to_string());
856            } else if optional_resources.contains(&resource_use.resource) {
857                self.optional_resources
858                    .push(resource_use.resource.to_string());
859            } else {
860                self.requires_resources
861                    .push(resource_use.resource.to_string());
862            }
863        }
864        self.grants
865            .extend(granted.iter().map(|name| (*name).to_string()));
866        self.enumerates
867            .extend(enumerated.iter().map(|name| (*name).to_string()));
868        for values in [
869            &mut self.requires_resources,
870            &mut self.optional_resources,
871            &mut self.releases,
872            &mut self.grants,
873            &mut self.enumerates,
874        ] {
875            values.sort();
876            values.dedup();
877        }
878    }
879
880    pub fn handle_typed<A, H, Fut>(&mut self, handler: H) -> &mut Self
881    where
882        A: FromCommandArgs + Send + Sync + 'static,
883        H: Fn(CommandContext, A) -> Fut + Send + Sync + 'static,
884        Fut: Future<Output = Result<CommandOutput>> + Send,
885    {
886        self.install_handler(BuiltHandler::Legacy {
887            handler: SharedCommandHandler::new(TypedHandler::<A, H> {
888                handler,
889                _marker: PhantomData,
890            }),
891            typed_arguments: true,
892        });
893        self
894    }
895
896    fn finish(self, workspace_names: &BTreeSet<&str>) -> Result<BuiltCommand> {
897        if let Some(error) = self.errors.into_iter().next() {
898            return Err(error);
899        }
900
901        let command_name = self.path.join(" ");
902        let summary = required_text(self.summary, "summary", &command_name)?;
903        let description = required_text(self.description, "description", &command_name)?;
904        let handler = self.handler.ok_or_else(|| {
905            FrameworkError::Build(format!("command `{command_name}` is missing a handler"))
906        })?;
907
908        let mut arg_names = BTreeSet::new();
909        for arg in &self.args {
910            if arg.summary.trim().is_empty() {
911                return Err(FrameworkError::Build(format!(
912                    "command `{command_name}` argument `{}` is missing summary",
913                    arg.name
914                )));
915            }
916            if !arg_names.insert(arg.name.clone()) {
917                return Err(FrameworkError::Build(format!(
918                    "command `{command_name}` declares duplicate argument `{}`",
919                    arg.name
920                )));
921            }
922            if let Some(workspace) = &arg.workspace
923                && !workspace_names.contains(workspace.as_str())
924            {
925                return Err(FrameworkError::Build(format!(
926                    "command `{command_name}` argument `{}` references unknown workspace `{workspace}`",
927                    arg.name
928                )));
929            }
930        }
931
932        let mut declared_workspaces = BTreeSet::new();
933        for workspace in &self.workspaces {
934            if !workspace_names.contains(workspace.as_str()) {
935                return Err(FrameworkError::Build(format!(
936                    "command `{command_name}` uses workspace `{workspace}`, which is not declared on the server"
937                )));
938            }
939            declared_workspaces.insert(workspace.as_str());
940        }
941        let mut optional_workspaces = BTreeSet::new();
942        for workspace in &self.optional_workspaces {
943            if !workspace_names.contains(workspace.as_str()) {
944                return Err(FrameworkError::Build(format!(
945                    "command `{command_name}` optionally uses workspace `{workspace}`, which is not declared on the server"
946                )));
947            }
948            optional_workspaces.insert(workspace.as_str());
949            if declared_workspaces.contains(workspace.as_str()) {
950                return Err(FrameworkError::Build(format!(
951                    "command `{command_name}` declares workspace `{workspace}` as both required and optional"
952                )));
953            }
954        }
955
956        let mut spec = CommandSpec::new(self.path, summary, description);
957        spec.invocation_message = self.invocation_message;
958        spec.confirmation = self.confirmation;
959        let mut output = self.output.unwrap_or_default();
960        match &handler {
961            BuiltHandler::Legacy { .. }
962            | BuiltHandler::Constrained(_)
963            | BuiltHandler::Result(_)
964                if self.result_contract.is_some() =>
965            {
966                return Err(FrameworkError::Build(format!(
967                    "command `{command_name}` pairs an explicit application result contract with a handler that cannot use it"
968                )));
969            }
970            BuiltHandler::Dynamic(_) if self.result_contract.is_none() => {
971                return Err(FrameworkError::Build(format!(
972                    "dynamic result command `{command_name}` is missing an application result contract"
973                )));
974            }
975            _ => {}
976        }
977        output.application = self.result_contract;
978        if output != OutputContract::default()
979            || matches!(&handler, BuiltHandler::Result(_) | BuiltHandler::Dynamic(_))
980        {
981            spec = spec.with_output(output);
982        }
983        if let Some(stdin) = self.stdin {
984            spec = spec.with_stdin(stdin);
985        }
986        for phase in self.progress {
987            spec = spec.with_progress_phase(phase);
988        }
989        for arg in self.args {
990            spec = spec.with_arg(arg);
991        }
992        for permission in self.permissions {
993            spec = spec.with_permission(permission);
994        }
995        for example in self.examples {
996            spec = spec.with_example(example);
997        }
998        if self.idempotent {
999            spec = spec.idempotent();
1000        }
1001        spec = spec.task_support(self.task_support);
1002        for workspace in self.workspaces {
1003            spec = spec.uses_workspace(workspace);
1004        }
1005        for workspace in self.optional_workspaces {
1006            spec = spec.uses_optional_workspace(workspace);
1007        }
1008        if self.uses_conversation_identity {
1009            spec = spec.uses_conversation_identity();
1010        }
1011        for capability in self.requires {
1012            spec = spec.requires(capability);
1013        }
1014        for capability in self.provides {
1015            spec = spec.provides(capability);
1016        }
1017        if let Some(text) = self.use_when {
1018            spec = spec.use_when(text);
1019        }
1020        for alternative in self.alternatives {
1021            spec = spec.alternative(alternative.command, alternative.when);
1022        }
1023        if let Some(fallback) = self.fallback {
1024            spec = spec.fallback(fallback.prefer, fallback.when);
1025        }
1026        spec.requires_resources = self.requires_resources;
1027        spec.optional_resources = self.optional_resources;
1028        spec.grants = self.grants;
1029        spec.releases = self.releases;
1030        spec.enumerates = self.enumerates;
1031
1032        Ok(BuiltCommand { spec, handler })
1033    }
1034}
1035
1036fn required_text(value: Option<String>, field: &str, command: &str) -> Result<String> {
1037    let value = value.unwrap_or_default();
1038    if value.trim().is_empty() {
1039        Err(FrameworkError::Build(format!(
1040            "command `{command}` is missing {field}"
1041        )))
1042    } else {
1043        Ok(value)
1044    }
1045}
1046
1047pub struct ArgBuilder {
1048    spec: ArgSpec,
1049    generated_schema: bool,
1050}
1051
1052impl ArgBuilder {
1053    fn new(name: impl Into<String>, value_type: ArgType) -> Self {
1054        Self {
1055            spec: ArgSpec {
1056                name: name.into(),
1057                value_type,
1058                required: true,
1059                summary: String::new(),
1060                workspace: None,
1061                repeated: false,
1062                schema: None,
1063                requires_arguments: Vec::new(),
1064            },
1065            generated_schema: false,
1066        }
1067    }
1068
1069    fn workspace(mut self, workspace: impl Into<String>) -> Self {
1070        self.spec.workspace = Some(workspace.into());
1071        self
1072    }
1073
1074    pub fn summary(mut self, summary: impl Into<String>) -> Self {
1075        self.spec.summary = summary.into();
1076        if self.generated_schema
1077            && let Some(crate::ArgumentSchemaUse::Inline { schema }) = &mut self.spec.schema
1078            && let Some(object) = schema.as_object_mut()
1079        {
1080            object.insert(
1081                "description".to_string(),
1082                serde_json::json!(self.spec.summary),
1083            );
1084        }
1085        self
1086    }
1087
1088    pub fn optional(mut self) -> Self {
1089        self.spec.required = false;
1090        self
1091    }
1092
1093    pub fn repeated(mut self) -> Self {
1094        self.spec.repeated = true;
1095        self
1096    }
1097
1098    pub fn with_named_schema(mut self, name: impl Into<String>) -> Self {
1099        self.spec.schema = Some(crate::ArgumentSchemaUse::named(name));
1100        self.generated_schema = false;
1101        self
1102    }
1103
1104    pub fn with_inline_schema(mut self, schema: impl Into<Value>) -> Self {
1105        self.spec.schema = Some(crate::ArgumentSchemaUse::inline(schema));
1106        self.generated_schema = false;
1107        self
1108    }
1109
1110    pub fn requires_argument(mut self, name: impl Into<String>) -> Self {
1111        self.spec.requires_arguments.push(name.into());
1112        self
1113    }
1114
1115    fn finish(self) -> ArgSpec {
1116        self.spec
1117    }
1118}
1119
1120pub trait IntoCommandPath {
1121    fn into_command_path(self) -> Vec<String>;
1122}
1123
1124impl IntoCommandPath for &str {
1125    fn into_command_path(self) -> Vec<String> {
1126        self.split_whitespace().map(ToOwned::to_owned).collect()
1127    }
1128}
1129
1130impl IntoCommandPath for String {
1131    fn into_command_path(self) -> Vec<String> {
1132        self.as_str().into_command_path()
1133    }
1134}
1135
1136impl<const N: usize> IntoCommandPath for [&str; N] {
1137    fn into_command_path(self) -> Vec<String> {
1138        self.into_iter().map(ToOwned::to_owned).collect()
1139    }
1140}
1141
1142pub trait FromCommandArgs: Sized {
1143    fn from_command_args(context: &CommandContext) -> Result<Self>;
1144}
1145
1146impl<T> FromCommandArgs for T
1147where
1148    T: DeserializeOwned,
1149{
1150    fn from_command_args(context: &CommandContext) -> Result<Self> {
1151        let mut values = serde_json::Map::new();
1152        for (name, arg) in &context.plan.bound_args {
1153            values.insert(name.clone(), arg.value.clone());
1154        }
1155        serde_json::from_value(Value::Object(values)).map_err(|error| {
1156            FrameworkError::Build(format!("typed argument extraction failed: {error}"))
1157        })
1158    }
1159}
1160
1161#[derive(Clone)]
1162struct SharedCommandHandler {
1163    inner: Arc<dyn CommandHandler>,
1164}
1165
1166impl SharedCommandHandler {
1167    fn new(handler: impl CommandHandler) -> Self {
1168        Self {
1169            inner: Arc::new(handler),
1170        }
1171    }
1172
1173    fn from_arc(inner: Arc<dyn CommandHandler>) -> Self {
1174        Self { inner }
1175    }
1176}
1177
1178#[async_trait]
1179impl CommandHandler for SharedCommandHandler {
1180    async fn call(&self, context: CommandContext) -> Result<CommandOutput> {
1181        self.inner.call(context).await
1182    }
1183}
1184
1185struct TypedHandler<A, H> {
1186    handler: H,
1187    _marker: PhantomData<A>,
1188}
1189
1190#[async_trait]
1191impl<A, H, Fut> CommandHandler for TypedHandler<A, H>
1192where
1193    A: FromCommandArgs + Send + Sync + 'static,
1194    H: Fn(CommandContext, A) -> Fut + Send + Sync + 'static,
1195    Fut: Future<Output = Result<CommandOutput>> + Send,
1196{
1197    async fn call(&self, context: CommandContext) -> Result<CommandOutput> {
1198        let args = A::from_command_args(&context)?;
1199        (self.handler)(context, args).await
1200    }
1201}