Skip to main content

agent_works/
tool_provider.rs

1//! Tool supply contract (ToolProvider) — the socket that every tool source plugs into.
2//!
3//! **P0 is the contract layer**: only signatures and the identity-key spec, no implementation.
4//! The four implementations (BuiltinProvider / WasmProvider / ScriptProvider / McpProvider)
5//! land in later phases, all plugging into the same tool table (unified identity / approval / budget / switches).
6//!
7//! # Identity key contract (fixed in one place)
8//!
9//! | Source | Identity key | Example |
10//! |---|---|---|
11//! | Builtin tools (present at compile time) | bare name like `read_file` | `read_file` |
12//! | MCP tools from `/connect` | `mcp.{server}.{tool}` | `mcp.figma.get_file` |
13//! | Global script tools | `script.{name}` | `script.deploy` |
14//! | All tools contributed by plugins (wasm/script/mcp forms unified) | `plugin.{plugin}.{tool}` | `plugin.my-tools.search` |
15//!
16//! - **Identity is determined by "ownership surface", not by "transport"**: an MCP server
17//!   inside a plugin is an implementation detail of the plugin; the tool key remains
18//!   `plugin.{plugin}.{tool}` (the tool segment = the server's tool name).
19//! - The `plugin.` namespace is a single prefix — sub-agent exclusion, approval ledger
20//!   matching, and fail-closed classification all go by the three prefixes
21//!   `mcp.` / `script.` / `plugin.`.
22//! - Name character set `[a-z0-9_-]{1,32}`; `mcp`/`script`/`plugin` are reserved words
23//!   and must not be used as any name segment (hitting a reserved word → reject).
24//!
25//! # Approval priority table (normative MUST; for the implementation see the approval ledger phase)
26//!
27//! | Scenario | Behavior |
28//! |---|---|
29//! | Prefix `mcp.`/`script.`/`plugin.`, tier `ask every time` | **Prompt, even with Shift+Tab = auto** (ledger before mode) |
30//! | Same as above, tier `always allow` | Allow |
31//! | Same as above, tier `deny` | Deny |
32//! | Shift+Tab = deny (global brake) | Deny everything, overrides the ledger |
33//! | Builtin tools | Not in the ledger; go through the existing three-layer approval |
34//!
35//! Three hard rules:
36//! 1. **fail-closed**: the classification fallback MUST return "needs confirmation" for the
37//!    three prefixes, never auto-allow;
38//! 2. **Single memory owner**: `always allow` is only recorded in approvals.json, never
39//!    double-written with the builtin tools' action_key cache;
40//! 3. **Test criterion**: an external tool call at tier `ask every time` still prompts under Shift+Tab=auto.
41//!
42//! # Contract invariants (every implementation MUST satisfy them)
43//!
44//! - `call` MUST reject identity keys outside its own namespace (fail-closed, no "helpful" forwarding);
45//! - the host MUST validate `args` against the descriptor's `parameters` before entering `call` —
46//!   wasm never sees unvalidated parameters;
47//! - keep the trait surface small and narrow: better to give too little than to give the wrong thing.
48//!   To add capability, change the contract first, then implement.
49
50use agent_base::{AgentResult, Content, ToolContext, ToolExposure};
51use async_trait::async_trait;
52use serde_json::Value;
53
54/// Max length of a name segment (`[a-z0-9_-]{1,32}`).
55pub const NAME_SEGMENT_MAX: usize = 32;
56
57/// Reserved words: must not be used as any identity-key name segment (plugin names / script names / builtin names are all rejected).
58pub const RESERVED_NAMESPACES: [&str; 3] = ["mcp", "script", "plugin"];
59
60/// Identity key error. Construction and parsing are always fail-closed: report an error when invalid, never settle for less.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum IdentityError {
63    /// Name segment is empty, too long, or contains characters outside `[a-z0-9_-]`.
64    BadSegment { segment: String },
65    /// Name collides with a reserved word `mcp` / `script` / `plugin`.
66    ReservedName { name: String },
67    /// Free-form key does not match any of the four identity key syntaxes.
68    MalformedKey { key: String },
69}
70
71impl std::fmt::Display for IdentityError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        match self {
74            Self::BadSegment { segment } => write!(
75                f,
76                "identity segment `{segment}` must match [a-z0-9_-]{{1,{NAME_SEGMENT_MAX}}}"
77            ),
78            Self::ReservedName { name } => {
79                write!(
80                    f,
81                    "`{name}` is a reserved identity namespace (mcp/script/plugin)"
82                )
83            }
84            Self::MalformedKey { key } => write!(
85                f,
86                "`{key}` is not a valid tool identity key (builtin name, mcp.{{server}}.{{tool}}, script.{{name}}, or plugin.{{plugin}}.{{tool}})"
87            ),
88        }
89    }
90}
91
92impl std::error::Error for IdentityError {}
93
94/// Identity on a tool table. The four shapes cover all sources; serializes to the keys in the table above.
95#[derive(Debug, Clone, PartialEq, Eq, Hash)]
96pub enum ToolIdentity {
97    /// Builtin tool bare name (`read_file`). Not among the three prefixes, not in the approval ledger.
98    Builtin(String),
99    /// MCP tool from `/connect`: `mcp.{server}.{tool}`.
100    Mcp { server: String, tool: String },
101    /// Global script tool: `script.{name}`.
102    Script { name: String },
103    /// Tool contributed by a plugin (wasm/script/mcp forms unified): `plugin.{plugin}.{tool}`.
104    Plugin { plugin: String, tool: String },
105}
106
107fn validate_segment(segment: &str) -> Result<(), IdentityError> {
108    let ok = !segment.is_empty()
109        && segment.len() <= NAME_SEGMENT_MAX
110        && segment
111            .chars()
112            .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '-'));
113    if ok {
114        Ok(())
115    } else {
116        Err(IdentityError::BadSegment {
117            segment: segment.to_string(),
118        })
119    }
120}
121
122fn validate_name(name: &str) -> Result<(), IdentityError> {
123    validate_segment(name)?;
124    if RESERVED_NAMESPACES.contains(&name) {
125        return Err(IdentityError::ReservedName {
126            name: name.to_string(),
127        });
128    }
129    Ok(())
130}
131
132impl ToolIdentity {
133    /// Builtin tool: bare name, not in the ledger.
134    pub fn builtin(name: &str) -> Result<Self, IdentityError> {
135        validate_name(name)?;
136        Ok(Self::Builtin(name.to_string()))
137    }
138
139    /// MCP tool key from `/connect`. The `tool` segment should be the normalized server
140    /// tool name (see [`normalize_tool_segment`]).
141    pub fn mcp(server: &str, tool: &str) -> Result<Self, IdentityError> {
142        validate_segment(server)?;
143        validate_segment(tool)?;
144        Ok(Self::Mcp {
145            server: server.to_string(),
146            tool: tool.to_string(),
147        })
148    }
149
150    /// Global script tool key.
151    pub fn script(name: &str) -> Result<Self, IdentityError> {
152        validate_name(name)?;
153        Ok(Self::Script {
154            name: name.to_string(),
155        })
156    }
157
158    /// Plugin tool key (wasm/script/mcp forms unified). A `plugin` segment hitting a
159    /// reserved word → reject (the same rule at install time).
160    pub fn plugin(plugin: &str, tool: &str) -> Result<Self, IdentityError> {
161        validate_name(plugin)?;
162        validate_segment(tool)?;
163        Ok(Self::Plugin {
164            plugin: plugin.to_string(),
165            tool: tool.to_string(),
166        })
167    }
168
169    /// Parse a display key. Grammar (the number of dot-separated segments determines the
170    /// ownership surface; segments contain no `.`):
171    /// no dots = builtin; `mcp.s.t`; `script.n`; `plugin.p.t`.
172    pub fn parse(key: &str) -> Result<Self, IdentityError> {
173        match key.split('.').collect::<Vec<_>>().as_slice() {
174            [name] => Self::builtin(name),
175            ["mcp", server, tool] => Self::mcp(server, tool),
176            ["script", name] => Self::script(name),
177            ["plugin", plugin, tool] => Self::plugin(plugin, tool),
178            _ => Err(IdentityError::MalformedKey {
179                key: key.to_string(),
180            }),
181        }
182    }
183
184    /// Canonical display key (shared by LLM tool names / ledger keys / the `/tools` panel).
185    pub fn to_key(&self) -> String {
186        self.to_string()
187    }
188}
189
190impl std::fmt::Display for ToolIdentity {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        match self {
193            Self::Builtin(name) => f.write_str(name),
194            Self::Mcp { server, tool } => write!(f, "mcp.{server}.{tool}"),
195            Self::Script { name } => write!(f, "script.{name}"),
196            Self::Plugin { plugin, tool } => write!(f, "plugin.{plugin}.{tool}"),
197        }
198    }
199}
200
201/// Normalization of an MCP server tool name into the identity key's tool segment:
202/// lowercase, each character outside `[a-z0-9_-]` replaced with `-`, truncated to 32 **characters**.
203///
204/// Numeric suffixes for post-normalization name collisions (`search` / `search-2` …) are a
205/// load-time registration algorithm, not part of this contract. The result of an empty
206/// string / all-invalid input cannot be used as an identity segment; rejected at load time.
207pub fn normalize_tool_segment(raw: &str) -> String {
208    raw.to_lowercase()
209        .chars()
210        .map(|c| match c {
211            'a'..='z' | '0'..='9' | '_' | '-' => c,
212            _ => '-',
213        })
214        .take(NAME_SEGMENT_MAX)
215        .collect()
216}
217
218/// One row on the tool table: identity + model-visible description and parameter envelope.
219#[derive(Debug, Clone)]
220pub struct ToolDescriptor {
221    pub identity: ToolIdentity,
222    /// Model-visible description.
223    pub description: String,
224    /// Parameter JSON Schema (the shape of MCP `inputSchema`). The plugin manifest's
225    /// simplified `parameters` table is converted into this envelope at registration;
226    /// it is what the host uses to validate `args`.
227    pub parameters: Value,
228    /// Hard timeout (milliseconds). `None` = framework default.
229    pub timeout_ms: Option<u64>,
230    /// Tool-table budget tier, default [`ToolExposure::Direct`].
231    pub exposure: ToolExposure,
232}
233
234/// Tool supply abstraction: `list` / `call` / `health`; for the identity key spec see the module docs.
235///
236/// The four implementations plug into the same tool table; future new implementations such
237/// as openapi won't break it — the dividing criterion is: "independently distributable
238/// third-party capability / written by the users themselves / language-neutral" goes to the
239/// plugin supply, "needs in-process state / high-frequency low-latency / security base" stays
240/// builtin (but still implements this trait).
241#[async_trait]
242pub trait ToolProvider: Send + Sync {
243    /// Enumerate the currently exposed tools. Identity keys MUST already be fully qualified ([`ToolIdentity`]).
244    ///
245    /// Dynamic sources (MCP discovery, plugin loading) may differ on each call; callers must
246    /// not cache beyond one health cycle.
247    async fn list(&self) -> AgentResult<Vec<ToolDescriptor>>;
248
249    /// Execute a tool by identity key.
250    ///
251    /// - `identity` MUST be a key within this provider's own namespace (one that `list`
252    ///   returned), otherwise reject (fail-closed, no "helpful" forwarding);
253    /// - `args` MUST already have been validated by the host against [`ToolDescriptor::parameters`];
254    /// - a cancelled/timed-out call only takes down the tool call, not the host.
255    async fn call(
256        &self,
257        identity: &ToolIdentity,
258        args: &Value,
259        ctx: &ToolContext,
260    ) -> AgentResult<Vec<Content>>;
261
262    /// Cheap liveness probe (MCP reconnection, wasm runtime, whether the script is still
263    /// around). On failure, returns an error string explaining what is broken; never panics.
264    async fn health(&self) -> AgentResult<()>;
265}
266
267#[cfg(test)]
268mod tests {
269    use std::sync::Arc;
270
271    use super::*;
272    use serde_json::json;
273
274    #[test]
275    fn identity_display_and_parse_round_trip() {
276        let cases = vec![
277            ToolIdentity::builtin("read_file").unwrap(),
278            ToolIdentity::mcp("figma", "get_file").unwrap(),
279            ToolIdentity::script("deploy").unwrap(),
280            ToolIdentity::plugin("my-tools", "search").unwrap(),
281        ];
282        let keys: Vec<String> = cases.iter().map(|c| c.to_key()).collect();
283        assert_eq!(
284            keys,
285            vec![
286                "read_file",
287                "mcp.figma.get_file",
288                "script.deploy",
289                "plugin.my-tools.search"
290            ]
291        );
292        for case in &cases {
293            assert_eq!(ToolIdentity::parse(&case.to_key()).unwrap(), *case);
294        }
295    }
296
297    #[test]
298    fn identity_rejects_reserved_names() {
299        for ctor in [
300            ToolIdentity::builtin("mcp"),
301            ToolIdentity::script("script"),
302            ToolIdentity::plugin("plugin", "x"),
303        ] {
304            assert!(matches!(
305                ctor,
306                Err(IdentityError::ReservedName { name }) if name == "mcp" || name == "script" || name == "plugin"
307            ));
308        }
309        // server / tool segments do not block reserved words: `mcp.mcp.get` is unambiguous syntax (not required by the design).
310        assert!(ToolIdentity::mcp("mcp", "get").is_ok());
311    }
312
313    #[test]
314    fn identity_rejects_bad_segments() {
315        // Uppercase, empty segments, over 32 chars, containing dots/spaces/non-ASCII — all rejected.
316        assert!(matches!(
317            ToolIdentity::script("Deploy"),
318            Err(IdentityError::BadSegment { .. })
319        ));
320        assert!(matches!(
321            ToolIdentity::plugin("my tools", "x"),
322            Err(IdentityError::BadSegment { .. })
323        ));
324        assert!(matches!(
325            ToolIdentity::builtin(""),
326            Err(IdentityError::BadSegment { .. })
327        ));
328        let long = "a".repeat(NAME_SEGMENT_MAX + 1);
329        assert!(matches!(
330            ToolIdentity::builtin(&long),
331            Err(IdentityError::BadSegment { .. })
332        ));
333        assert!(matches!(
334            ToolIdentity::mcp("notion", "get.file"),
335            Err(IdentityError::BadSegment { .. })
336        ));
337        assert!(matches!(
338            ToolIdentity::builtin("搜索"),
339            Err(IdentityError::BadSegment { .. })
340        ));
341    }
342
343    #[test]
344    fn identity_segment_boundary_is_32() {
345        let ok = "a".repeat(NAME_SEGMENT_MAX);
346        assert!(ToolIdentity::builtin(&ok).is_ok());
347    }
348
349    #[test]
350    fn parse_rejects_malformed_keys() {
351        for key in [
352            "mcp.onlyonesegment",
353            "plugin.onlyonesegment",
354            "mcp.a.b.c",
355            "a.b",
356            "script.a.b",
357            "mcp..tool",
358            "mcp.server.",
359            ".server.tool",
360        ] {
361            assert!(
362                matches!(
363                    ToolIdentity::parse(key),
364                    Err(IdentityError::MalformedKey { .. } | IdentityError::BadSegment { .. })
365                ),
366                "expected malformed/bad segment for {key:?}"
367            );
368        }
369    }
370
371    #[test]
372    fn normalize_tool_segment_follows_three_rules() {
373        // Lowercase, invalid chars → `-`, truncate to 32 characters.
374        assert_eq!(normalize_tool_segment("Get File!"), "get-file-");
375        assert_eq!(normalize_tool_segment("GET"), "get");
376        assert_eq!(normalize_tool_segment("a.b:c"), "a-b-c");
377        // Truncation counts characters; multibyte characters don't panic.
378        let long = "x".repeat(40);
379        assert_eq!(normalize_tool_segment(&long).len(), NAME_SEGMENT_MAX);
380        let cjk = "搜".repeat(40);
381        assert_eq!(normalize_tool_segment(&cjk), "-".repeat(NAME_SEGMENT_MAX));
382    }
383
384    // ── behavioral contract of the trait surface itself ─────────────────────────────────────────────
385
386    struct EchoProvider;
387
388    #[async_trait]
389    impl ToolProvider for EchoProvider {
390        async fn list(&self) -> AgentResult<Vec<ToolDescriptor>> {
391            Ok(vec![ToolDescriptor {
392                identity: ToolIdentity::script("echo").unwrap(),
393                description: "echoes".into(),
394                parameters: json!({"type": "object", "properties": {}}),
395                timeout_ms: Some(1_000),
396                exposure: ToolExposure::Direct,
397            }])
398        }
399
400        async fn call(
401            &self,
402            identity: &ToolIdentity,
403            args: &Value,
404            _ctx: &ToolContext,
405        ) -> AgentResult<Vec<Content>> {
406            // Contract invariant: only accept keys in our own namespace, reject foreign keys.
407            if identity.to_key() != "script.echo" {
408                return Err(agent_base::AgentError::ToolNotFound {
409                    name: identity.to_key(),
410                });
411            }
412            Ok(vec![Content::text(args.to_string())])
413        }
414
415        async fn health(&self) -> AgentResult<()> {
416            Ok(())
417        }
418    }
419
420    #[tokio::test]
421    async fn provider_is_object_safe_and_round_trips() {
422        let provider: Arc<dyn ToolProvider> = Arc::new(EchoProvider);
423        let listed = provider.list().await.unwrap();
424        assert_eq!(listed[0].identity.to_key(), "script.echo");
425
426        let ctx = ToolContext::for_test();
427        let out = provider
428            .call(
429                &ToolIdentity::script("echo").unwrap(),
430                &json!({"x": 1}),
431                &ctx,
432            )
433            .await
434            .unwrap();
435        assert_eq!(out.len(), 1);
436        provider.health().await.unwrap();
437    }
438
439    #[tokio::test]
440    async fn provider_call_rejects_foreign_identity() {
441        let provider: Arc<dyn ToolProvider> = Arc::new(EchoProvider);
442        let ctx = ToolContext::for_test();
443        let err = provider
444            .call(
445                &ToolIdentity::plugin("my-tools", "search").unwrap(),
446                &json!({}),
447                &ctx,
448            )
449            .await
450            .unwrap_err();
451        assert!(matches!(err, agent_base::AgentError::ToolNotFound { .. }));
452    }
453}