adk_plugin/enhanced_plugin.rs
1//! Enhanced plugin trait with fine-grained hooks and default no-op implementations.
2//!
3//! The [`EnhancedPlugin`] trait provides a trait-based plugin interface that allows
4//! plugin authors to implement only the hooks they need. All hook methods have default
5//! implementations that pass through inputs unchanged (identity behavior).
6//!
7//! # Overview
8//!
9//! Unlike the closure-based [`PluginConfig`](crate::PluginConfig) approach, `EnhancedPlugin`
10//! uses Rust's trait system for a more ergonomic and type-safe plugin authoring experience.
11//! Plugins can:
12//!
13//! - Intercept and modify tool call arguments before execution
14//! - Inspect and transform tool results after execution
15//! - Modify LLM requests before they are sent
16//! - Transform LLM responses after they are received
17//! - Keep per-invocation state in [`PluginContext`] and agent-wide state in
18//! [`PluginContext::shared`]
19//! - Define execution priority for deterministic ordering
20//!
21//! # Examples
22//!
23//! ## Minimal plugin (no-op)
24//!
25//! ```rust
26//! use adk_core::async_trait;
27//! use adk_plugin::EnhancedPlugin;
28//!
29//! struct MyPlugin;
30//!
31//! #[async_trait]
32//! impl EnhancedPlugin for MyPlugin {
33//! fn name(&self) -> &str {
34//! "my-plugin"
35//! }
36//! }
37//! ```
38//!
39//! ## Plugin with custom priority and before-tool hook
40//!
41//! ```rust,ignore
42//! use std::sync::Arc;
43//! use adk_core::{async_trait, CallbackContext, Result, Tool};
44//! use adk_plugin::{BeforeToolCallResult, EnhancedPlugin, PluginContext};
45//! use serde_json::Value;
46//!
47//! struct ValidationPlugin;
48//!
49//! #[async_trait]
50//! impl EnhancedPlugin for ValidationPlugin {
51//! fn name(&self) -> &str {
52//! "validation"
53//! }
54//!
55//! fn priority(&self) -> i32 {
56//! 10 // Run early in the pipeline
57//! }
58//!
59//! async fn before_tool_call(
60//! &self,
61//! tool: Arc<dyn Tool>,
62//! args: Value,
63//! _ctx: Arc<dyn CallbackContext>,
64//! _plugin_ctx: &PluginContext,
65//! ) -> Result<BeforeToolCallResult> {
66//! // Inject a safety flag into all tool arguments
67//! let mut modified = args;
68//! if let Value::Object(ref mut map) = modified {
69//! map.insert("safe_mode".to_string(), Value::Bool(true));
70//! }
71//! Ok(BeforeToolCallResult::Continue(modified))
72//! }
73//! }
74//! ```
75//!
76//! ## Plugin using the agent-wide context for rate limiting
77//!
78//! ```rust,ignore
79//! use std::sync::Arc;
80//! use adk_core::{async_trait, AdkError, CallbackContext, Result, Tool};
81//! use adk_plugin::{BeforeToolCallResult, EnhancedPlugin, PluginContext};
82//! use serde_json::Value;
83//!
84//! #[derive(Clone)]
85//! struct RateLimitState {
86//! call_count: u32,
87//! }
88//!
89//! struct RateLimitPlugin {
90//! max_calls: u32,
91//! }
92//!
93//! #[async_trait]
94//! impl EnhancedPlugin for RateLimitPlugin {
95//! fn name(&self) -> &str {
96//! "rate-limiter"
97//! }
98//!
99//! fn priority(&self) -> i32 {
100//! 5 // Security plugins run first
101//! }
102//!
103//! async fn before_tool_call(
104//! &self,
105//! _tool: Arc<dyn Tool>,
106//! args: Value,
107//! _ctx: Arc<dyn CallbackContext>,
108//! plugin_ctx: &PluginContext,
109//! ) -> Result<BeforeToolCallResult> {
110//! // The limit spans every invocation of the agent, so it lives in the shared context.
111//! let shared = plugin_ctx.shared();
112//! let mut state = shared.get::<RateLimitState>().await
113//! .unwrap_or(RateLimitState { call_count: 0 });
114//!
115//! state.call_count += 1;
116//! shared.insert(state.clone()).await;
117//!
118//! if state.call_count > self.max_calls {
119//! return Err(AdkError::plugin("rate limit exceeded"));
120//! }
121//!
122//! Ok(BeforeToolCallResult::Continue(args))
123//! }
124//! }
125//! ```
126
127use std::sync::Arc;
128
129use adk_core::{CallbackContext, LlmRequest, LlmResponse, Result, Tool, async_trait};
130use serde_json::Value;
131
132use crate::context::PluginContext;
133use crate::hook_result::{
134 AfterModelCallResult, AfterToolCallResult, BeforeModelCallResult, BeforeToolCallResult,
135};
136
137/// Enhanced plugin trait with fine-grained hooks and default no-op implementations.
138///
139/// Implement only the hooks you need. All methods have default implementations
140/// that pass through inputs unchanged (identity function behavior).
141///
142/// # Priority
143///
144/// Plugins execute in ascending priority order (lower values run first).
145/// The default priority is 100. Recommended ranges:
146///
147/// | Range | Use Case |
148/// |-------|----------|
149/// | 0–25 | Security plugins (auth, validation, rate limiting) |
150/// | 26–50 | Caching plugins |
151/// | 51–75 | Transformation plugins (sanitization, injection) |
152/// | 76–100 | Logging and metrics plugins |
153/// | 100+ | Application-specific plugins |
154///
155/// # Thread Safety
156///
157/// All implementations must be `Send + Sync` to support concurrent async execution.
158/// The [`PluginContext`] provides thread-safe shared state access via
159/// [`tokio::sync::RwLock`].
160#[async_trait]
161pub trait EnhancedPlugin: Send + Sync {
162 /// Unique name identifying this plugin.
163 ///
164 /// Used for logging, debugging, and error messages. Should be a short,
165 /// descriptive identifier (e.g., `"rate-limiter"`, `"cache"`, `"audit-log"`).
166 fn name(&self) -> &str;
167
168 /// Execution priority. Lower values execute first. Default: 100.
169 ///
170 /// When multiple plugins are registered, they execute hooks in ascending
171 /// priority order. Plugins with the same priority execute in registration order.
172 fn priority(&self) -> i32 {
173 100
174 }
175
176 /// Called before a tool is executed.
177 ///
178 /// Receives the tool reference, call arguments, callback context, and the invocation's
179 /// plugin context.
180 ///
181 /// # Returns
182 ///
183 /// - `Ok(BeforeToolCallResult::Continue(args))` — pass (possibly modified) args to the
184 /// next plugin in the chain, and ultimately to the tool execution.
185 /// - `Ok(BeforeToolCallResult::ShortCircuit(result))` — skip tool execution entirely
186 /// and use this synthetic result. No further plugins in the chain are invoked.
187 /// - `Err(e)` — stop the pipeline and propagate the error. The tool is not executed.
188 async fn before_tool_call(
189 &self,
190 _tool: Arc<dyn Tool>,
191 args: Value,
192 _ctx: Arc<dyn CallbackContext>,
193 _plugin_ctx: &PluginContext,
194 ) -> Result<BeforeToolCallResult> {
195 Ok(BeforeToolCallResult::Continue(args))
196 }
197
198 /// Called after a tool executes successfully.
199 ///
200 /// Receives the tool reference, the arguments that were used for execution
201 /// (after any modifications by before-hooks), the result, callback context,
202 /// and the invocation's plugin context.
203 ///
204 /// # Returns
205 ///
206 /// - `Ok(AfterToolCallResult::Continue(result))` — pass (possibly modified) result
207 /// to the next plugin in the chain, and ultimately return to the agent.
208 /// - `Err(e)` — stop the pipeline and propagate the error.
209 async fn after_tool_call(
210 &self,
211 _tool: Arc<dyn Tool>,
212 _args: &Value,
213 result: Value,
214 _ctx: Arc<dyn CallbackContext>,
215 _plugin_ctx: &PluginContext,
216 ) -> Result<AfterToolCallResult> {
217 Ok(AfterToolCallResult::Continue(result))
218 }
219
220 /// Called before a model (LLM) call is made.
221 ///
222 /// Receives the LLM request, callback context, and the invocation's plugin context.
223 ///
224 /// # Returns
225 ///
226 /// - `Ok(BeforeModelCallResult::Continue(request))` — pass (possibly modified) request
227 /// to the next plugin in the chain, and ultimately to the LLM provider.
228 /// - `Ok(BeforeModelCallResult::ShortCircuit(response))` — skip the model call entirely
229 /// and use this synthetic response. No further plugins in the chain are invoked.
230 /// - `Err(e)` — stop the pipeline and propagate the error. The model is not called.
231 async fn before_model_call(
232 &self,
233 request: LlmRequest,
234 _ctx: Arc<dyn CallbackContext>,
235 _plugin_ctx: &PluginContext,
236 ) -> Result<BeforeModelCallResult> {
237 Ok(BeforeModelCallResult::Continue(request))
238 }
239
240 /// Called after a model (LLM) call completes.
241 ///
242 /// Receives the LLM response, callback context, and the invocation's plugin context.
243 ///
244 /// # Returns
245 ///
246 /// - `Ok(AfterModelCallResult::Continue(response))` — pass (possibly modified) response
247 /// to the next plugin in the chain, and ultimately return to the agent.
248 /// - `Err(e)` — stop the pipeline and propagate the error.
249 async fn after_model_call(
250 &self,
251 response: LlmResponse,
252 _ctx: Arc<dyn CallbackContext>,
253 _plugin_ctx: &PluginContext,
254 ) -> Result<AfterModelCallResult> {
255 Ok(AfterModelCallResult::Continue(response))
256 }
257
258 /// Called when the plugin is being shut down.
259 ///
260 /// Override this method to perform cleanup operations such as flushing
261 /// buffers, closing connections, or persisting state.
262 ///
263 /// The default implementation is a no-op.
264 async fn close(&self) {}
265}