feat(plugins): add AI tools and consent-gated data access

This commit is contained in:
t8y2 committed 2026-09-25 01:56:26 +08:00
1 parent 1bc6f70cd8
commit 26a015cd86
71 files changed
+4613 -129

No files matched your search

+269 -17
View File
@@ -6,13 +6,15 @@ use futures::FutureExt;
use serde_json::json;
use tokio::sync::Notify;
use crate::agent_events::{AgentEvent, ToolCall, ToolDefinition, ToolResult};
use crate::agent_events::{AgentEvent, ToolApprovalOutcome, ToolCall, ToolDefinition, ToolResult};
use crate::agent_tools;
use crate::ai::{self, AiCompletionRequest, AiConfig, AiMessage, AiProvider, AiStreamChunk, AiTaskContract};
use crate::ai_cli_agent::CliAgentCommandSpec;
use crate::connection::AppState;
use crate::models::connection::DatabaseType;
use crate::plugin_tools::{self, PluginToolSet, PreparedPluginToolCall};
use crate::token_usage::TokenUsage;
use crate::tool_approval::{self, ToolApprovalWait};
/// Default number of agent loop turns to prevent infinite loops.
/// Users can raise the limit in Settings → AI; it is clamped to
@@ -88,6 +90,12 @@ pub struct AgentLoopContext {
/// Stable per-conversation key forwarded to providers that support prompt
/// caching (OpenAI Responses API). `None` disables the field entirely.
pub prompt_cache_key: Option<String>,
/// Client AI session id. Plugin tool calls that need the user's approval
/// are routed to the client through it; without one they are refused.
pub session_id: Option<String>,
/// Runtime that owns plugin sidecar sessions. The web server runs each
/// agent loop on a runtime of its own, so plugin calls are spawned here.
pub host_runtime: Option<tokio::runtime::Handle>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -281,11 +289,21 @@ async fn run_agent_loop_inner(
.await;
}
let mut sql_permissions = agent_ctx.sql_permissions.clone();
let tools = if is_agent_mode {
let mut tools = if is_agent_mode {
agent_tools::all_tools(agent_ctx.db_type, sql_permissions.clone())
} else {
agent_tools::read_only_tools(agent_ctx.db_type)
};
// Plugin tools join agent runs only; ask mode keeps its database-only
// read tools.
let plugin_tool_set = if is_agent_mode {
plugin_tools::discover_plugin_tools(&agent_ctx.state, agent_ctx.host_runtime.as_ref()).await
} else {
PluginToolSet::default()
};
tools.extend(plugin_tool_set.definitions());
let plugin_system_prompt = plugin_tool_set.prompt_section().map(|section| format!("{system_prompt}\n\n{section}"));
let system_prompt = plugin_system_prompt.as_deref().unwrap_or(system_prompt);
let task_contract = task_contract.cloned();
let mut conversation_messages: Vec<AiMessage> = messages.to_vec();
let mut final_text = String::new();
@@ -542,6 +560,34 @@ async fn run_agent_loop_inner(
});
}
// Plugin tool calls are validated first; a call not declared read-only
// runs only after the user approved it. Nothing has executed yet, so a
// cancellation here stops the run without side effects.
let mut plugin_calls = match gate_plugin_tool_calls(
&plugin_tool_set,
&collected_tool_calls,
agent_ctx,
&on_event,
cancelled,
)
.await
{
Some(plugin_calls) => plugin_calls,
None => {
for tc in &collected_tool_calls {
on_event(AgentEvent::ToolCallEnd {
tool_call_id: tc.id.clone(),
tool_name: tc.name.clone(),
result: json!({ "content": "Cancelled before the tool ran." }),
is_error: true,
});
}
final_text = accumulated_text;
loop_exit = LoopExit::Cancelled;
break;
}
};
// Execute tool calls: parallel for read tools, sequential for execute_query
let state2 = Arc::clone(&agent_ctx.state);
let conn2 = agent_ctx.connection_id.clone();
@@ -552,7 +598,7 @@ async fn run_agent_loop_inner(
// Split by index into parallel and sequential groups using tool metadata
let tool_parallel_map: std::collections::HashMap<&str, bool> =
tools.iter().map(|t| (t.name, t.parallel_ok)).collect();
tools.iter().map(|t| (t.name.as_ref(), t.parallel_ok)).collect();
let (parallel_indices, sequential_indices): (Vec<usize>, Vec<usize>) = (0..collected_tool_calls.len())
.partition(|&i| *tool_parallel_map.get(collected_tool_calls[i].name.as_str()).unwrap_or(&false));
@@ -585,19 +631,26 @@ async fn run_agent_loop_inner(
let mut sequential_results = Vec::with_capacity(sequential_indices.len());
for &i in &sequential_indices {
let tc = make_tc(&collected_tool_calls[i]);
let execution_permissions = sequential_tool_permissions(&tc, db_type, &mut sql_permissions);
sequential_results.push(
agent_tools::execute_tool(
&tc,
&state2,
&conn2,
&db2,
schema2.as_deref(),
&db_type,
execution_permissions,
)
.await,
);
let result = match plugin_calls.remove(&i) {
Some(Ok(prepared)) => {
plugin_tools::execute_plugin_tool(&state2, agent_ctx.host_runtime.as_ref(), &tc, &prepared).await
}
Some(Err(not_executed)) => not_executed,
None => {
let execution_permissions = sequential_tool_permissions(&tc, db_type, &mut sql_permissions);
agent_tools::execute_tool(
&tc,
&state2,
&conn2,
&db2,
schema2.as_deref(),
&db_type,
execution_permissions,
)
.await
}
};
sequential_results.push(result);
}
// Merge results back into original order
@@ -1095,7 +1148,7 @@ fn estimate_tool_schema_tokens(tools: &[ToolDefinition]) -> u32 {
.map(|tool| {
let schema_tokens =
serde_json::to_string(&tool.parameters).map(|schema| estimate_text_tokens(&schema)).unwrap_or_default();
estimate_text_tokens(tool.name) + estimate_text_tokens(tool.description) + schema_tokens + 16
estimate_text_tokens(&tool.name) + estimate_text_tokens(&tool.description) + schema_tokens + 16
})
.sum()
}
@@ -1290,6 +1343,98 @@ fn write_attempt_response(sql: &str, targets_production: bool) -> WriteAttemptRe
}
}
const PLUGIN_TOOL_DECLINED: &str =
"The user declined this tool call, so it did not run. Do not retry it; continue without it.";
const PLUGIN_TOOL_APPROVAL_TIMED_OUT: &str =
"Nobody approved this tool call in time, so it did not run. Do not retry it; tell the user what you intended to run.";
const PLUGIN_TOOL_APPROVAL_UNAVAILABLE: &str =
"This tool may change state and needs the user's approval, which this session cannot ask for. It did not run.";
/// Per-call outcome of the plugin tool gate: run the prepared call, or reply
/// with the ready result explaining why it did not run.
type PluginCallGate = std::collections::HashMap<usize, Result<PreparedPluginToolCall, ToolResult>>;
/// Validates this turn's plugin tool calls and asks the user to approve every
/// call that is not declared read-only, one at a time in call order. Returns
/// `None` when the run was cancelled while an approval was pending.
async fn gate_plugin_tool_calls<F>(
plugin_tool_set: &PluginToolSet,
tool_calls: &[ToolCall],
agent_ctx: &AgentLoopContext,
on_event: &F,
cancelled: &Notify,
) -> Option<PluginCallGate>
where
F: Fn(AgentEvent) + Sync,
{
let mut gate = PluginCallGate::new();
if plugin_tool_set.is_empty() {
return Some(gate);
}
for (index, tool_call) in tool_calls.iter().enumerate() {
let Some(prepared) = plugin_tool_set.prepare_call(tool_call) else {
continue;
};
let outcome = match prepared {
Err(error) => Err(plugin_tools::not_executed_result(tool_call, error)),
Ok(prepared) if prepared.read_only => Ok(prepared),
Ok(prepared) => match agent_ctx.session_id.as_deref() {
None => Err(plugin_tools::not_executed_result(tool_call, PLUGIN_TOOL_APPROVAL_UNAVAILABLE)),
Some(session_id) => match request_tool_approval(session_id, tool_call, &prepared, on_event, cancelled)
.await
{
ToolApprovalWait::Approved => Ok(prepared),
ToolApprovalWait::Denied => Err(plugin_tools::not_executed_result(tool_call, PLUGIN_TOOL_DECLINED)),
ToolApprovalWait::TimedOut => {
Err(plugin_tools::not_executed_result(tool_call, PLUGIN_TOOL_APPROVAL_TIMED_OUT))
}
ToolApprovalWait::Cancelled => return None,
},
},
};
gate.insert(index, outcome);
}
Some(gate)
}
async fn request_tool_approval<F>(
session_id: &str,
tool_call: &ToolCall,
prepared: &PreparedPluginToolCall,
on_event: &F,
cancelled: &Notify,
) -> ToolApprovalWait
where
F: Fn(AgentEvent) + Sync,
{
let approval = tool_approval::register_tool_approval(session_id);
let approval_id = approval.id().to_string();
on_event(AgentEvent::ToolApprovalRequired {
approval_id: approval_id.clone(),
tool_call_id: tool_call.id.clone(),
tool_name: tool_call.name.clone(),
plugin_id: prepared.plugin_id.clone(),
plugin_name: prepared.plugin_name.clone(),
plugin_tool: prepared.plugin_tool.clone(),
connection_id: prepared.connection_id.clone(),
connection_name: prepared.connection_name.clone(),
args: prepared.arguments.clone(),
timeout_secs: tool_approval::TOOL_APPROVAL_TIMEOUT.as_secs(),
});
let wait = approval.wait(tool_approval::TOOL_APPROVAL_TIMEOUT, cancelled).await;
on_event(AgentEvent::ToolApprovalResolved {
approval_id,
tool_call_id: tool_call.id.clone(),
outcome: match wait {
ToolApprovalWait::Approved => ToolApprovalOutcome::Approved,
ToolApprovalWait::Denied => ToolApprovalOutcome::Denied,
ToolApprovalWait::TimedOut => ToolApprovalOutcome::TimedOut,
ToolApprovalWait::Cancelled => ToolApprovalOutcome::Cancelled,
},
});
wait
}
fn sequential_tool_permissions(
tool_call: &ToolCall,
db_type: DatabaseType,
@@ -1517,6 +1662,113 @@ fn summarize_message_content(content: &str) -> String {
mod tests {
use super::*;
fn plugin_tool_set() -> PluginToolSet {
PluginToolSet::from_listings_for_tests(
&[("io.dbx.kafka", "Kafka Studio")],
vec![(
plugin_tools::OpenPluginConnection {
connection_id: "k1".to_string(),
connection_name: "prod-kafka".to_string(),
plugin_id: "io.dbx.kafka".to_string(),
},
json!({ "tools": [
{ "name": "kafka_topics_list", "annotations": { "readOnlyHint": true }, "inputSchema": { "type": "object", "properties": {} } },
{ "name": "kafka_topics_delete", "inputSchema": { "type": "object", "properties": { "topics": { "type": "array", "items": { "type": "string" } } } } }
] }),
)],
)
}
fn plugin_tool_call(id: &str, name: &str) -> ToolCall {
ToolCall {
id: id.to_string(),
name: name.to_string(),
arguments: json!({ "topics": ["orders"] }),
provider_payload: None,
}
}
async fn gate_context(session_id: Option<&str>) -> (tempfile::TempDir, AgentLoopContext) {
let temp_dir = tempfile::tempdir().unwrap();
let storage = crate::storage::Storage::open(&temp_dir.path().join("storage.db")).await.unwrap();
let ctx = AgentLoopContext {
state: Arc::new(AppState::new(storage)),
connection_id: "db".to_string(),
database: String::new(),
selected_databases: Vec::new(),
schema: None,
db_type: DatabaseType::Postgres,
cli_mcp_server_command: None,
sql_permissions: agent_tools::AgentSqlPermissions::default(),
max_agent_turns: DEFAULT_MAX_AGENT_TURNS,
prompt_cache_key: None,
session_id: session_id.map(str::to_string),
host_runtime: None,
};
(temp_dir, ctx)
}
#[tokio::test]
async fn plugin_tool_gate_runs_read_only_calls_and_asks_before_the_rest() {
let (_dir, ctx) = gate_context(Some("session-gate")).await;
let set = plugin_tool_set();
let calls = vec![
plugin_tool_call("c1", "kafka__kafka_topics_list"),
plugin_tool_call("c2", "kafka__kafka_topics_delete"),
plugin_tool_call("c3", "list_tables"),
];
let events = Arc::new(Mutex::new(Vec::new()));
let recorded = events.clone();
// The "user" approves as soon as the question appears.
let on_event = move |event: AgentEvent| {
if let AgentEvent::ToolApprovalRequired { approval_id, .. } = &event {
assert!(tool_approval::resolve_tool_approval("session-gate", approval_id, true));
}
recorded.lock().unwrap().push(event);
};
let gate = gate_plugin_tool_calls(&set, &calls, &ctx, &on_event, &Notify::new()).await.unwrap();
assert!(gate[&0].as_ref().is_ok_and(|prepared| prepared.read_only));
let approved = gate[&1].as_ref().unwrap();
assert_eq!(approved.connection_id, "k1");
assert_eq!(approved.arguments, json!({ "topics": ["orders"] }));
assert!(!gate.contains_key(&2), "database tools bypass the plugin gate");
let events = events.lock().unwrap();
assert_eq!(events.len(), 2, "only the non-read-only call asks: {events:?}");
assert!(
matches!(&events[0], AgentEvent::ToolApprovalRequired { tool_call_id, plugin_tool, .. } if tool_call_id == "c2" && plugin_tool == "kafka_topics_delete")
);
assert!(matches!(&events[1], AgentEvent::ToolApprovalResolved { outcome: ToolApprovalOutcome::Approved, .. }));
}
#[tokio::test]
async fn plugin_tool_gate_refuses_declined_and_unaskable_calls_and_stops_on_cancel() {
let set = plugin_tool_set();
let calls = vec![plugin_tool_call("c1", "kafka__kafka_topics_delete")];
let (_dir, ctx) = gate_context(Some("session-deny")).await;
let deny = |event: AgentEvent| {
if let AgentEvent::ToolApprovalRequired { approval_id, .. } = &event {
tool_approval::resolve_tool_approval("session-deny", approval_id, false);
}
};
let gate = gate_plugin_tool_calls(&set, &calls, &ctx, &deny, &Notify::new()).await.unwrap();
let declined = gate[&0].as_ref().unwrap_err();
assert!(declined.is_error);
assert_eq!(declined.content, PLUGIN_TOOL_DECLINED);
// No client session: nobody can be asked, so the call never runs.
let (_dir, headless) = gate_context(None).await;
let gate = gate_plugin_tool_calls(&set, &calls, &headless, &|_event| {}, &Notify::new()).await.unwrap();
assert_eq!(gate[&0].as_ref().unwrap_err().content, PLUGIN_TOOL_APPROVAL_UNAVAILABLE);
let (_dir, ctx) = gate_context(Some("session-cancel")).await;
let cancelled = Notify::new();
cancelled.notify_one();
assert!(gate_plugin_tool_calls(&set, &calls, &ctx, &|_event| {}, &cancelled).await.is_none());
}
#[test]
fn compaction_prompt_preserves_attachment_trust_boundary() {
assert!(COMPACT_SYSTEM_PROMPT.contains("<attached-text-data>"));
+52 -31
View File
@@ -280,13 +280,14 @@ pub fn is_vector_db(db_type: DatabaseType) -> bool {
/// the current UTC time plus a caller-provided local offset.
fn get_current_time_tool() -> ToolDefinition {
ToolDefinition {
name: "get_current_time",
name: "get_current_time".into(),
description: "Get the current date and time with timezone information. \
Pass the client UTC offset from the system prompt; when \
omitted, local time safely falls back to UTC. Use this to resolve \
relative time expressions like \"last 7 days\", \
\"yesterday\", \"this month\" into concrete dates \
for constructing SQL queries.",
for constructing SQL queries."
.into(),
parameters: json!({
"type": "object",
"properties": {
@@ -341,7 +342,9 @@ fn execute_get_current_time(tool_call: &ToolCall) -> Result<String, String> {
/// Get read-only tool definitions for the given database type.
/// Returns vector tools for vector DBs, SQL tools otherwise.
pub fn read_only_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
if is_vector_db(db_type) {
if db_type == DatabaseType::Plugin {
vec![get_current_time_tool()]
} else if is_vector_db(db_type) {
vec![list_collections_tool(), get_current_time_tool()]
} else {
vec![list_databases_tool(), list_tables_tool(), get_columns_tool(db_type), get_current_time_tool()]
@@ -352,6 +355,9 @@ pub fn read_only_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
/// Includes read-only tools plus execute_query, get_sample_data, and
/// explain_query for database types that support them.
pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) -> Vec<ToolDefinition> {
if db_type == DatabaseType::Plugin {
return vec![get_current_time_tool()];
}
if is_vector_db(db_type) {
return vec![list_collections_tool(), browse_collection_tool(), get_current_time_tool()];
}
@@ -375,8 +381,8 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
fn list_databases_tool() -> ToolDefinition {
ToolDefinition {
name: "list_databases",
description: "List databases available through the current connection. If more than one database is returned, cross-database read queries can use fully qualified names such as database.table (or database.schema.table for SQL Server).",
name: "list_databases".into(),
description: "List databases available through the current connection. If more than one database is returned, cross-database read queries can use fully qualified names such as database.table (or database.schema.table for SQL Server).".into(),
parameters: json!({"type": "object", "properties": {}, "required": []}),
read_only: true,
parallel_ok: true,
@@ -385,8 +391,8 @@ fn list_databases_tool() -> ToolDefinition {
fn mongo_execute_query_tool(_sql_permissions: AgentSqlPermissions) -> ToolDefinition {
ToolDefinition {
name: "execute_query",
description: "Execute a read-only MongoDB shell command and return results (max 50 rows). Use commands such as db.collection.find({}), db.collection.findOne({}), db.collection.aggregate([]), or db.collection.countDocuments({}). Write commands are not available to the MongoDB Agent.",
name: "execute_query".into(),
description: "Execute a read-only MongoDB shell command and return results (max 50 rows). Use commands such as db.collection.find({}), db.collection.findOne({}), db.collection.aggregate([]), or db.collection.countDocuments({}). Write commands are not available to the MongoDB Agent.".into(),
parameters: json!({
"type": "object",
"properties": {
@@ -423,8 +429,8 @@ fn solr_execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefiniti
request in one ```sql code block and ask for confirmation."
};
ToolDefinition {
name: "execute_query",
description,
name: "execute_query".into(),
description: description.into(),
parameters: json!({
"type": "object",
"properties": {
@@ -461,8 +467,9 @@ fn solr_execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefiniti
/// list_tables tool definition.
fn list_tables_tool() -> ToolDefinition {
ToolDefinition {
name: "list_tables",
description: "List all tables and views in the current database. Returns table names, types, and comments.",
name: "list_tables".into(),
description: "List all tables and views in the current database. Returns table names, types, and comments."
.into(),
parameters: json!({
"type": "object",
"properties": {
@@ -485,15 +492,17 @@ fn list_tables_tool() -> ToolDefinition {
/// get_columns tool definition.
fn get_columns_tool(db_type: DatabaseType) -> ToolDefinition {
ToolDefinition {
name: "get_columns",
name: "get_columns".into(),
description: if db_type == DatabaseType::MongoDb {
"Sample up to 100 documents from a MongoDB collection and infer up to 512 top-level field names and types. \
The sample may be smaller and is not a complete schema or a guarantee of required fields. \
Nested documents and arrays remain object and array fields; numeric BSON types are reported as number."
.into()
} else {
"Get column definitions for a table: names, types, primary keys, nullable, defaults, and comments. \
Use this when the user asks about table structure, column details, or field information — \
even if some schema context was provided, this tool returns the authoritative and complete column list."
.into()
},
parameters: json!({
"type": "object",
@@ -529,8 +538,8 @@ fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
"Execute a read-only SQL query and return results (default 50 rows, up to 1000 with the limit argument). Cross-database reads may use fully qualified names such as database.table (or database.schema.table for SQL Server) without switching the current database. This run cannot execute writes or DDL because no specific SQL has been confirmed yet; this does not mean the database itself is read-only. When the user requests a write, first propose the exact SQL in one ```sql code block and ask for confirmation. After confirmation, DBX starts a new run that can execute only that exact SQL. Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN statements may be executed in this run."
};
ToolDefinition {
name: "execute_query",
description,
name: "execute_query".into(),
description: description.into(),
parameters: json!({
"type": "object",
"properties": {
@@ -571,8 +580,8 @@ fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
/// get_sample_data tool definition.
fn get_sample_data_tool() -> ToolDefinition {
ToolDefinition {
name: "get_sample_data",
description: "Get sample rows from a table to understand its data. Returns up to 20 rows.",
name: "get_sample_data".into(),
description: "Get sample rows from a table to understand its data. Returns up to 20 rows.".into(),
parameters: json!({
"type": "object",
"properties": {
@@ -603,11 +612,12 @@ fn get_sample_data_tool() -> ToolDefinition {
/// explain_query tool definition (Phase 3).
fn explain_query_tool() -> ToolDefinition {
ToolDefinition {
name: "explain_query",
name: "explain_query".into(),
description: "Get the execution plan for a SQL query using EXPLAIN. \
Shows how the database will execute the query (scan type, indexes, cost). \
Only read-only queries (SELECT, WITH, SHOW, DESCRIBE, EXPLAIN) are allowed. \
Use this to analyze query performance and suggest index optimizations.",
Use this to analyze query performance and suggest index optimizations."
.into(),
parameters: json!({
"type": "object",
"properties": {
@@ -626,8 +636,9 @@ fn explain_query_tool() -> ToolDefinition {
/// list_collections tool definition (vector databases).
fn list_collections_tool() -> ToolDefinition {
ToolDefinition {
name: "list_collections",
description: "List all collections in the current vector database. Returns collection names and dimensions.",
name: "list_collections".into(),
description: "List all collections in the current vector database. Returns collection names and dimensions."
.into(),
parameters: json!({
"type": "object",
"properties": {},
@@ -641,8 +652,8 @@ fn list_collections_tool() -> ToolDefinition {
/// browse_collection tool definition (vector databases).
fn browse_collection_tool() -> ToolDefinition {
ToolDefinition {
name: "browse_collection",
description: "Browse documents in a collection. Returns up to 20 items with payload/metadata (vectors excluded for compactness). For ChromaDB, use the collection id (UUID from list_collections) instead of the collection name.",
name: "browse_collection".into(),
description: "Browse documents in a collection. Returns up to 20 items with payload/metadata (vectors excluded for compactness). For ChromaDB, use the collection id (UUID from list_collections) instead of the collection name.".into(),
parameters: json!({
"type": "object",
"properties": {
@@ -1697,7 +1708,7 @@ for line in sys.stdin:
#[test]
fn vector_read_only_tools_do_not_include_collection_browsing() {
let tools = read_only_tools(DatabaseType::Qdrant);
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"list_collections"));
assert!(!names.contains(&"browse_collection"));
@@ -1707,17 +1718,27 @@ for line in sys.stdin:
#[test]
fn vector_agent_tools_include_collection_browsing() {
let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default());
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"list_collections"));
assert!(names.contains(&"browse_collection"));
assert!(names.contains(&"get_current_time"));
}
#[test]
fn plugin_connections_only_receive_database_independent_builtin_tools() {
for tools in
[read_only_tools(DatabaseType::Plugin), all_tools(DatabaseType::Plugin, AgentSqlPermissions::default())]
{
let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
assert_eq!(names, ["get_current_time"]);
}
}
#[test]
fn solr_agent_registers_rest_execute_query_tool() {
let tools = all_tools(DatabaseType::Solr, AgentSqlPermissions::default());
let names = tools.iter().map(|tool| tool.name).collect::<Vec<_>>();
let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
// Solr gets the shared metadata tools plus a REST `execute_query`; SQL
// sample/explain helpers are not meaningful for a non-SQL backend.
assert!(names.contains(&"list_tables"));
@@ -1746,7 +1767,7 @@ for line in sys.stdin:
#[tokio::test]
async fn mongodb_agent_registers_shell_query_tool_and_routes_find_one_as_read_only() {
let tools = all_tools(DatabaseType::MongoDb, AgentSqlPermissions::default());
let names = tools.iter().map(|tool| tool.name).collect::<Vec<_>>();
let names = tools.iter().map(|tool| tool.name.as_ref()).collect::<Vec<_>>();
assert!(names.contains(&"execute_query"));
assert!(!names.contains(&"get_sample_data"));
assert!(!names.contains(&"explain_query"));
@@ -1906,7 +1927,7 @@ for line in sys.stdin:
#[test]
fn oracle_agent_tools_include_explain_query() {
let tools = all_tools(DatabaseType::Oracle, AgentSqlPermissions::default());
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"explain_query"));
}
@@ -2456,28 +2477,28 @@ for line in sys.stdin:
#[test]
fn get_current_time_is_in_all_tools_postgres() {
let tools = all_tools(DatabaseType::Postgres, AgentSqlPermissions::default());
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"get_current_time"), "get_current_time missing from all_tools(Postgres)");
}
#[test]
fn get_current_time_is_in_read_only_tools_postgres() {
let tools = read_only_tools(DatabaseType::Postgres);
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"get_current_time"), "get_current_time missing from read_only_tools(Postgres)");
}
#[test]
fn get_current_time_is_in_all_tools_qdrant() {
let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default());
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"get_current_time"), "get_current_time missing from all_tools(Qdrant)");
}
#[test]
fn get_current_time_is_in_read_only_tools_qdrant() {
let tools = read_only_tools(DatabaseType::Qdrant);
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
let names: Vec<&str> = tools.iter().map(|tool| tool.name.as_ref()).collect();
assert!(names.contains(&"get_current_time"), "get_current_time missing from read_only_tools(Qdrant)");
}
+2
View File
@@ -5,4 +5,6 @@ pub mod agent_kv;
pub mod agent_loop;
pub mod agent_tools;
pub mod mcp_policy;
pub mod plugin_tools;
pub mod prompt_template;
pub mod tool_approval;
File diff suppressed because it is too large. Load diff
+158
View File
@@ -0,0 +1,158 @@
//! Interactive approvals for agent tool calls.
//!
//! A tool call that may change state outside DBX (today: plugin MCP tools not
//! declared read-only) must not run on the model's word alone. The agent loop
//! registers a pending approval, emits `AgentEvent::ToolApprovalRequired`, and
//! suspends until the client answers through [`resolve_tool_approval`], the
//! deadline passes, or the run is cancelled.
//!
//! The registry is process-wide and deliberately runtime-agnostic (a std mutex
//! plus `oneshot` channels): the web server runs each agent loop on its own
//! runtime while the approval arrives through an HTTP handler on another one.
//! An approval is bound to the AI session that requested it, so a client can
//! only answer questions its own run asked.
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::Duration;
use tokio::sync::{oneshot, Notify};
/// How long a pending approval waits for the user before it counts as denied.
pub const TOOL_APPROVAL_TIMEOUT: Duration = Duration::from_secs(300);
struct PendingApproval {
session_id: String,
responder: oneshot::Sender<bool>,
}
fn pending_approvals() -> &'static Mutex<HashMap<String, PendingApproval>> {
static PENDING: OnceLock<Mutex<HashMap<String, PendingApproval>>> = OnceLock::new();
PENDING.get_or_init(|| Mutex::new(HashMap::new()))
}
/// How a wait for approval ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolApprovalWait {
Approved,
Denied,
TimedOut,
Cancelled,
}
/// A registered approval. Dropping it removes the entry, so an abandoned wait
/// (cancelled future, early return) can never leave a stale approval behind
/// for a later answer to hit.
pub struct PendingToolApproval {
approval_id: String,
receiver: Option<oneshot::Receiver<bool>>,
}
impl PendingToolApproval {
pub fn id(&self) -> &str {
&self.approval_id
}
/// Waits for the user's answer. A dropped responder (the entry was purged)
/// counts as a denial: without an answer there is no approval.
pub async fn wait(mut self, timeout: Duration, cancelled: &Notify) -> ToolApprovalWait {
let Some(receiver) = self.receiver.take() else {
return ToolApprovalWait::Denied;
};
tokio::select! {
biased;
_ = cancelled.notified() => ToolApprovalWait::Cancelled,
answer = tokio::time::timeout(timeout, receiver) => match answer {
Ok(Ok(true)) => ToolApprovalWait::Approved,
Ok(Ok(false)) | Ok(Err(_)) => ToolApprovalWait::Denied,
Err(_) => ToolApprovalWait::TimedOut,
},
}
}
}
impl Drop for PendingToolApproval {
fn drop(&mut self) {
pending_approvals().lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.approval_id);
}
}
/// Registers a pending approval for `session_id`.
pub fn register_tool_approval(session_id: &str) -> PendingToolApproval {
let approval_id = uuid::Uuid::new_v4().to_string();
let (responder, receiver) = oneshot::channel();
pending_approvals()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(approval_id.clone(), PendingApproval { session_id: session_id.to_string(), responder });
PendingToolApproval { approval_id, receiver: Some(receiver) }
}
/// Answers a pending approval. Returns `false` when no approval with this id is
/// pending for `session_id` (already answered, timed out, or never asked).
pub fn resolve_tool_approval(session_id: &str, approval_id: &str, approved: bool) -> bool {
let mut pending = pending_approvals().lock().unwrap_or_else(|poisoned| poisoned.into_inner());
let belongs_to_session = pending.get(approval_id).is_some_and(|entry| entry.session_id == session_id);
if !belongs_to_session {
return false;
}
let Some(entry) = pending.remove(approval_id) else {
return false;
};
entry.responder.send(approved).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn resolved_approval_reports_the_user_answer() {
let cancelled = Notify::new();
let approval = register_tool_approval("session-a");
let id = approval.id().to_string();
assert!(resolve_tool_approval("session-a", &id, true));
assert_eq!(approval.wait(Duration::from_secs(5), &cancelled).await, ToolApprovalWait::Approved);
let denied = register_tool_approval("session-a");
let id = denied.id().to_string();
assert!(resolve_tool_approval("session-a", &id, false));
assert_eq!(denied.wait(Duration::from_secs(5), &cancelled).await, ToolApprovalWait::Denied);
}
#[tokio::test]
async fn another_session_cannot_answer_an_approval() {
let cancelled = Notify::new();
let approval = register_tool_approval("owner");
let id = approval.id().to_string();
assert!(!resolve_tool_approval("intruder", &id, true));
assert!(resolve_tool_approval("owner", &id, false));
assert_eq!(approval.wait(Duration::from_secs(5), &cancelled).await, ToolApprovalWait::Denied);
}
#[tokio::test]
async fn unanswered_approval_times_out_and_is_forgotten() {
let cancelled = Notify::new();
let approval = register_tool_approval("session-b");
let id = approval.id().to_string();
assert_eq!(approval.wait(Duration::from_millis(20), &cancelled).await, ToolApprovalWait::TimedOut);
assert!(!resolve_tool_approval("session-b", &id, true), "a timed-out approval must not accept a late answer");
}
#[tokio::test]
async fn cancellation_ends_the_wait() {
let cancelled = Notify::new();
cancelled.notify_one();
let approval = register_tool_approval("session-c");
assert_eq!(approval.wait(Duration::from_secs(5), &cancelled).await, ToolApprovalWait::Cancelled);
}
#[tokio::test]
async fn cancellation_wins_over_an_answer_that_arrived_at_the_same_time() {
let cancelled = Notify::new();
let approval = register_tool_approval("session-race");
assert!(resolve_tool_approval("session-race", approval.id(), true));
cancelled.notify_one();
assert_eq!(approval.wait(Duration::from_secs(5), &cancelled).await, ToolApprovalWait::Cancelled);
}
}