fix(ai): improve assistant execution and MCP settings

This commit is contained in:
t8y2 committed 2026-07-10 14:31:08 +08:00
1 parent 1c18a80092
commit 5a666b1f48
20 files changed
+213 -47

No files matched your search

+10 -4
View File
@@ -65,6 +65,7 @@ pub struct AgentLoopContext {
pub database: String,
pub db_type: DatabaseType,
pub cli_mcp_server_command: Option<CliAgentCommandSpec>,
pub sql_permissions: agent_tools::AgentSqlPermissions,
}
/// Check if the provider supports function calling / tool use.
@@ -108,7 +109,8 @@ pub async fn run_agent_loop(
.map(|config| config.name.clone())
.unwrap_or_else(|| agent_ctx.connection_id.clone())
};
let prompt = crate::ai_codex_cli::build_codex_prompt(system_prompt, messages);
let prompt =
crate::ai_codex_cli::build_codex_prompt(system_prompt, messages, agent_ctx.sql_permissions.allow_writes);
return crate::ai_codex_cli::run_codex_agent(
config,
&prompt,
@@ -117,6 +119,8 @@ pub async fn run_agent_loop(
connection_name,
database: agent_ctx.database.clone(),
agent_mode: is_agent_mode,
allow_writes: agent_ctx.sql_permissions.allow_writes,
allow_dangerous: agent_ctx.sql_permissions.allow_dangerous,
mcp_server_command: agent_ctx.cli_mcp_server_command.clone(),
},
cancelled,
@@ -140,7 +144,7 @@ pub async fn run_agent_loop(
.await;
}
let tools = if is_agent_mode {
agent_tools::all_tools(agent_ctx.db_type)
agent_tools::all_tools(agent_ctx.db_type, agent_ctx.sql_permissions)
} else {
agent_tools::read_only_tools(agent_ctx.db_type)
};
@@ -343,6 +347,7 @@ pub async fn run_agent_loop(
let conn2 = agent_ctx.connection_id.clone();
let db2 = agent_ctx.database.clone();
let db_type = agent_ctx.db_type;
let sql_permissions = agent_ctx.sql_permissions;
// Split by index into parallel and sequential groups using tool metadata
let tool_parallel_map: std::collections::HashMap<&str, bool> =
@@ -361,7 +366,7 @@ pub async fn run_agent_loop(
let state = Arc::clone(&state2);
let conn = conn2.clone();
let db = db2.clone();
async move { agent_tools::execute_tool(&tc, &state, &conn, &db, &db_type).await }
async move { agent_tools::execute_tool(&tc, &state, &conn, &db, &db_type, sql_permissions).await }
})
.collect();
let parallel_results = join_all(parallel_futures).await;
@@ -370,7 +375,8 @@ pub async fn run_agent_loop(
let mut sequential_results = Vec::with_capacity(sequential_indices.len());
for &i in &sequential_indices {
let tc = make_tc(&collected_tool_calls[i]);
sequential_results.push(agent_tools::execute_tool(&tc, &state2, &conn2, &db2, &db_type).await);
sequential_results
.push(agent_tools::execute_tool(&tc, &state2, &conn2, &db2, &db_type, sql_permissions).await);
}
// Merge results back into original order
+61 -16
View File
@@ -26,6 +26,21 @@ const BROWSE_COLLECTION_LIMIT: usize = 20;
/// Absolute maximum rows any query tool may request.
const MAX_ALLOWED_ROWS: usize = 100;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AgentSqlPermissions {
pub allow_writes: bool,
pub allow_dangerous: bool,
}
fn sql_risk_allowed(risk: SqlRisk, permissions: AgentSqlPermissions) -> bool {
match risk {
SqlRisk::ReadOnly => true,
SqlRisk::Write => permissions.allow_writes,
SqlRisk::Ddl => permissions.allow_dangerous,
SqlRisk::Transaction => false,
}
}
/// Returns true for vector database types (Qdrant, Milvus, Weaviate, ChromaDb).
/// If modifying this, also update VECTOR_DB_TYPES in apps/desktop/src/lib/ai.ts.
pub fn is_vector_db(db_type: DatabaseType) -> bool {
@@ -45,13 +60,13 @@ pub fn read_only_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
/// Get all available tool definitions for the given database type.
/// 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) -> Vec<ToolDefinition> {
pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) -> Vec<ToolDefinition> {
if is_vector_db(db_type) {
return vec![list_collections_tool(), browse_collection_tool()];
}
let mut tools = vec![list_tables_tool(), get_columns_tool()];
if supports_sql_query(db_type) {
tools.push(execute_query_tool());
tools.push(execute_query_tool(sql_permissions));
tools.push(get_sample_data_tool());
}
if supports_explain_plan(Some(db_type)) {
@@ -109,12 +124,17 @@ fn get_columns_tool() -> ToolDefinition {
}
}
/// execute_query tool definition.
fn execute_query_tool() -> ToolDefinition {
fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
let description = if sql_permissions.allow_dangerous {
"Execute SQL after the user explicitly confirmed this operation. Read queries, writes, and DDL are allowed for this run."
} else if sql_permissions.allow_writes {
"Execute SQL after the user explicitly confirmed this operation. Read queries and non-DDL writes are allowed for this run."
} else {
"Execute a read-only SQL query and return results (max 50 rows). Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN statements are allowed. Write operations (INSERT/UPDATE/DELETE/DDL) are blocked."
};
ToolDefinition {
name: "execute_query",
description: "Execute a read-only SQL query and return results (max 50 rows). \
Only SELECT, WITH, SHOW, DESCRIBE, EXPLAIN statements are allowed. \
Write operations (INSERT/UPDATE/DELETE/DDL) are blocked.",
description,
parameters: json!({
"type": "object",
"properties": {
@@ -231,11 +251,14 @@ pub async fn execute_tool(
connection_id: &str,
database: &str,
db_type: &DatabaseType,
sql_permissions: AgentSqlPermissions,
) -> ToolResult {
let result = match tool_call.name.as_str() {
"list_tables" => execute_list_tables(tool_call, state, connection_id, database, db_type).await,
"get_columns" => execute_get_columns(tool_call, state, connection_id, database, db_type).await,
"execute_query" => execute_execute_query(tool_call, state, connection_id, database, db_type).await,
"execute_query" => {
execute_execute_query(tool_call, state, connection_id, database, db_type, sql_permissions).await
}
"get_sample_data" => execute_get_sample_data(tool_call, state, connection_id, database, db_type).await,
"list_collections" => execute_list_collections(tool_call, state, connection_id, database, db_type).await,
"browse_collection" => execute_browse_collection(tool_call, state, connection_id, database, db_type).await,
@@ -415,6 +438,7 @@ async fn execute_execute_query(
connection_id: &str,
database: &str,
db_type: &DatabaseType,
sql_permissions: AgentSqlPermissions,
) -> Result<String, String> {
let sql = tool_call.arguments.get("sql").and_then(|v| v.as_str()).ok_or("Missing required parameter: sql")?.trim();
@@ -432,14 +456,14 @@ async fn execute_execute_query(
// Classify SQL risk using sqlparser AST
let db_type_str = format!("{:?}", db_type).to_lowercase();
let risk = crate::sql_risk::classify_sql_risk(sql, &db_type_str)?;
match risk {
SqlRisk::ReadOnly => { /* proceed */ }
_ => {
return Err(format!(
"Blocked: {} statement detected. Only read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN) are allowed.",
risk
));
if !sql_risk_allowed(risk, sql_permissions) {
if risk == SqlRisk::Transaction {
return Err("Blocked: transaction control statements are not available to the AI agent.".to_string());
}
return Err(format!(
"Blocked: {} statement detected. Ask the user to confirm the proposed database change before executing it.",
risk
));
}
// Execute query using existing infrastructure
@@ -533,7 +557,8 @@ async fn execute_get_sample_data(
name: "execute_query".to_string(),
arguments: serde_json::json!({ "sql": sql, "limit": limit }),
};
execute_execute_query(&synthetic_call, state, connection_id, database, db_type).await
execute_execute_query(&synthetic_call, state, connection_id, database, db_type, AgentSqlPermissions::default())
.await
}
/// Execute an EXPLAIN query via the explain_query tool.
@@ -772,12 +797,32 @@ mod tests {
#[test]
fn vector_agent_tools_include_collection_browsing() {
let tools = all_tools(DatabaseType::Qdrant);
let tools = all_tools(DatabaseType::Qdrant, AgentSqlPermissions::default());
let names: Vec<&str> = tools.iter().map(|tool| tool.name).collect();
assert_eq!(names, vec!["list_collections", "browse_collection"]);
}
#[test]
fn confirmed_sql_permissions_update_execute_query_contract() {
let tools = all_tools(DatabaseType::Mysql, AgentSqlPermissions { allow_writes: true, allow_dangerous: true });
let execute_query = tools.iter().find(|tool| tool.name == "execute_query").unwrap();
assert!(execute_query.description.contains("explicitly confirmed"));
assert!(execute_query.description.contains("DDL"));
}
#[test]
fn sql_permissions_keep_writes_blocked_until_confirmation() {
assert!(!sql_risk_allowed(SqlRisk::Write, AgentSqlPermissions::default()));
assert!(!sql_risk_allowed(SqlRisk::Ddl, AgentSqlPermissions::default()));
assert!(sql_risk_allowed(SqlRisk::Ddl, AgentSqlPermissions { allow_writes: true, allow_dangerous: true }));
assert!(!sql_risk_allowed(
SqlRisk::Transaction,
AgentSqlPermissions { allow_writes: true, allow_dangerous: true }
));
}
#[test]
fn build_browse_query_qdrant() {
let q = build_browse_query(&DatabaseType::Qdrant, "articles", "", 10).unwrap();
+16 -3
View File
@@ -14,6 +14,8 @@ pub struct CliAgentRunOptions {
pub connection_name: String,
pub database: String,
pub agent_mode: bool,
pub allow_writes: bool,
pub allow_dangerous: bool,
pub mcp_server_command: Option<CliAgentCommandSpec>,
}
@@ -57,7 +59,8 @@ pub fn dbx_mcp_enabled_tools(agent_mode: bool) -> Vec<&'static str> {
pub fn dbx_mcp_scope_env(options: &CliAgentRunOptions) -> Vec<(&'static str, String)> {
vec![
("DBX_MCP_ALLOW_WRITES", "0".to_string()),
("DBX_MCP_ALLOW_WRITES", if options.allow_writes { "1" } else { "0" }.to_string()),
("DBX_MCP_ALLOW_DANGEROUS_SQL", if options.allow_dangerous { "1" } else { "0" }.to_string()),
("DBX_MCP_SCOPE_CONNECTION_ID", options.connection_id.clone()),
("DBX_MCP_SCOPE_CONNECTION_NAME", options.connection_name.clone()),
("DBX_MCP_SCOPE_DATABASE", options.database.clone()),
@@ -71,10 +74,20 @@ pub fn append_config_overrides(args: &mut Vec<String>, overrides: impl IntoItera
}
}
pub fn build_cli_agent_prompt(provider_label: &str, system_prompt: &str, messages: &[AiMessage]) -> String {
pub fn build_cli_agent_prompt(
provider_label: &str,
system_prompt: &str,
messages: &[AiMessage],
allow_write_sql: bool,
) -> String {
let database_access = if allow_write_sql {
"The user explicitly confirmed the proposed database change. DBX MCP tools may execute write and DDL SQL for this run only."
} else {
"Use the DBX MCP tools when you need live database schema or read-only query results."
};
let mut sections = vec![
format!("You are running inside DBX Desktop as the {provider_label} CLI provider."),
"Use the DBX MCP tools when you need live database schema or read-only query results.".to_string(),
database_access.to_string(),
"Do not modify files or run shell commands. The DBX MCP server is the only intended tool surface.".to_string(),
String::new(),
"## System instructions".to_string(),
+5 -2
View File
@@ -433,8 +433,8 @@ pub fn build_codex_exec_command(config: &AiConfig, _prompt: &str, options: &Code
CodexCommandSpec { program: codex_program(config), args }
}
pub fn build_codex_prompt(system_prompt: &str, messages: &[crate::ai::AiMessage]) -> String {
build_cli_agent_prompt("Codex", system_prompt, messages)
pub fn build_codex_prompt(system_prompt: &str, messages: &[crate::ai::AiMessage], allow_write_sql: bool) -> String {
build_cli_agent_prompt("Codex", system_prompt, messages, allow_write_sql)
}
pub async fn list_codex_models(config: &AiConfig) -> Result<Vec<AiModelInfo>, String> {
@@ -622,6 +622,8 @@ mod tests {
connection_name: "local".to_string(),
database: "demo".to_string(),
agent_mode: true,
allow_writes: false,
allow_dangerous: false,
mcp_server_command: None,
}
}
@@ -639,6 +641,7 @@ mod tests {
assert!(spec.args.contains(&"mcp_servers.dbx.command=\"dbx-mcp-server\"".to_string()));
assert!(spec.args.contains(&"mcp_servers.dbx.default_tools_approval_mode=\"approve\"".to_string()));
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_ALLOW_WRITES=\"0\"".to_string()));
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_ALLOW_DANGEROUS_SQL=\"0\"".to_string()));
assert!(spec.args.contains(&"mcp_servers.dbx.env.DBX_MCP_SCOPE_CONNECTION_ID=\"conn-1\"".to_string()));
assert!(spec.args.iter().any(|arg| arg.contains("dbx_execute_query")));
}