Skip to main content

adk_kernel/drivers/
manifest.rs

1//! Driver manifests and effect classes (spec 3.2 §7.7).
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::fmt;
5use std::path::{Path, PathBuf};
6
7use adk_tool::mcp::McpTaskConfig;
8use adk_tool::mcp::manager::{McpLifecycleMode, McpServerConfig, RestartPolicy};
9use serde::{Deserialize, Serialize};
10
11use super::EffectClass;
12use crate::error::{KernelError, Result};
13use crate::partition::PartitionId;
14
15/// The scheme of an environment value the credential broker resolves (spec 3.2 §7.7).
16pub const SECRET_SCHEME: &str = "secret";
17
18/// How a driver's process is isolated (spec 3.2 §7.7).
19///
20/// `os` runs the server under the platform's enforcer (Seatbelt, bubblewrap) through
21/// `adk_sandbox::sandbox::sandboxed_command`; where no enforcer exists the kernel records
22/// the driver as unsandboxed with the reason, or refuses to start it under
23/// [`KernelConfig::fail_if_sandbox_unavailable`](crate::KernelConfig::fail_if_sandbox_unavailable).
24///
25/// # Example
26///
27/// ```rust
28/// use adk_kernel::drivers::DriverSandbox;
29///
30/// assert_eq!(DriverSandbox::default(), DriverSandbox::Os);
31/// assert_eq!(serde_json::to_value(DriverSandbox::Unsandboxed).unwrap(), "unsandboxed");
32/// ```
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum DriverSandbox {
37    /// The platform's OS sandbox.
38    #[default]
39    Os,
40    /// A container. Drivers have no container launcher yet, so this behaves as an
41    /// unavailable enforcer.
42    Container,
43    /// No sandbox, by the manifest's choice; recorded as such.
44    Unsandboxed,
45}
46
47impl DriverSandbox {
48    /// The name a manifest writes.
49    pub fn as_str(self) -> &'static str {
50        match self {
51            Self::Os => "os",
52            Self::Container => "container",
53            Self::Unsandboxed => "unsandboxed",
54        }
55    }
56}
57
58/// When a driver's process starts (spec 3.2 §7.7, the manifest's `lifecycle`).
59///
60/// # Example
61///
62/// ```rust
63/// use adk_kernel::drivers::DriverLifecycle;
64///
65/// assert_eq!(DriverLifecycle::default(), DriverLifecycle::Lazy);
66/// ```
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69#[non_exhaustive]
70pub enum DriverLifecycle {
71    /// When a partition's agent first lists the driver's tools.
72    #[default]
73    Lazy,
74    /// When the kernel starts, and when the driver is mounted.
75    Eager,
76}
77
78/// What a sandboxed driver may reach besides the system's read-only paths (spec 3.2 §7.7).
79///
80/// The server's program directory, a scratch home and the directory of its brokered
81/// secrets are granted by the kernel; these add to them. Paths that do not exist are left
82/// out, as the enforcers refuse a policy naming a missing path.
83///
84/// # Example
85///
86/// ```rust
87/// use adk_kernel::drivers::DriverAccess;
88///
89/// let access = DriverAccess::default();
90/// assert!(access.allow_network);
91/// assert!(access.allow_write.is_empty());
92/// ```
93#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95#[non_exhaustive]
96pub struct DriverAccess {
97    /// Paths the server may read.
98    #[serde(default, skip_serializing_if = "Vec::is_empty")]
99    pub allow_read: Vec<PathBuf>,
100    /// Paths the server may read and write.
101    #[serde(default, skip_serializing_if = "Vec::is_empty")]
102    pub allow_write: Vec<PathBuf>,
103    /// Whether the server may use the network; integrations usually must.
104    #[serde(default = "default_true")]
105    pub allow_network: bool,
106    /// With `allow_network`, the only hosts the server may reach (`[network] hosts` in the
107    /// manifest), through an egress proxy of its own: `Proxied` network access under the OS
108    /// sandbox. Empty leaves the network open.
109    #[serde(default, skip_serializing_if = "Vec::is_empty")]
110    pub network_hosts: Vec<adk_core::egress::EgressRule>,
111}
112
113impl Default for DriverAccess {
114    fn default() -> Self {
115        Self {
116            allow_read: Vec::new(),
117            allow_write: Vec::new(),
118            allow_network: true,
119            network_hosts: Vec::new(),
120        }
121    }
122}
123
124impl DriverAccess {
125    /// The egress policy the server's connections pass, when `network_hosts` names any.
126    pub fn egress_policy(&self) -> Option<adk_core::egress::EgressPolicy> {
127        (self.allow_network && !self.network_hosts.is_empty()).then(|| {
128            self.network_hosts.iter().cloned().fold(
129                adk_core::egress::EgressPolicy::deny_all(),
130                adk_core::egress::EgressPolicy::allow,
131            )
132        })
133    }
134}
135
136fn default_true() -> bool {
137    true
138}
139
140/// An MCP server run as a supervised child process, as the user approved it (spec 3.2
141/// §7.7).
142///
143/// Written as TOML in the user's drivers directory, or in a workspace's `.adk/drivers/`,
144/// where it may only restrict ([`restrict_with`](Self::restrict_with)):
145///
146/// ```toml
147/// id          = "email"
148/// command     = "mcp-email"
149/// args        = ["--imap"]
150/// env         = { EMAIL_TOKEN = "secret://email/token" }
151/// partitions  = ["work"]
152/// lifecycle   = "lazy"          # lazy | eager
153/// # with allow_network, the only hosts the server reaches, through an egress proxy
154/// # network     = { hosts = ["imap.example.com:993", "smtp.example.com:465"] }
155/// sandbox     = "os"            # os | container | unsandboxed
156/// restart     = { max_attempts = 5, initial_delay_ms = 500, max_delay_ms = 30000, backoff_multiplier = 2.0 }
157///
158/// [tools]                       # unknown tools are `other`
159/// list_inbox   = "read"
160/// send_draft   = "send_external"
161/// ```
162///
163/// Further keys: `protocol` (`initialize`, `auto` or `discover`, the MCP handshake),
164/// `allow_read`, `allow_write`, `allow_network` (the [`DriverAccess`] of a sandboxed
165/// server), `sampling` (whether the server may sample the harness model) and
166/// `data_classes`. An `env` value `secret://...` is resolved through the credential broker
167/// when the driver starts and reaches the process as a file named by `<NAME>_FILE`, never
168/// as a variable's value; a plain value under a name that reads as a credential
169/// (`*_TOKEN`, `*_SECRET`, `*_PASSWORD`, `*_API_KEY`, ...) is refused.
170///
171/// Every driver declares MCP tasks ([`McpTaskConfig::enable_tasks`]), so a server that
172/// needs a long wait can hand back a durable task handle (§13 Q9). Without a `restart`
173/// table a driver restarts under [`RestartPolicy::default`].
174///
175/// # Example
176///
177/// ```rust
178/// use adk_kernel::drivers::{DriverManifest, EffectClass};
179///
180/// let manifest = DriverManifest::from_toml(r#"
181///     id = "email"
182///     command = "mcp-email"
183///     partitions = ["work"]
184///     [tools]
185///     list_inbox = "read"
186///     send_draft = "send_external"
187/// "#).unwrap();
188/// assert_eq!(manifest.class_of("send_draft"), EffectClass::SendExternal);
189/// assert_eq!(manifest.class_of("delete_everything"), EffectClass::Other);
190/// assert!(manifest.server.task_config.enable_tasks);
191/// ```
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193#[serde(rename_all = "camelCase")]
194#[non_exhaustive]
195pub struct DriverManifest {
196    /// The driver's id, also the MCP server id: ASCII letters, digits, `-` and `_`.
197    pub id: String,
198    /// The server process: command, arguments, environment, restart policy, handshake and
199    /// task policy.
200    pub server: McpServerConfig,
201    /// The partitions whose agents may use the driver.
202    pub partitions: Vec<PartitionId>,
203    /// How the process is isolated.
204    pub sandbox: DriverSandbox,
205    /// The effect class of each tool; a tool not listed is [`EffectClass::Other`].
206    #[serde(default)]
207    pub tools: BTreeMap<String, EffectClass>,
208    /// Labels of the data the driver handles, for the person approving it.
209    #[serde(default, skip_serializing_if = "Vec::is_empty")]
210    pub data_classes: Vec<String>,
211    /// Each tool's declaration digest (`ToolOrigin::declaration_digest`), pinned when the
212    /// driver first lists its tools after approval, and again at re-approval.
213    #[serde(default)]
214    pub declaration_digests: BTreeMap<String, String>,
215    /// When the process starts.
216    #[serde(default)]
217    pub lifecycle: DriverLifecycle,
218    /// What a sandboxed process may reach.
219    #[serde(default)]
220    pub access: DriverAccess,
221    /// Whether the server may sample the harness model.
222    #[serde(default)]
223    pub sampling: bool,
224}
225
226/// The TOML form of a manifest.
227#[derive(Debug, Deserialize)]
228#[serde(deny_unknown_fields)]
229struct ManifestFile {
230    id: String,
231    command: String,
232    #[serde(default)]
233    args: Vec<String>,
234    #[serde(default)]
235    env: HashMap<String, String>,
236    #[serde(default)]
237    partitions: Option<Vec<String>>,
238    #[serde(default)]
239    lifecycle: DriverLifecycle,
240    #[serde(default)]
241    protocol: McpLifecycleMode,
242    #[serde(default)]
243    sandbox: DriverSandbox,
244    #[serde(default)]
245    allow_read: Vec<PathBuf>,
246    #[serde(default)]
247    allow_write: Vec<PathBuf>,
248    #[serde(default = "default_true")]
249    allow_network: bool,
250    #[serde(default)]
251    network: Option<NetworkFile>,
252    #[serde(default)]
253    restart: Option<RestartFile>,
254    #[serde(default)]
255    sampling: bool,
256    #[serde(default)]
257    data_classes: Vec<String>,
258    #[serde(default)]
259    tools: BTreeMap<String, String>,
260}
261
262/// The manifest's `network` table.
263#[derive(Debug, Deserialize)]
264#[serde(deny_unknown_fields)]
265struct NetworkFile {
266    #[serde(default)]
267    hosts: Vec<adk_core::egress::EgressRule>,
268}
269
270/// The manifest's `restart` table, in the manifest's own key names.
271#[derive(Debug, Deserialize)]
272#[serde(deny_unknown_fields)]
273struct RestartFile {
274    #[serde(default)]
275    max_attempts: Option<u32>,
276    #[serde(default)]
277    initial_delay_ms: Option<u64>,
278    #[serde(default)]
279    max_delay_ms: Option<u64>,
280    #[serde(default)]
281    backoff_multiplier: Option<f64>,
282}
283
284/// Name suffixes that mark an environment variable as a credential.
285const CREDENTIAL_NAMES: &[&str] = &[
286    "TOKEN",
287    "SECRET",
288    "PASSWORD",
289    "PASSWD",
290    "API_KEY",
291    "APIKEY",
292    "ACCESS_KEY",
293    "PRIVATE_KEY",
294    "CREDENTIAL",
295    "CREDENTIALS",
296];
297
298/// Whether `name` reads as the name of a credential.
299fn names_a_credential(name: &str) -> bool {
300    let upper = name.to_ascii_uppercase();
301    CREDENTIAL_NAMES.iter().any(|suffix| {
302        upper == *suffix || upper.strip_suffix(suffix).is_some_and(|rest| rest.ends_with('_'))
303    })
304}
305
306fn invalid(id: &str, reason: impl fmt::Display) -> KernelError {
307    KernelError::Config { reason: format!("driver manifest `{id}`: {reason}") }
308}
309
310impl DriverManifest {
311    /// A manifest for server `server` under `id`, in the default partition, sandboxed,
312    /// with every tool `other` until [`with_tool`](Self::with_tool) classes it.
313    ///
314    /// Tasks are enabled on the server's task configuration, and a server without a restart
315    /// policy gets [`RestartPolicy::default`].
316    ///
317    /// # Errors
318    ///
319    /// Returns [`KernelError::Config`] when `id` or the server's command is not valid, or
320    /// an environment value is a plain credential or a malformed `secret://` reference.
321    pub fn new(id: impl Into<String>, mut server: McpServerConfig) -> Result<Self> {
322        server.task_config.enable_tasks = true;
323        // A supervised driver restarts with backoff unless its manifest says otherwise.
324        server.restart_policy.get_or_insert_with(RestartPolicy::default);
325        let manifest = Self {
326            id: id.into(),
327            server,
328            partitions: vec![PartitionId::default()],
329            sandbox: DriverSandbox::default(),
330            tools: BTreeMap::new(),
331            data_classes: Vec::new(),
332            declaration_digests: BTreeMap::new(),
333            lifecycle: DriverLifecycle::default(),
334            access: DriverAccess::default(),
335            sampling: false,
336        };
337        manifest.validate()?;
338        Ok(manifest)
339    }
340
341    /// Parses a manifest from its TOML form.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`KernelError::Config`] when the text is not a manifest, names an unknown
346    /// key or effect class, or fails [`new`](Self::new)'s checks.
347    pub fn from_toml(text: &str) -> Result<Self> {
348        let file: ManifestFile = toml::from_str(text).map_err(|error| KernelError::Config {
349            reason: format!("not a driver manifest: {error}"),
350        })?;
351        let mut restart = None;
352        if let Some(table) = file.restart {
353            let defaults = RestartPolicy::default();
354            restart = Some(RestartPolicy {
355                initial_delay_ms: table.initial_delay_ms.unwrap_or(defaults.initial_delay_ms),
356                max_delay_ms: table.max_delay_ms.unwrap_or(defaults.max_delay_ms),
357                backoff_multiplier: table.backoff_multiplier.unwrap_or(defaults.backoff_multiplier),
358                max_restart_attempts: table.max_attempts.unwrap_or(defaults.max_restart_attempts),
359            });
360        }
361        let server = McpServerConfig {
362            command: file.command,
363            args: file.args,
364            env: file.env,
365            restart_policy: restart,
366            lifecycle: file.protocol,
367            task_config: McpTaskConfig::enabled(),
368            ..McpServerConfig::default()
369        };
370        let mut tools = BTreeMap::new();
371        for (tool, class) in file.tools {
372            let class = class
373                .parse::<EffectClass>()
374                .map_err(|error| invalid(&file.id, format!("tool `{tool}`: {error}")))?;
375            tools.insert(tool, class);
376        }
377        let mut manifest = Self::new(file.id, server)?;
378        if let Some(partitions) = file.partitions {
379            manifest.partitions = partitions.into_iter().map(PartitionId::new).collect();
380        }
381        manifest.sandbox = file.sandbox;
382        manifest.tools = tools;
383        manifest.data_classes = file.data_classes;
384        manifest.lifecycle = file.lifecycle;
385        manifest.access = DriverAccess {
386            allow_read: file.allow_read,
387            allow_write: file.allow_write,
388            allow_network: file.allow_network,
389            network_hosts: file.network.map(|network| network.hosts).unwrap_or_default(),
390        };
391        manifest.sampling = file.sampling;
392        manifest.validate()?;
393        Ok(manifest)
394    }
395
396    /// Reads and parses the manifest at `path`.
397    ///
398    /// # Errors
399    ///
400    /// Returns [`KernelError::Io`] when the file cannot be read, and the errors of
401    /// [`from_toml`](Self::from_toml) naming the file.
402    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
403        let path = path.as_ref();
404        let text = std::fs::read_to_string(path)?;
405        Self::from_toml(&text)
406            .map_err(|error| KernelError::Config { reason: format!("{}: {error}", path.display()) })
407    }
408
409    /// Checks the manifest's invariants.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`KernelError::Config`] naming the first violation.
414    pub fn validate(&self) -> Result<()> {
415        if self.id.is_empty()
416            || !self.id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
417        {
418            return Err(invalid(
419                &self.id,
420                "the id must be ASCII letters, digits, `-` or `_`, as MCP server ids are",
421            ));
422        }
423        if self.server.command.trim().is_empty() {
424            return Err(invalid(&self.id, "the command is empty"));
425        }
426        if !self.access.network_hosts.is_empty()
427            && (!self.access.allow_network || self.sandbox != DriverSandbox::Os)
428        {
429            return Err(invalid(
430                &self.id,
431                "network hosts are enforced only by the OS sandbox's egress proxy: set \
432                 sandbox = \"os\" and leave allow_network on, or drop the hosts",
433            ));
434        }
435        if self.partitions.is_empty() {
436            return Err(invalid(&self.id, "it serves no partition; list at least one"));
437        }
438        for (name, value) in &self.server.env {
439            match secret_reference(value) {
440                Some(Err(reason)) => {
441                    return Err(invalid(&self.id, format!("env `{name}`: {reason}")));
442                }
443                Some(Ok(_)) => {}
444                None if names_a_credential(name) && !value.is_empty() => {
445                    return Err(invalid(
446                        &self.id,
447                        format!(
448                            "env `{name}` holds a plain value under a credential's name; write \
449                             `secret://<path>` and bind the secret in the credential broker"
450                        ),
451                    ));
452                }
453                None => {}
454            }
455        }
456        Ok(())
457    }
458
459    /// The effect class of `tool`: the manifest's, or [`EffectClass::Other`].
460    pub fn class_of(&self, tool: &str) -> EffectClass {
461        self.tools.get(tool).copied().unwrap_or(EffectClass::Other)
462    }
463
464    /// Sets the class of `tool`.
465    #[must_use]
466    pub fn with_tool(mut self, tool: impl Into<String>, class: EffectClass) -> Self {
467        self.tools.insert(tool.into(), class);
468        self
469    }
470
471    /// Sets the partitions the driver serves.
472    #[must_use]
473    pub fn with_partitions(mut self, partitions: impl IntoIterator<Item = PartitionId>) -> Self {
474        self.partitions = partitions.into_iter().collect();
475        self
476    }
477
478    /// Sets how the process is isolated.
479    #[must_use]
480    pub fn with_sandbox(mut self, sandbox: DriverSandbox) -> Self {
481        self.sandbox = sandbox;
482        self
483    }
484
485    /// Sets what a sandboxed process may reach.
486    #[must_use]
487    pub fn with_access(mut self, access: DriverAccess) -> Self {
488        self.access = access;
489        self
490    }
491
492    /// Sets when the process starts.
493    #[must_use]
494    pub fn with_lifecycle(mut self, lifecycle: DriverLifecycle) -> Self {
495        self.lifecycle = lifecycle;
496        self
497    }
498
499    /// Sets whether the server may sample the harness model.
500    #[must_use]
501    pub fn with_sampling(mut self, sampling: bool) -> Self {
502        self.sampling = sampling;
503        self
504    }
505
506    /// The command line the person approving the driver sees: the command and its
507    /// arguments, each quoted where the shell would need it.
508    pub fn command_line(&self) -> String {
509        std::iter::once(&self.server.command)
510            .chain(&self.server.args)
511            .map(|word| shell_word(word))
512            .collect::<Vec<_>>()
513            .join(" ")
514    }
515
516    /// The digest of what runs: command, arguments, environment (references, never
517    /// secrets), handshake, sandbox and access (spec 3.2 §9.3 `commandDigest`).
518    pub fn command_digest(&self) -> String {
519        let env: BTreeMap<&String, &String> = self.server.env.iter().collect();
520        adk_core::json_digest(&serde_json::json!({
521            "command": self.server.command,
522            "args": self.server.args,
523            "env": env,
524            "protocol": self.server.lifecycle,
525            "sandbox": self.sandbox,
526            "access": self.access,
527        }))
528    }
529
530    /// The `secret://` references of the environment, by variable name.
531    pub fn secret_references(&self) -> BTreeMap<String, url::Url> {
532        self.server
533            .env
534            .iter()
535            .filter_map(|(name, value)| match secret_reference(value) {
536                Some(Ok(reference)) => Some((name.clone(), reference)),
537                _ => None,
538            })
539            .collect()
540    }
541
542    /// This user-scope manifest restricted by `project`, a workspace's manifest for the
543    /// same driver (spec 3.2 §7.7, 3.1 I3).
544    ///
545    /// A project manifest may narrow the partitions, the sandbox access and sampling, move
546    /// the driver from eager to lazy start, require a sandbox the user left off, and raise
547    /// a tool's class to a stricter one. It may not change what runs: the command, the
548    /// arguments, the environment, the handshake and the restart policy.
549    ///
550    /// # Example
551    ///
552    /// ```rust
553    /// use adk_kernel::drivers::{DriverManifest, EffectClass};
554    ///
555    /// let user = DriverManifest::from_toml(r#"
556    ///     id = "email"
557    ///     command = "mcp-email"
558    ///     partitions = ["work", "home"]
559    ///     [tools]
560    ///     send_draft = "write_local"
561    /// "#).unwrap();
562    /// let project = DriverManifest::from_toml(r#"
563    ///     id = "email"
564    ///     command = "mcp-email"
565    ///     partitions = ["work"]
566    ///     [tools]
567    ///     send_draft = "publish_public"
568    /// "#).unwrap();
569    /// let effective = user.restrict_with(&project).unwrap();
570    /// assert_eq!(effective.partitions.len(), 1);
571    /// assert_eq!(effective.class_of("send_draft"), EffectClass::PublishPublic);
572    ///
573    /// // Loosening is refused.
574    /// assert!(project.restrict_with(&user).is_err());
575    /// ```
576    ///
577    /// # Errors
578    ///
579    /// Returns [`KernelError::Config`] naming what the project manifest tried to loosen
580    /// or change.
581    pub fn restrict_with(&self, project: &DriverManifest) -> Result<DriverManifest> {
582        let refuse = |what: &str| {
583            Err(invalid(
584                &self.id,
585                format!("a project manifest may only restrict a driver; it {what}"),
586            ))
587        };
588        if project.id != self.id {
589            return refuse(&format!("names driver `{}` instead", project.id));
590        }
591        let (mine, theirs) = (&self.server, &project.server);
592        if mine.command != theirs.command
593            || mine.args != theirs.args
594            || mine.env != theirs.env
595            || mine.lifecycle != theirs.lifecycle
596            || mine.restart_policy != theirs.restart_policy
597        {
598            return refuse(
599                "changes what runs: the command, arguments, environment, protocol or restart",
600            );
601        }
602        let allowed: BTreeSet<&PartitionId> = self.partitions.iter().collect();
603        if let Some(extra) = project.partitions.iter().find(|p| !allowed.contains(p)) {
604            return refuse(&format!("adds partition `{extra}`"));
605        }
606        if project.sandbox != self.sandbox && self.sandbox != DriverSandbox::Unsandboxed {
607            return refuse(&format!(
608                "changes the sandbox from `{}` to `{}`",
609                self.sandbox.as_str(),
610                project.sandbox.as_str()
611            ));
612        }
613        if let Some(path) =
614            project.access.allow_read.iter().find(|p| !self.access.allow_read.contains(p))
615        {
616            return refuse(&format!("grants read access to {}", path.display()));
617        }
618        if let Some(path) =
619            project.access.allow_write.iter().find(|p| !self.access.allow_write.contains(p))
620        {
621            return refuse(&format!("grants write access to {}", path.display()));
622        }
623        if project.access.allow_network && !self.access.allow_network {
624            return refuse("grants network access");
625        }
626        // A project allowlist narrows an open network; under the user's allowlist each of its
627        // hosts must be one the user's admits.
628        if project.access.allow_network
629            && let Some(mine) = self.access.egress_policy()
630        {
631            if project.access.network_hosts.is_empty() {
632                return refuse("opens the network the user's manifest limits to its hosts");
633            }
634            if let Some(host) = project.access.network_hosts.iter().find(|host| !mine.covers(host))
635            {
636                return refuse(&format!("grants network access to {host}"));
637            }
638        }
639        if project.sampling && !self.sampling {
640            return refuse("lets the server sample");
641        }
642        if project.lifecycle == DriverLifecycle::Eager && self.lifecycle == DriverLifecycle::Lazy {
643            return refuse("starts the driver eagerly");
644        }
645        let mut tools = self.tools.clone();
646        for (tool, class) in &project.tools {
647            let current = self.class_of(tool);
648            if class.strictness() < current.strictness() {
649                return refuse(&format!("loosens tool `{tool}` from `{current}` to `{class}`"));
650            }
651            tools.insert(tool.clone(), *class);
652        }
653        let mut effective = self.clone();
654        effective.partitions = project.partitions.clone();
655        effective.sandbox = project.sandbox;
656        effective.access = project.access.clone();
657        effective.sampling = project.sampling;
658        effective.lifecycle = project.lifecycle;
659        effective.tools = tools;
660        Ok(effective)
661    }
662}
663
664/// `Some(Ok(url))` for a well-formed `secret://` value, `Some(Err(reason))` for a
665/// malformed one, `None` for a plain value.
666fn secret_reference(value: &str) -> Option<std::result::Result<url::Url, String>> {
667    let rest = value.strip_prefix(SECRET_SCHEME)?.strip_prefix("://")?;
668    Some(match url::Url::parse(value) {
669        Ok(url) if !rest.is_empty() && url.host_str().is_some_and(|host| !host.is_empty()) => {
670            Ok(url)
671        }
672        Ok(_) => Err(format!("`{value}` names no secret; write secret://<scope>/<name>")),
673        Err(error) => Err(format!("`{value}` is not a secret reference: {error}")),
674    })
675}
676
677/// `word` as the shell would need it written.
678fn shell_word(word: &str) -> String {
679    let plain = !word.is_empty()
680        && word.chars().all(|c| c.is_ascii_alphanumeric() || "-_./=:,+@%".contains(c));
681    if plain { word.to_string() } else { format!("'{}'", word.replace('\'', "'\\''")) }
682}
683
684/// Reads every `*.toml` manifest in `dir`, in file-name order; an absent directory has none.
685///
686/// # Errors
687///
688/// Returns the first manifest's error, naming its file, or [`KernelError::Config`] when
689/// two files declare the same driver id.
690pub fn load_dir(dir: impl AsRef<Path>) -> Result<Vec<DriverManifest>> {
691    let dir = dir.as_ref();
692    let entries = match std::fs::read_dir(dir) {
693        Ok(entries) => entries,
694        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
695        Err(error) => return Err(error.into()),
696    };
697    let mut paths: Vec<PathBuf> = entries
698        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
699        .filter(|path| path.extension().is_some_and(|ext| ext == "toml") && path.is_file())
700        .collect();
701    paths.sort();
702    let mut manifests: Vec<DriverManifest> = Vec::with_capacity(paths.len());
703    for path in paths {
704        let manifest = DriverManifest::from_file(&path)?;
705        if manifests.iter().any(|known| known.id == manifest.id) {
706            return Err(KernelError::Config {
707                reason: format!(
708                    "{}: driver `{}` is declared twice in {}",
709                    path.display(),
710                    manifest.id,
711                    dir.display()
712                ),
713            });
714        }
715        manifests.push(manifest);
716    }
717    Ok(manifests)
718}
719
720/// The manifests of the user's drivers directory, each restricted by the workspace's
721/// manifest of the same id (spec 3.2 §7.7: a project scope may only restrict).
722///
723/// # Example
724///
725/// ```rust
726/// let dir = tempfile::tempdir().unwrap();
727/// std::fs::write(dir.path().join("email.toml"), "id = \"email\"\ncommand = \"mcp-email\"\n").unwrap();
728/// let manifests = adk_kernel::drivers::load_manifests(dir.path(), None).unwrap();
729/// assert_eq!(manifests[0].id, "email");
730/// ```
731///
732/// # Errors
733///
734/// Returns the errors of [`load_dir`], and [`KernelError::Config`] when a workspace
735/// manifest names a driver the user did not declare or loosens one.
736pub fn load_manifests(
737    user_dir: impl AsRef<Path>,
738    project_dir: Option<&Path>,
739) -> Result<Vec<DriverManifest>> {
740    let mut manifests = load_dir(user_dir)?;
741    let Some(project_dir) = project_dir else {
742        return Ok(manifests);
743    };
744    for project in load_dir(project_dir)? {
745        let Some(user) = manifests.iter_mut().find(|user| user.id == project.id) else {
746            return Err(KernelError::Config {
747                reason: format!(
748                    "{}: driver `{}` is not in the user's drivers; a workspace may only \
749                     restrict drivers the user declared",
750                    project_dir.display(),
751                    project.id
752                ),
753            });
754        };
755        *user = user.restrict_with(&project)?;
756    }
757    Ok(manifests)
758}
759
760#[cfg(test)]
761mod tests {
762    use adk_core::ToolEffect;
763
764    use super::*;
765
766    #[test]
767    fn network_hosts_limit_the_driver_and_a_project_can_only_narrow_them() {
768        let base = "id = \"mail\"\ncommand = \"mcp-mail\"\nsandbox = \"os\"\n";
769        let user = DriverManifest::from_toml(&format!(
770            "{base}network = {{ hosts = [\"imap.example.com:993\", \"*.example.com:443\"] }}\n"
771        ))
772        .unwrap();
773        let policy = user.access.egress_policy().expect("hosts make an egress policy");
774        assert!(policy.check_url("https://api.example.com/").is_ok());
775        assert!(policy.check_url("https://evil.test/").is_err());
776
777        let narrower = DriverManifest::from_toml(&format!(
778            "{base}network = {{ hosts = [\"api.example.com:443\"] }}\n"
779        ))
780        .unwrap();
781        let effective = user.restrict_with(&narrower).unwrap();
782        assert_eq!(effective.access.network_hosts, narrower.access.network_hosts);
783        for wider in
784            [format!("{base}network = {{ hosts = [\"evil.test:443\"] }}\n"), base.to_string()]
785        {
786            let project = DriverManifest::from_toml(&wider).unwrap();
787            assert!(user.restrict_with(&project).is_err(), "{wider}");
788        }
789        let denied = DriverManifest::from_toml(&format!("{base}allow_network = false\n")).unwrap();
790        assert!(user.restrict_with(&denied).is_ok());
791        assert_eq!(denied.access.egress_policy(), None);
792        for refused in [
793            format!("{base}network = {{ hosts = [\"https://x\"] }}\n"),
794            format!("{base}allow_network = false\nnetwork = {{ hosts = [\"x.example.com\"] }}\n"),
795            "id = \"mail\"\ncommand = \"mcp-mail\"\nsandbox = \"unsandboxed\"\n\
796             network = { hosts = [\"x.example.com\"] }\n"
797                .to_string(),
798        ] {
799            assert!(DriverManifest::from_toml(&refused).is_err(), "{refused}");
800        }
801    }
802
803    const EMAIL: &str = r#"
804        id          = "email"
805        command     = "mcp-email"
806        args        = ["--imap"]
807        env         = { EMAIL_TOKEN = "secret://email/token", LOG_LEVEL = "info" }
808        partitions  = ["work"]
809        lifecycle   = "lazy"
810        sandbox     = "os"
811        restart     = { max_attempts = 5, initial_delay_ms = 500, max_delay_ms = 30000, backoff_multiplier = 2.0 }
812
813        [tools]
814        list_inbox   = "read"
815        get_email    = "read"
816        create_draft = "write_local"
817        send_draft   = "send_external"
818    "#;
819
820    #[test]
821    fn the_spec_manifest_parses() {
822        let manifest = DriverManifest::from_toml(EMAIL).unwrap();
823        assert_eq!(manifest.id, "email");
824        assert_eq!(manifest.server.command, "mcp-email");
825        assert_eq!(manifest.server.args, ["--imap"]);
826        assert_eq!(manifest.partitions, [PartitionId::new("work")]);
827        assert_eq!(manifest.lifecycle, DriverLifecycle::Lazy);
828        assert_eq!(manifest.sandbox, DriverSandbox::Os);
829        assert_eq!(
830            manifest.server.restart_policy,
831            Some(RestartPolicy {
832                initial_delay_ms: 500,
833                max_delay_ms: 30_000,
834                backoff_multiplier: 2.0,
835                max_restart_attempts: 5,
836            })
837        );
838        assert!(manifest.server.task_config.enable_tasks);
839        assert_eq!(manifest.class_of("list_inbox"), EffectClass::Read);
840        assert_eq!(manifest.class_of("create_draft"), EffectClass::WriteLocal);
841        assert_eq!(manifest.class_of("send_draft"), EffectClass::SendExternal);
842        assert_eq!(manifest.class_of("unknown_tool"), EffectClass::Other);
843        assert!(manifest.declaration_digests.is_empty());
844        let secrets = manifest.secret_references();
845        assert_eq!(secrets["EMAIL_TOKEN"].as_str(), "secret://email/token");
846        assert!(!secrets.contains_key("LOG_LEVEL"));
847        assert_eq!(manifest.command_line(), "mcp-email --imap");
848    }
849
850    #[test]
851    fn every_effect_class_parses_and_prints_as_itself() {
852        for class in EffectClass::ALL {
853            assert_eq!(class.as_str().parse::<EffectClass>().unwrap(), class);
854            assert_eq!(serde_json::to_value(class).unwrap(), class.as_str());
855        }
856        assert_eq!("Send-External".parse::<EffectClass>().unwrap(), EffectClass::SendExternal);
857        assert!("teleport".parse::<EffectClass>().is_err());
858        let manifest =
859            DriverManifest::from_toml("id = \"x\"\ncommand = \"x\"\n[tools]\na = \"teleport\"\n");
860        assert!(manifest.unwrap_err().to_string().contains("teleport"));
861    }
862
863    #[test]
864    fn only_publish_public_and_financial_are_never_auto_allowed() {
865        let never: Vec<_> =
866            EffectClass::ALL.into_iter().filter(|class| class.is_never_auto_allowed()).collect();
867        assert_eq!(never, [EffectClass::PublishPublic, EffectClass::Financial]);
868        for class in EffectClass::ALL {
869            let effect = class.tool_effect();
870            assert_eq!(effect == ToolEffect::ReadOnly, class == EffectClass::Read, "{class}");
871        }
872    }
873
874    #[test]
875    fn defaults_are_sandboxed_lazy_and_in_the_default_partition() {
876        let manifest = DriverManifest::from_toml("id = \"fs\"\ncommand = \"mcp-fs\"\n").unwrap();
877        assert_eq!(manifest.partitions, [PartitionId::default()]);
878        assert_eq!(manifest.sandbox, DriverSandbox::Os);
879        assert_eq!(manifest.lifecycle, DriverLifecycle::Lazy);
880        assert!(manifest.access.allow_network);
881        assert!(!manifest.sampling);
882        assert_eq!(manifest.server.lifecycle, McpLifecycleMode::Initialize);
883        assert_eq!(manifest.server.restart_policy, Some(RestartPolicy::default()));
884    }
885
886    #[test]
887    fn bad_manifests_are_refused_with_the_reason() {
888        let cases = [
889            ("id = \"a b\"\ncommand = \"x\"\n", "the id must be"),
890            ("id = \"a\"\ncommand = \" \"\n", "command is empty"),
891            ("id = \"a\"\ncommand = \"x\"\npartitions = []\n", "serves no partition"),
892            ("id = \"a\"\ncommand = \"x\"\nenv = { API_TOKEN = \"abc\" }\n", "credential"),
893            ("id = \"a\"\ncommand = \"x\"\nenv = { GH_PASSWORD = \"abc\" }\n", "credential"),
894            ("id = \"a\"\ncommand = \"x\"\nenv = { TOKEN = \"secret://\" }\n", "secret"),
895            ("id = \"a\"\ncommand = \"x\"\nsurprise = 1\n", "unknown field"),
896            ("id = \"a\"\ncommand = \"x\"\nsandbox = \"vm\"\n", "unknown variant"),
897        ];
898        for (text, expected) in cases {
899            let error = DriverManifest::from_toml(text).unwrap_err().to_string();
900            assert!(error.contains(expected), "{text}: {error}");
901        }
902        // A credential's name with a reference, or a non-credential name with a value, is fine.
903        DriverManifest::from_toml(
904            "id = \"a\"\ncommand = \"x\"\nenv = { API_TOKEN = \"secret://a/t\", TOKENIZER = \"bpe\" }\n",
905        )
906        .unwrap();
907    }
908
909    #[test]
910    fn a_project_manifest_may_only_restrict() {
911        let user = DriverManifest::from_toml(
912            r#"
913            id = "email"
914            command = "mcp-email"
915            partitions = ["work", "home"]
916            sandbox = "unsandboxed"
917            allow_read = ["/srv/mail"]
918            lifecycle = "eager"
919            sampling = true
920            [tools]
921            send_draft = "send_external"
922            list_inbox = "read"
923        "#,
924        )
925        .unwrap();
926        let narrow = |extra: &str| {
927            DriverManifest::from_toml(&format!(
928                "id = \"email\"\ncommand = \"mcp-email\"\npartitions = [\"work\"]\n{extra}"
929            ))
930            .unwrap()
931        };
932
933        let effective = user
934            .restrict_with(&narrow(
935                "sandbox = \"os\"\nallow_network = false\n[tools]\nlist_inbox = \"delete\"\n",
936            ))
937            .unwrap();
938        assert_eq!(effective.partitions, [PartitionId::new("work")]);
939        assert_eq!(effective.sandbox, DriverSandbox::Os);
940        assert!(!effective.access.allow_network);
941        assert!(!effective.sampling);
942        assert_eq!(effective.lifecycle, DriverLifecycle::Lazy);
943        assert_eq!(effective.class_of("list_inbox"), EffectClass::Delete);
944        assert_eq!(effective.class_of("send_draft"), EffectClass::SendExternal);
945
946        let error = user
947            .restrict_with(
948                &DriverManifest::from_toml(
949                    "id = \"email\"\ncommand = \"mcp-email\"\npartitions = [\"work\", \"play\"]\n",
950                )
951                .unwrap(),
952            )
953            .unwrap_err()
954            .to_string();
955        assert!(error.contains("adds partition"), "{error}");
956        for (project, loosens) in [
957            ("[tools]\nsend_draft = \"read\"\n", "loosens tool"),
958            ("allow_write = [\"/\"]\n", "write access"),
959            ("allow_read = [\"/etc\"]\n", "read access"),
960        ] {
961            let error = user.restrict_with(&narrow(project)).unwrap_err().to_string();
962            assert!(error.contains(loosens), "{error}");
963        }
964        let other_command = DriverManifest::from_toml(
965            "id = \"email\"\ncommand = \"evil\"\npartitions = [\"work\"]\n",
966        )
967        .unwrap();
968        assert!(user.restrict_with(&other_command).unwrap_err().to_string().contains("what runs"));
969
970        // A sandboxed user manifest keeps its sandbox.
971        let sandboxed = narrow("");
972        let unsandboxed = narrow("sandbox = \"unsandboxed\"\n");
973        assert!(sandboxed.restrict_with(&unsandboxed).is_err());
974    }
975
976    #[test]
977    fn load_manifests_restricts_by_the_workspace_and_refuses_new_drivers() {
978        let user = tempfile::tempdir().unwrap();
979        let project = tempfile::tempdir().unwrap();
980        std::fs::write(user.path().join("email.toml"), EMAIL).unwrap();
981        std::fs::write(user.path().join("notes.txt"), "not a manifest").unwrap();
982        std::fs::write(
983            project.path().join("email.toml"),
984            EMAIL.replace("send_external", "publish_public"),
985        )
986        .unwrap();
987        let manifests = load_manifests(user.path(), Some(project.path())).unwrap();
988        assert_eq!(manifests.len(), 1);
989        assert_eq!(manifests[0].class_of("send_draft"), EffectClass::PublishPublic);
990
991        std::fs::write(
992            project.path().join("calendar.toml"),
993            "id = \"calendar\"\ncommand = \"c\"\n",
994        )
995        .unwrap();
996        let error = load_manifests(user.path(), Some(project.path())).unwrap_err().to_string();
997        assert!(error.contains("may only restrict drivers the user declared"), "{error}");
998        assert!(load_dir(user.path().join("missing")).unwrap().is_empty());
999    }
1000
1001    #[test]
1002    fn the_command_digest_changes_with_what_runs() {
1003        let manifest = DriverManifest::from_toml(EMAIL).unwrap();
1004        let mut other = manifest.clone();
1005        other.server.args.push("--debug".into());
1006        assert_ne!(manifest.command_digest(), other.command_digest());
1007        let mut reclassed = manifest.clone();
1008        reclassed.tools.clear();
1009        assert_eq!(manifest.command_digest(), reclassed.command_digest());
1010        let quoted = DriverManifest::new(
1011            "q",
1012            McpServerConfig {
1013                command: "/opt/my tools/srv".into(),
1014                args: vec!["it's".into()],
1015                ..Default::default()
1016            },
1017        )
1018        .unwrap();
1019        assert_eq!(quoted.command_line(), "'/opt/my tools/srv' 'it'\\''s'");
1020    }
1021
1022    #[test]
1023    fn a_manifest_round_trips_through_json() {
1024        let mut manifest = DriverManifest::from_toml(EMAIL).unwrap();
1025        manifest.declaration_digests.insert("list_inbox".into(), "sha256:ab".into());
1026        let json = serde_json::to_value(&manifest).unwrap();
1027        assert_eq!(json["sandbox"], "os");
1028        assert_eq!(json["tools"]["send_draft"], "send_external");
1029        let back: DriverManifest = serde_json::from_value(json).unwrap();
1030        assert_eq!(back, manifest);
1031    }
1032}