strands/plugins/plugin.rs
1//! The [`Plugin`] trait.
2
3use async_trait::async_trait;
4
5use crate::agent::LocalAgent;
6use crate::error::Result;
7use crate::tools::ToolSource;
8
9/// Extends an agent with hooks, tools and setup (`Plugin`).
10///
11/// [`init_agent`](Plugin::init_agent) runs once when the agent initializes and typically
12/// registers hooks; [`get_tools`](Plugin::get_tools) runs after it, so the tools can depend on
13/// what initialization set up. Plugin names are unique per agent.
14///
15/// ```
16/// use strands::agent::LocalAgent;
17/// use strands::hooks::BeforeToolCallEvent;
18/// use strands::plugins::Plugin;
19///
20/// struct NoShell;
21///
22/// #[strands::async_trait]
23/// impl Plugin for NoShell {
24/// fn name(&self) -> &str {
25/// "no-shell"
26/// }
27///
28/// async fn init_agent(&self, agent: &mut LocalAgent) -> strands::Result<()> {
29/// agent.add_hook(|event: &mut BeforeToolCallEvent| {
30/// if event.tool_use().name == "shell" {
31/// event.set_cancel("shell is disabled");
32/// }
33/// });
34/// Ok(())
35/// }
36/// }
37/// ```
38#[async_trait]
39pub trait Plugin: Send + Sync + 'static {
40 /// The unique plugin name, such as `strands:model` for built-ins.
41 fn name(&self) -> &str;
42
43 /// Sets the plugin up on the agent: register hooks, read configuration.
44 ///
45 /// # Errors
46 ///
47 /// Any error fails agent initialization.
48 async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()>;
49
50 /// The tools to register on the agent after [`init_agent`](Plugin::init_agent):
51 /// anything that converts into a [`ToolSource`], such as `vec![MyTool.into()]`. An MCP client
52 /// is rejected; pass it to the agent's tools instead.
53 fn get_tools(&self) -> Vec<ToolSource> {
54 Vec::new()
55 }
56}
57
58/// A shared plugin is a plugin, so `Arc<dyn Plugin>` and `Arc<P>` go wherever plugins do.
59#[async_trait]
60impl<P: Plugin + ?Sized> Plugin for std::sync::Arc<P> {
61 fn name(&self) -> &str {
62 (**self).name()
63 }
64
65 async fn init_agent(&self, agent: &mut LocalAgent) -> Result<()> {
66 (**self).init_agent(agent).await
67 }
68
69 fn get_tools(&self) -> Vec<ToolSource> {
70 (**self).get_tools()
71 }
72}