feat(ai): cross-database query with multi database selection

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-09-14 13:50:17 +08:00
1 parent 58d902c07f
commit 193d875b8a
20 files changed
+240 -57

No files matched your search

+2
View File
@@ -76,6 +76,7 @@ pub struct AgentLoopContext {
pub state: Arc<AppState>,
pub connection_id: String,
pub database: String,
pub selected_databases: Vec<String>,
/// Selected schema that scopes Agent metadata and SQL execution.
pub schema: Option<String>,
pub db_type: DatabaseType,
@@ -151,6 +152,7 @@ pub async fn run_agent_loop(
connection_id: agent_ctx.connection_id.clone(),
connection_name,
database: agent_ctx.database.clone(),
selected_databases: agent_ctx.selected_databases.clone(),
schema: agent_ctx.schema.clone(),
agent_mode: is_agent_mode,
allow_writes: agent_ctx.sql_permissions.allow_writes,
+59 -7
View File
@@ -55,7 +55,8 @@ fn connection_tool_lock(connection_id: &str) -> Arc<tokio::sync::Mutex<()>> {
fn tool_uses_database(tool_name: &str) -> bool {
matches!(
tool_name,
"list_tables"
"list_databases"
| "list_tables"
| "get_columns"
| "execute_query"
| "get_sample_data"
@@ -320,7 +321,7 @@ pub fn read_only_tools(db_type: DatabaseType) -> Vec<ToolDefinition> {
if is_vector_db(db_type) {
vec![list_collections_tool(), get_current_time_tool()]
} else {
vec![list_tables_tool(), get_columns_tool(), get_current_time_tool()]
vec![list_databases_tool(), list_tables_tool(), get_columns_tool(), get_current_time_tool()]
}
}
@@ -331,7 +332,7 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
if is_vector_db(db_type) {
return vec![list_collections_tool(), browse_collection_tool(), get_current_time_tool()];
}
let mut tools = vec![list_tables_tool(), get_columns_tool(), get_current_time_tool()];
let mut tools = vec![list_databases_tool(), list_tables_tool(), get_columns_tool(), get_current_time_tool()];
if db_type == DatabaseType::MongoDb {
tools.push(mongo_execute_query_tool(sql_permissions));
} else if supports_sql_query(db_type) {
@@ -344,6 +345,16 @@ pub fn all_tools(db_type: DatabaseType, sql_permissions: AgentSqlPermissions) ->
tools
}
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).",
parameters: json!({"type": "object", "properties": {}, "required": []}),
read_only: true,
parallel_ok: true,
}
}
fn mongo_execute_query_tool(_sql_permissions: AgentSqlPermissions) -> ToolDefinition {
ToolDefinition {
name: "execute_query",
@@ -378,6 +389,10 @@ fn list_tables_tool() -> ToolDefinition {
"schema": {
"type": "string",
"description": "Schema name to list tables from (optional, defaults to current database)"
},
"database": {
"type": "string",
"description": "Database to inspect (optional, defaults to the current database)"
}
},
"required": []
@@ -405,6 +420,10 @@ fn get_columns_tool() -> ToolDefinition {
"schema": {
"type": "string",
"description": "Schema name (optional, defaults to current database)"
},
"database": {
"type": "string",
"description": "Database containing the table (optional, defaults to the current database)"
}
},
"required": ["table"]
@@ -422,7 +441,7 @@ fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition {
} 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). 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."
"Execute a read-only SQL query and return results (max 50 rows). 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",
@@ -478,6 +497,10 @@ fn get_sample_data_tool() -> ToolDefinition {
"type": "string",
"description": "Schema name (optional)"
},
"database": {
"type": "string",
"description": "Database containing the table (optional, defaults to the current database)"
},
"limit": {
"type": "number",
"description": "Max rows (default 20)"
@@ -572,6 +595,7 @@ pub async fn execute_tool(
None
};
let result = match tool_call.name.as_str() {
"list_databases" => execute_list_databases(tool_call, state, connection_id).await,
"list_tables" => execute_list_tables(tool_call, state, connection_id, database, default_schema, db_type).await,
"get_columns" => execute_get_columns(tool_call, state, connection_id, database, default_schema, db_type).await,
"execute_query" => {
@@ -629,6 +653,20 @@ pub async fn execute_tool(
}
}
async fn execute_list_databases(
_tool_call: &ToolCall,
state: &Arc<AppState>,
connection_id: &str,
) -> Result<String, String> {
let databases = crate::schema::list_databases_core(state, connection_id)
.await
.map_err(|e| format!("Failed to list databases: {e}"))?;
if databases.is_empty() {
return Ok("No databases were returned for this connection.".to_string());
}
Ok(databases.into_iter().map(|database| format!("- {}", database.name)).collect::<Vec<_>>().join("\n"))
}
async fn execute_list_tables(
tool_call: &ToolCall,
state: &Arc<AppState>,
@@ -637,13 +675,14 @@ async fn execute_list_tables(
default_schema: Option<&str>,
_db_type: &DatabaseType,
) -> Result<String, String> {
let database = effective_database(tool_call, database);
let schema = effective_schema(tool_call, default_schema).unwrap_or_default();
// Request one extra to detect whether more tables exist beyond the limit.
let tables = crate::schema::list_tables_core(
state,
connection_id,
database,
&database,
&schema,
None,
Some(LIST_TABLES_LIMIT + 1),
@@ -689,6 +728,7 @@ async fn execute_get_columns(
default_schema: Option<&str>,
_db_type: &DatabaseType,
) -> Result<String, String> {
let database = effective_database(tool_call, database);
let table = tool_call
.arguments
.get("table")
@@ -710,7 +750,7 @@ async fn execute_get_columns(
let schema = effective_schema(tool_call, default_schema).unwrap_or_default();
let columns = crate::schema::get_columns_core(state, connection_id, database, &schema, &table)
let columns = crate::schema::get_columns_core(state, connection_id, &database, &schema, &table)
.await
.map_err(|e| format!("Failed to get columns for {table}: {e}"))?;
@@ -999,6 +1039,7 @@ async fn execute_get_sample_data(
default_schema: Option<&str>,
db_type: &DatabaseType,
) -> Result<String, String> {
let database = effective_database(tool_call, database);
let table =
tool_call.arguments.get("table").and_then(|v| v.as_str()).ok_or("Missing required parameter: table")?.trim();
@@ -1032,7 +1073,7 @@ async fn execute_get_sample_data(
&synthetic_call,
state,
connection_id,
database,
&database,
schema.as_deref(),
db_type,
AgentSqlPermissions::default(),
@@ -1171,6 +1212,17 @@ fn effective_schema(tool_call: &ToolCall, default_schema: Option<&str>) -> Optio
})
}
fn effective_database(tool_call: &ToolCall, default_database: &str) -> String {
tool_call
.arguments
.get("database")
.and_then(Value::as_str)
.map(str::trim)
.filter(|database| !database.is_empty())
.map(ToOwned::to_owned)
.unwrap_or_else(|| default_database.to_string())
}
/// Execute list_collections tool (vector databases).
async fn execute_list_collections(
_tool_call: &ToolCall,
@@ -602,6 +602,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "local".to_string(),
database: "demo".to_string(),
selected_databases: Vec::new(),
schema: None,
agent_mode: true,
allow_writes: false,
+47 -2
View File
@@ -14,6 +14,7 @@ pub struct CliAgentRunOptions {
pub connection_id: String,
pub connection_name: String,
pub database: String,
pub selected_databases: Vec<String>,
pub schema: Option<String>,
pub agent_mode: bool,
pub allow_writes: bool,
@@ -72,14 +73,27 @@ pub fn dbx_mcp_enabled_tools(agent_mode: bool) -> Vec<&'static str> {
}
pub fn dbx_mcp_scope_env(options: &CliAgentRunOptions) -> Vec<(&'static str, String)> {
let mut databases: Vec<&str> = Vec::new();
for database in &options.selected_databases {
let database = database.trim();
if !database.is_empty() && !databases.contains(&database) {
databases.push(database);
}
}
let multiple_databases = databases.len() > 1;
// An empty value explicitly clears inherited/configured single-database
// bounds. MCP's persisted connection/database policy still applies.
let database_scope = if multiple_databases { "" } else { databases.first().copied().unwrap_or(&options.database) };
let mut env = vec![
("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()),
("DBX_MCP_SCOPE_DATABASE", database_scope.to_string()),
];
if let Some(schema) = options.schema.as_deref().filter(|schema| !schema.trim().is_empty()) {
if multiple_databases {
env.push(("DBX_MCP_SCOPE_SCHEMA", String::new()));
} else if let Some(schema) = options.schema.as_deref().filter(|schema| !schema.trim().is_empty()) {
env.push(("DBX_MCP_SCOPE_SCHEMA", schema.to_string()));
}
if let Some(ref sql) = options.confirmed_write_sql {
@@ -92,12 +106,43 @@ pub fn dbx_mcp_scope_env(options: &CliAgentRunOptions) -> Vec<(&'static str, Str
mod scope_env_tests {
use super::*;
#[test]
fn database_selection_controls_runtime_bounds_without_changing_write_permissions() {
for (selection, expected_database, expected_schema) in [
(vec![], "db_a", "public"),
(vec!["db_b"], "db_b", "public"),
(vec!["db_a", "db_b"], "", ""),
(vec![" db_a ", "db_a", " "], "db_a", "public"),
] {
let options = CliAgentRunOptions {
connection_id: "conn-1".into(),
connection_name: "Test".into(),
database: "db_a".into(),
selected_databases: selection.into_iter().map(str::to_string).collect(),
schema: Some("public".into()),
agent_mode: true,
allow_writes: false,
allow_dangerous: false,
confirmed_write_sql: None,
mcp_server_command: None,
};
let env: std::collections::HashMap<_, _> = dbx_mcp_scope_env(&options).into_iter().collect();
assert_eq!(env["DBX_MCP_SCOPE_DATABASE"], expected_database);
assert_eq!(env["DBX_MCP_SCOPE_SCHEMA"], expected_schema);
assert_eq!(env["DBX_MCP_SCOPE_CONNECTION_ID"], "conn-1");
assert_eq!(env["DBX_MCP_ALLOW_WRITES"], "0");
assert_eq!(env["DBX_MCP_ALLOW_DANGEROUS_SQL"], "0");
assert!(!env.contains_key("DBX_MCP_CONFIRMED_WRITE_SQL"));
}
}
#[test]
fn confirmed_write_sql_is_passed_to_the_scoped_mcp_subprocess() {
let options = CliAgentRunOptions {
connection_id: "dameng-1".to_string(),
connection_name: "Dameng".to_string(),
database: "APPDB".to_string(),
selected_databases: Vec::new(),
schema: Some("REPORTING".to_string()),
agent_mode: true,
allow_writes: true,
+3
View File
@@ -957,6 +957,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "local".to_string(),
database: "demo".to_string(),
selected_databases: Vec::new(),
schema: None,
agent_mode: true,
allow_writes: false,
@@ -1385,6 +1386,7 @@ exit 9
connection_id: String::new(),
connection_name: connection_name.clone(),
database,
selected_databases: Vec::new(),
schema: None,
agent_mode: false,
allow_writes: false,
@@ -1440,6 +1442,7 @@ exit 9
connection_id: String::new(),
connection_name,
database,
selected_databases: Vec::new(),
schema: None,
agent_mode: true,
allow_writes: false,
+1
View File
@@ -1148,6 +1148,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "local".to_string(),
database: "demo".to_string(),
selected_databases: Vec::new(),
schema: None,
agent_mode: true,
allow_writes: false,
+2
View File
@@ -517,6 +517,7 @@ mod tests {
connection_id: "sqlite-1".to_string(),
connection_name: "SQLite".to_string(),
database: "main".to_string(),
selected_databases: Vec::new(),
schema: None,
agent_mode: false,
allow_writes: false,
@@ -571,6 +572,7 @@ mod tests {
connection_id: String::new(),
connection_name: connection_name.clone(),
database,
selected_databases: Vec::new(),
schema: None,
agent_mode: false,
allow_writes: false,
+1
View File
@@ -819,6 +819,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "Demo".to_string(),
database: "app".to_string(),
selected_databases: Vec::new(),
schema: None,
agent_mode: true,
allow_writes: false,
+2
View File
@@ -485,6 +485,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "Local".to_string(),
database: "demo".to_string(),
selected_databases: Vec::new(),
schema: Some("public".to_string()),
agent_mode: true,
allow_writes: false,
@@ -654,6 +655,7 @@ mod tests {
connection_id: String::new(),
connection_name: connection_name.clone(),
database,
selected_databases: Vec::new(),
schema: None,
agent_mode: false,
allow_writes: false,
+1
View File
@@ -1017,6 +1017,7 @@ mod tests {
connection_id: "connection-1".to_string(),
connection_name: "Test connection".to_string(),
database: "dbx_test".to_string(),
selected_databases: Vec::new(),
schema: Some("reporting".to_string()),
agent_mode: true,
allow_writes: true,
+1
View File
@@ -561,6 +561,7 @@ mod tests {
connection_id: "conn-1".to_string(),
connection_name: "local".to_string(),
database: "demo".to_string(),
selected_databases: Vec::new(),
schema: Some("public".to_string()),
agent_mode: true,
allow_writes: false,