From f5daba54b6e8584700d14e095b592688494b8d49 Mon Sep 17 00:00:00 2001 From: lizujie Date: Thu, 30 Jul 2026 00:58:40 +0800 Subject: [PATCH] feat(mcp): add stateful pinned query sessions --- crates/dbx-core/src/agent_tools.rs | 16 +- crates/dbx-core/src/sql_risk.rs | 3 + crates/dbx-mcp/src/backend.rs | 91 ++++- crates/dbx-mcp/src/lib.rs | 2 + crates/dbx-mcp/src/server.rs | 424 ++++++++++++++++++++++-- crates/dbx-mcp/src/session.rs | 208 ++++++++++++ crates/dbx-mcp/tests/protocol.rs | 4 +- crates/dbx-web/src/routes/mcp_policy.rs | 3 +- crates/dbx-web/src/routes/query.rs | 10 +- 9 files changed, 704 insertions(+), 57 deletions(-) create mode 100644 crates/dbx-mcp/src/session.rs diff --git a/crates/dbx-core/src/agent_tools.rs b/crates/dbx-core/src/agent_tools.rs index c2bd8712fe..601fd3004e 100644 --- a/crates/dbx-core/src/agent_tools.rs +++ b/crates/dbx-core/src/agent_tools.rs @@ -204,6 +204,10 @@ fn execute_query_tool(sql_permissions: AgentSqlPermissions) -> ToolDefinition { "limit": { "type": "number", "description": "Max rows to return (default 50, max 100)" + }, + "client_session_id": { + "type": "string", + "description": "Opaque DBX session handle that pins this query to the same backend connection as earlier queries in the session (preserves USE/SET/session state). Managed by DBX; agents should not invent values." } }, "required": ["sql"] @@ -572,8 +576,18 @@ async fn execute_execute_query( )); } + // Stateful callers (e.g. MCP sessions) pin the query to their dedicated + // connection pool so USE/SET and other session state is preserved. + let client_session_id = + tool_call.arguments.get("client_session_id").and_then(|v| v.as_str()).map(str::trim).filter(|v| !v.is_empty()); + // Execute query using existing infrastructure - let options = QueryExecutionOptions { max_rows: Some(limit), timeout_secs: Some(30), ..Default::default() }; + let options = QueryExecutionOptions { + max_rows: Some(limit), + timeout_secs: Some(30), + client_session_id: client_session_id.map(str::to_string), + ..Default::default() + }; let result = crate::query::execute_sql_statement_with_options(state, connection_id, database, sql, None, None, options) .await?; diff --git a/crates/dbx-core/src/sql_risk.rs b/crates/dbx-core/src/sql_risk.rs index 483b1c55c8..db6f4ddf6c 100644 --- a/crates/dbx-core/src/sql_risk.rs +++ b/crates/dbx-core/src/sql_risk.rs @@ -136,6 +136,9 @@ fn classify_statement(stmt: &Statement, detect_select_into: bool) -> SqlRisk { fn statement_is_dangerous(stmt: &Statement, detect_select_into: bool) -> bool { match stmt { + // `USE` only changes connection-local state. MCP separately requires + // a pinned session for it, so it does not need dangerous-SQL approval. + Statement::Use(_) => false, Statement::Query(query) => query_is_dangerous(query, detect_select_into), Statement::Insert(insert) => { insert.replace_into diff --git a/crates/dbx-mcp/src/backend.rs b/crates/dbx-mcp/src/backend.rs index 0cb7d7b068..789fb0e7c2 100644 --- a/crates/dbx-mcp/src/backend.rs +++ b/crates/dbx-mcp/src/backend.rs @@ -134,6 +134,16 @@ pub trait DbxBackend: Send + Sync { let _ = (connection, database, command); Err("MongoDB shell commands are not supported by this backend.".to_string()) } + /// Release the connection pool pinned by an MCP session (`client_session_id`). + async fn close_client_session( + &self, + connection_id: &str, + database: &str, + client_session_id: &str, + ) -> Result { + let _ = (connection_id, database, client_session_id); + Err("Session cleanup is not supported by this backend.".to_string()) + } async fn bridge_request(&self, path: &str, body: Value) -> Result<(), String> { let _ = (path, body); Err("DBX is not running. Please start DBX first.".to_string()) @@ -156,6 +166,7 @@ pub struct WebBackend { password: String, client: reqwest::Client, auth: Mutex, + connected: Mutex>, } impl WebBackend { @@ -168,7 +179,13 @@ impl WebBackend { .redirect(reqwest::redirect::Policy::none()) .build() .map_err(|error| error.to_string())?; - Ok(Self { base_url, password, client, auth: Mutex::new(WebAuthState::default()) }) + Ok(Self { + base_url, + password, + client, + auth: Mutex::new(WebAuthState::default()), + connected: Mutex::new(HashMap::new()), + }) } async fn ensure_auth(&self) -> Result<(), String> { @@ -260,7 +277,12 @@ impl WebBackend { } async fn ensure_connected(&self, connection: &ConnectionConfig) -> Result<(), String> { + let mut connected = self.connected.lock().await; + if connected.get(&connection.id) == Some(connection) { + return Ok(()); + } self.request(reqwest::Method::POST, "/api/connection/connect", Some(json!({ "config": connection }))).await?; + connected.insert(connection.id.clone(), connection.clone()); Ok(()) } } @@ -598,6 +620,16 @@ impl DbxBackend for LocalBackend { } } + async fn close_client_session( + &self, + connection_id: &str, + database: &str, + client_session_id: &str, + ) -> Result { + let database = if database.trim().is_empty() { None } else { Some(database) }; + self.state.close_client_session_pool(connection_id, database, client_session_id).await + } + async fn bridge_request(&self, path: &str, body: Value) -> Result<(), String> { let port = tokio::fs::read_to_string(self.data_dir.join("mcp-bridge-port")) .await @@ -678,13 +710,12 @@ impl DbxBackend for WebBackend { } let max_rows = arguments.get("limit").and_then(Value::as_u64).unwrap_or(100) as usize; - let response = self - .request( - reqwest::Method::POST, - "/api/query/execute", - Some(json!({ "connectionId": connection.id, "database": database, "sql": sql })), - ) - .await?; + let mut body = json!({ "connectionId": connection.id, "database": database, "sql": sql }); + // Stateful MCP sessions pin every query to the same backend pool. + if let Some(client_session_id) = arguments.get("client_session_id").and_then(Value::as_str) { + body["clientSessionId"] = json!(client_session_id); + } + let response = self.request(reqwest::Method::POST, "/api/query/execute", Some(body)).await?; let query_result: dbx_core::db::QueryResult = response.json().await.map_err(|error| format!("Invalid query response: {error}"))?; Ok(format_query_result(&query_result, max_rows)) @@ -722,6 +753,27 @@ impl DbxBackend for WebBackend { .map_err(|error| format!("Invalid query response: {error}")) } + async fn close_client_session( + &self, + connection_id: &str, + database: &str, + client_session_id: &str, + ) -> Result { + self.request( + reqwest::Method::POST, + "/api/query/close-client-session", + Some(json!({ + "connectionId": connection_id, + "database": database, + "clientSessionId": client_session_id, + })), + ) + .await? + .json() + .await + .map_err(|error| format!("Invalid close session response: {error}")) + } + async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result { self.request(reqwest::Method::POST, "/api/connection/mcp/add", Some(json!({ "config": config }))) .await? @@ -731,15 +783,20 @@ impl DbxBackend for WebBackend { } async fn remove_connection_for_mcp(&self, connection_id: &str) -> Result { - self.request( - reqwest::Method::POST, - "/api/connection/mcp/remove", - Some(json!({ "connectionId": connection_id })), - ) - .await? - .json() - .await - .map_err(|error| format!("Invalid MCP connection response: {error}")) + let removed = self + .request( + reqwest::Method::POST, + "/api/connection/mcp/remove", + Some(json!({ "connectionId": connection_id })), + ) + .await? + .json() + .await + .map_err(|error| format!("Invalid MCP connection response: {error}"))?; + if removed { + self.connected.lock().await.remove(connection_id); + } + Ok(removed) } async fn list_tables( diff --git a/crates/dbx-mcp/src/lib.rs b/crates/dbx-mcp/src/lib.rs index fcdb719b44..96764ea9cb 100644 --- a/crates/dbx-mcp/src/lib.rs +++ b/crates/dbx-mcp/src/lib.rs @@ -1,7 +1,9 @@ pub mod backend; pub mod paths; pub mod server; +pub mod session; pub use backend::{ConnectionSummary, DbxBackend, LocalBackend, WebBackend}; pub use dbx_core::mongo_shell as mongo; pub use server::{DbxMcpServer, McpScope}; +pub use session::McpSessionStore; diff --git a/crates/dbx-mcp/src/server.rs b/crates/dbx-mcp/src/server.rs index d43b025cb7..6626be6d58 100644 --- a/crates/dbx-mcp/src/server.rs +++ b/crates/dbx-mcp/src/server.rs @@ -11,6 +11,7 @@ use uuid::Uuid; use crate::backend::{format_query_result, new_connection_config, parse_database_type, ConnectionSummary, DbxBackend}; use crate::mongo::{self, MongoCommand, MongoSafetyError}; +use crate::session::{McpSession, McpSessionStore}; use dbx_core::{ db::redis_driver::{classify_command, parse_command_argv, RedisCommandResult, RedisCommandSafety}, models::connection::DatabaseType, @@ -65,6 +66,24 @@ pub struct ExecuteQueryRequest { pub database: Option, #[schemars(description = "SQL query to execute")] pub sql: String, + #[schemars( + description = "Session ID from dbx_open_session. When set, the query runs on the session's pinned connection, preserving USE/SET and other session state across calls." + )] + pub session_id: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +pub struct OpenSessionRequest { + #[serde(flatten)] + pub selector: ConnectionSelector, + #[schemars(description = "Database name")] + pub database: Option, +} + +#[derive(Debug, Deserialize, schemars::JsonSchema)] +pub struct CloseSessionRequest { + #[schemars(description = "Session ID returned by dbx_open_session")] + pub session_id: String, } #[derive(Debug, Deserialize, schemars::JsonSchema)] @@ -132,6 +151,7 @@ pub struct ExecuteAndShowRequest { pub struct DbxMcpServer { backend: Arc, scope: McpScope, + sessions: Arc, tool_router: ToolRouter, } @@ -194,7 +214,16 @@ impl DbxMcpServer { tool_router.disable_route("dbx_open_table"); tool_router.disable_route("dbx_execute_and_show"); } - Self { backend, scope, tool_router } + Self { backend, scope, sessions: McpSessionStore::new(), tool_router } + } + + async fn close_backend_sessions_best_effort(&self, sessions: Vec) { + for session in sessions { + let _ = self + .backend + .close_client_session(&session.connection_id, &session.database, &session.client_session_id) + .await; + } } } @@ -285,10 +314,47 @@ impl DbxMcpServer { "Redis connections do not accept SQL through dbx_execute_query. Use dbx_execute_redis_command.", ); } + // Resolve the session before the database so its connection/database + // binding is enforced on every stateful query. + let session = match request.session_id.as_deref().map(str::trim).filter(|id| !id.is_empty()) { + Some(session_id) => { + let (session, expired) = self.sessions.resolve(session_id).await.into_parts(); + self.close_backend_sessions_best_effort(expired).await; + match session { + Some(session) if session.connection_id == connection.id => Some(session), + Some(_) => { + return tool_error( + "SESSION_CONNECTION_MISMATCH", + format!("Session \"{session_id}\" is bound to a different connection."), + ) + } + None => { + return tool_error( + "SESSION_NOT_FOUND", + format!( + "Session \"{session_id}\" not found or expired. Open a new one with dbx_open_session." + ), + ) + } + } + } + None => None, + }; let database = match self.resolve_database(request.database, connection) { Ok(database) => database, Err(error) => return error, }; + if let Some(session) = &session { + if session.database != database { + return tool_error( + "SESSION_DATABASE_MISMATCH", + format!( + "Session \"{}\" is bound to database \"{}\", not \"{database}\".", + session.id, session.database + ), + ); + } + } if connection.db_type == DatabaseType::MongoDb { let command = match validate_mongo_command(connection, &resolved.policy, &database, &request.sql) { Ok(command) => command, @@ -299,21 +365,82 @@ impl DbxMcpServer { Err(error) => backend_tool_error("QUERY_ERROR", error), }; } - let permissions = match validate_sql_policy(connection, &resolved.policy, &database, &request.sql) { - Ok(permissions) => permissions, + // A pinned session makes USE/SET CATALOG meaningful, so database + // switching is allowed — unless a hard database scope is configured, + // which a USE statement could otherwise escape. + let allow_database_switch = session.is_some() && self.scope.database.is_none(); + let permissions = + match validate_sql_policy(connection, &resolved.policy, &database, &request.sql, allow_database_switch) { + Ok(permissions) => permissions, + Err(error) => return error, + }; + let mut arguments = json!({ "sql": request.sql, "limit": 100 }); + if let Some(session) = &session { + arguments["client_session_id"] = json!(session.client_session_id); + } + let result = + self.backend.execute_agent_tool(connection, &database, "execute_query", arguments, permissions).await; + agent_result(result) + } + + #[tool( + name = "dbx_open_session", + description = "Open a stateful query session pinned to a single backend connection. Returns a session ID for dbx_execute_query: USE, SET CATALOG, session variables and temporary tables persist across calls within the session. Close with dbx_close_session when done; idle sessions expire after 30 minutes." + )] + async fn open_session(&self, Parameters(request): Parameters) -> CallToolResult { + let resolved = match self.resolve_connection(&request.selector).await { + Ok(resolved) => resolved, Err(error) => return error, }; - let result = self + let connection = &resolved.connection; + if matches!(connection.db_type, DatabaseType::Redis | DatabaseType::MongoDb) { + return tool_error( + "SESSION_UNSUPPORTED", + format!("Sessions are only supported for SQL connections; \"{}\" is not one.", connection.name), + ); + } + let database = match self.resolve_database(request.database, connection) { + Ok(database) => database, + Err(error) => return error, + }; + let (session, expired) = self.sessions.open(&connection.id, &database).await.into_parts(); + self.close_backend_sessions_best_effort(expired).await; + match session { + Ok(session) => text(format!( + "Session opened.\nsession_id: {}\nconnection: {} (id: {})\ndatabase: {}\n\nPass session_id to dbx_execute_query to run every query on the same pinned connection. Close with dbx_close_session when done.", + session.id, connection.name, connection.id, database + )), + Err(error) => tool_error("SESSION_LIMIT", error), + } + } + + #[tool( + name = "dbx_close_session", + description = "Close a stateful query session and release its pinned backend connection" + )] + async fn close_session(&self, Parameters(request): Parameters) -> CallToolResult { + let (session, expired) = self.sessions.begin_close(&request.session_id).await.into_parts(); + self.close_backend_sessions_best_effort(expired).await; + let Some(session) = session else { + return tool_error( + "SESSION_NOT_FOUND", + format!("Session \"{}\" not found or already closed.", request.session_id), + ); + }; + match self .backend - .execute_agent_tool( - connection, - &database, - "execute_query", - json!({ "sql": request.sql, "limit": 100 }), - permissions, - ) - .await; - agent_result(result) + .close_client_session(&session.connection_id, &session.database, &session.client_session_id) + .await + { + Ok(_) => { + self.sessions.finish_close(&session.id).await; + text(format!("Session \"{}\" closed.", session.id)) + } + Err(error) => { + self.sessions.restore_after_failed_close(session).await; + backend_tool_error("SESSION_CLOSE_ERROR", error) + } + } } #[tool(name = "dbx_execute_redis_command", description = "Execute a Redis command on a Redis connection")] @@ -570,7 +697,7 @@ impl DbxMcpServer { let permissions = if connection.db_type == DatabaseType::MongoDb { mcp_permissions(connection, &resolved.policy) } else { - match validate_sql_policy(connection, &resolved.policy, &database, &request.sql) { + match validate_sql_policy(connection, &resolved.policy, &database, &request.sql, false) { Ok(permissions) => permissions, Err(error) => return error, } @@ -817,9 +944,13 @@ fn validate_sql_policy( policy: &McpGlobalPolicy, database: &str, sql: &str, + allow_database_switch: bool, ) -> Result { - if mcp_sql_has_forbidden_database_switch(sql, connection.db_type) { - return Err(tool_error("SQL_BLOCKED", "MCP does not allow USE or persistent database switching.")); + if !allow_database_switch && mcp_sql_has_forbidden_database_switch(sql, connection.db_type) { + return Err(tool_error( + "SQL_BLOCKED", + "MCP does not allow USE or persistent database switching outside a session. Open one with dbx_open_session to run stateful queries.", + )); } let risk = classify_sql_risk_for_database(sql, connection.db_type).map_err(|error| tool_error("SQL_BLOCKED", error))?; @@ -1051,9 +1182,26 @@ mod tests { use super::*; use async_trait::async_trait; use dbx_core::models::connection::ConnectionConfig; + use std::collections::HashSet; struct FakeBackend { connections: Vec, + recorded_arguments: std::sync::Mutex>, + closed_sessions: std::sync::Mutex>, + pinned_sessions: std::sync::Mutex>, + close_failures_remaining: std::sync::Mutex, + } + + impl Default for FakeBackend { + fn default() -> Self { + Self { + connections: Vec::new(), + recorded_arguments: std::sync::Mutex::new(Vec::new()), + closed_sessions: std::sync::Mutex::new(Vec::new()), + pinned_sessions: std::sync::Mutex::new(HashSet::new()), + close_failures_remaining: std::sync::Mutex::new(0), + } + } } fn connection(id: &str, name: &str, db_type: &str, database: &str) -> ConnectionConfig { @@ -1075,6 +1223,14 @@ mod tests { result.content[0].as_text().expect("text tool result").text.as_str() } + fn opened_session_id(result: &CallToolResult) -> String { + result_text(result) + .lines() + .find_map(|line| line.strip_prefix("session_id: ")) + .expect("open_session returns a session_id") + .to_string() + } + #[async_trait] impl DbxBackend for FakeBackend { async fn load_mcp_global_policy(&self) -> Result { @@ -1090,9 +1246,15 @@ mod tests { _connection: &ConnectionConfig, _database: &str, tool_name: &str, - _arguments: serde_json::Value, + arguments: serde_json::Value, _permissions: dbx_core::agent_tools::AgentSqlPermissions, ) -> dbx_core::agent_events::ToolResult { + if let Some(client_session_id) = + arguments.get("client_session_id").and_then(serde_json::Value::as_str).filter(|id| !id.is_empty()) + { + self.pinned_sessions.lock().unwrap().insert(client_session_id.to_string()); + } + self.recorded_arguments.lock().unwrap().push((tool_name.to_string(), arguments)); dbx_core::agent_events::ToolResult { tool_call_id: "test".to_string(), tool_name: tool_name.to_string(), @@ -1102,6 +1264,23 @@ mod tests { } } + async fn close_client_session( + &self, + _connection_id: &str, + _database: &str, + client_session_id: &str, + ) -> Result { + let mut failures = self.close_failures_remaining.lock().unwrap(); + if *failures > 0 { + *failures -= 1; + return Err("temporary close failure".to_string()); + } + drop(failures); + self.closed_sessions.lock().unwrap().push(client_session_id.to_string()); + self.pinned_sessions.lock().unwrap().remove(client_session_id); + Ok(true) + } + async fn add_connection_for_mcp(&self, config: ConnectionConfig) -> Result { Ok(config) } @@ -1127,14 +1306,10 @@ mod tests { #[test] fn server_registers_list_connections_tool() { - let server = DbxMcpServer::with_runtime_options( - Arc::new(FakeBackend { connections: Vec::new() }), - McpScope::default(), - false, - ); + let server = DbxMcpServer::with_runtime_options(Arc::new(FakeBackend::default()), McpScope::default(), false); let tools = server.tool_router.list_all(); let names = tools.iter().map(|tool| tool.name.as_ref()).collect::>(); - assert_eq!(tools.len(), 10); + assert_eq!(tools.len(), 12); assert!(names.contains(&"dbx_list_connections")); assert!(names.contains(&"dbx_list_tables")); assert!(names.contains(&"dbx_describe_table")); @@ -1145,21 +1320,25 @@ mod tests { assert!(names.contains(&"dbx_get_schema_context")); assert!(names.contains(&"dbx_open_table")); assert!(names.contains(&"dbx_execute_and_show")); + assert!(names.contains(&"dbx_open_session")); + assert!(names.contains(&"dbx_close_session")); } #[test] fn scoped_server_hides_mutating_and_desktop_tools() { let server = DbxMcpServer::with_runtime_options( - Arc::new(FakeBackend { connections: Vec::new() }), + Arc::new(FakeBackend::default()), McpScope { connection_ids: vec!["scoped".to_string()], ..Default::default() }, false, ); let names = server.tool_router.list_all().into_iter().map(|tool| tool.name).collect::>(); - assert_eq!(names.len(), 6); + assert_eq!(names.len(), 8); assert!(!names.iter().any(|name| name == "dbx_add_connection")); assert!(!names.iter().any(|name| name == "dbx_remove_connection")); assert!(!names.iter().any(|name| name == "dbx_open_table")); assert!(!names.iter().any(|name| name == "dbx_execute_and_show")); + assert!(names.iter().any(|name| name == "dbx_open_session")); + assert!(names.iter().any(|name| name == "dbx_close_session")); } #[test] @@ -1182,7 +1361,7 @@ mod tests { async fn database_scope_is_a_hard_bound_without_filtering_connections() { let scoped = connection("scoped", "scoped", "postgres", "configured"); let server = DbxMcpServer::with_runtime_options( - Arc::new(FakeBackend { connections: vec![scoped.clone()] }), + Arc::new(FakeBackend { connections: vec![scoped.clone()], ..Default::default() }), McpScope { database: Some("analytics".to_string()), ..Default::default() }, false, ); @@ -1202,7 +1381,7 @@ mod tests { fn redis_database_scope_fails_closed_and_cannot_be_overridden() { let redis = connection("redis", "redis", "redis", "1"); let scoped = DbxMcpServer::with_runtime_options( - Arc::new(FakeBackend { connections: vec![redis.clone()] }), + Arc::new(FakeBackend { connections: vec![redis.clone()], ..Default::default() }), McpScope { database: Some("2".to_string()), ..Default::default() }, false, ); @@ -1211,7 +1390,7 @@ mod tests { assert!(result_text(&error).contains("DATABASE_OUT_OF_SCOPE")); let invalid = DbxMcpServer::with_runtime_options( - Arc::new(FakeBackend { connections: vec![redis.clone()] }), + Arc::new(FakeBackend { connections: vec![redis.clone()], ..Default::default() }), McpScope { database: Some("analytics".to_string()), ..Default::default() }, false, ); @@ -1263,13 +1442,13 @@ mod tests { let writable_policy = McpGlobalPolicy { read_only: false, allow_dangerous_sql: true, allowed_connection_ids: None }; let read_only_error = - validate_sql_policy(&read_only, &writable_policy, "app", "DELETE FROM sessions").unwrap_err(); + validate_sql_policy(&read_only, &writable_policy, "app", "DELETE FROM sessions", false).unwrap_err(); assert!(result_text(&read_only_error).contains("CONNECTION_READ_ONLY")); let mut production = connection("production", "production", "postgres", "app"); production.production_databases = vec!["app".to_string()]; let production_error = - validate_sql_policy(&production, &writable_policy, "app", "DROP TABLE sessions").unwrap_err(); + validate_sql_policy(&production, &writable_policy, "app", "DROP TABLE sessions", false).unwrap_err(); assert!(result_text(&production_error).contains("PRODUCTION_WRITE_BLOCKED")); } @@ -1317,7 +1496,8 @@ mod tests { assert_eq!(permissions.confirmed_write_sql.as_deref(), Some("CREATE TABLE metrics (id INT)")); // 2. SQL path (validate_sql_policy) elevates allow_dangerous with a confirmed binding. - let permissions = validate_sql_policy(&connection, &policy, "app", "CREATE TABLE metrics (id INT)").unwrap(); + let permissions = + validate_sql_policy(&connection, &policy, "app", "CREATE TABLE metrics (id INT)", false).unwrap(); assert!(permissions.allow_dangerous, "SQL path should elevate allow_dangerous with confirmed binding"); assert!(permissions.allow_writes); assert_eq!(permissions.confirmed_write_sql.as_deref(), Some("CREATE TABLE metrics (id INT)")); @@ -1325,7 +1505,7 @@ mod tests { // 3. Without a confirmed binding, high-risk SQL is blocked. let _guard = EnvGuard::remove("DBX_MCP_CONFIRMED_WRITE_SQL"); - let error = validate_sql_policy(&connection, &policy, "app", "DROP TABLE sessions").unwrap_err(); + let error = validate_sql_policy(&connection, &policy, "app", "DROP TABLE sessions", false).unwrap_err(); assert!(result_text(&error).contains("SQL_BLOCKED")); assert!(result_text(&error).contains("High-risk SQL is disabled")); drop(_guard); @@ -1334,8 +1514,184 @@ mod tests { let _guard = EnvGuard::set("DBX_MCP_CONFIRMED_WRITE_SQL", "CREATE TABLE metrics (id INT)"); let read_only_policy = McpGlobalPolicy { read_only: true, allow_dangerous_sql: false, allowed_connection_ids: None }; - let error = - validate_sql_policy(&connection, &read_only_policy, "app", "CREATE TABLE metrics (id INT)").unwrap_err(); + let error = validate_sql_policy(&connection, &read_only_policy, "app", "CREATE TABLE metrics (id INT)", false) + .unwrap_err(); assert!(result_text(&error).contains("MCP_READ_ONLY"), "confirmed SQL must not bypass global read_only"); } + + #[test] + fn use_statements_require_a_session() { + let starrocks = connection("sr", "sr", "starrocks", "default_catalog"); + let policy = McpGlobalPolicy { read_only: false, allow_dangerous_sql: false, allowed_connection_ids: None }; + + let blocked = validate_sql_policy(&starrocks, &policy, "default_catalog", "USE analytics", false).unwrap_err(); + assert!(result_text(&blocked).contains("SQL_BLOCKED")); + assert!(result_text(&blocked).contains("dbx_open_session")); + + // Inside a pinned session, USE is meaningful and passes policy checks. + assert!(validate_sql_policy(&starrocks, &policy, "default_catalog", "USE analytics", true).is_ok()); + } + + fn selector(id: &str) -> ConnectionSelector { + ConnectionSelector { connection_id: Some(id.to_string()), connection_name: None } + } + + #[tokio::test] + async fn session_queries_pin_client_session_and_close_releases_pool() { + let starrocks = connection("sr", "sr", "starrocks", "default_catalog"); + let backend = Arc::new(FakeBackend { connections: vec![starrocks], ..Default::default() }); + let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false); + + let opened = + server.open_session(Parameters(OpenSessionRequest { selector: selector("sr"), database: None })).await; + let session_id = opened_session_id(&opened); + + // A USE statement is allowed inside the session and runs with the + // session's pinned client_session_id. + let result = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: None, + sql: "USE analytics".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert_eq!(result_text(&result), "ok"); + let pinned_client_session = { + let recorded = backend.recorded_arguments.lock().unwrap(); + let (_, arguments) = recorded.iter().find(|(name, _)| name == "execute_query").unwrap(); + arguments["client_session_id"].as_str().unwrap().to_string() + }; + assert_eq!(pinned_client_session, format!("mcp:{session_id}")); + + // Queries bound to another database are rejected. + let mismatch = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: Some("other".to_string()), + sql: "SELECT 1".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert!(result_text(&mismatch).contains("SESSION_DATABASE_MISMATCH")); + + let closed = server.close_session(Parameters(CloseSessionRequest { session_id: session_id.clone() })).await; + assert!(result_text(&closed).contains("closed")); + assert_eq!(backend.closed_sessions.lock().unwrap().as_slice(), [format!("mcp:{session_id}")]); + + // The session is gone: further queries fail instead of silently + // falling back to an unpinned connection. + let missing = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: None, + sql: "SELECT 1".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert!(result_text(&missing).contains("SESSION_NOT_FOUND")); + + let second_close = server.close_session(Parameters(CloseSessionRequest { session_id })).await; + assert!(result_text(&second_close).contains("SESSION_NOT_FOUND")); + } + + #[tokio::test] + async fn expired_sessions_close_backend_pools_without_accumulating() { + let starrocks = connection("sr", "sr", "starrocks", "default_catalog"); + let backend = Arc::new(FakeBackend { connections: vec![starrocks], ..Default::default() }); + let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false); + let mut expired_client_session_ids = Vec::new(); + + for _ in 0..3 { + let opened = + server.open_session(Parameters(OpenSessionRequest { selector: selector("sr"), database: None })).await; + let session_id = opened_session_id(&opened); + let result = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: None, + sql: "SELECT 1".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert_eq!(result_text(&result), "ok"); + assert_eq!(backend.pinned_sessions.lock().unwrap().len(), 1); + + server.sessions.expire_for_test(&session_id).await; + expired_client_session_ids.push(format!("mcp:{session_id}")); + } + + let opened = + server.open_session(Parameters(OpenSessionRequest { selector: selector("sr"), database: None })).await; + let final_session_id = opened_session_id(&opened); + assert!(backend.pinned_sessions.lock().unwrap().is_empty()); + assert_eq!(backend.closed_sessions.lock().unwrap().as_slice(), expired_client_session_ids.as_slice()); + + let closed = server.close_session(Parameters(CloseSessionRequest { session_id: final_session_id })).await; + assert!(result_text(&closed).contains("closed")); + } + + #[tokio::test] + async fn failed_session_close_can_be_retried() { + let starrocks = connection("sr", "sr", "starrocks", "default_catalog"); + let backend = Arc::new(FakeBackend { connections: vec![starrocks], ..Default::default() }); + *backend.close_failures_remaining.lock().unwrap() = 1; + let server = DbxMcpServer::with_runtime_options(backend.clone(), McpScope::default(), false); + + let opened = + server.open_session(Parameters(OpenSessionRequest { selector: selector("sr"), database: None })).await; + let session_id = opened_session_id(&opened); + let query = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: None, + sql: "SELECT 1".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert_eq!(result_text(&query), "ok"); + + let failed = server.close_session(Parameters(CloseSessionRequest { session_id: session_id.clone() })).await; + assert!(result_text(&failed).contains("SESSION_CLOSE_ERROR")); + assert_eq!(backend.pinned_sessions.lock().unwrap().len(), 1); + + let retry_query = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("sr"), + database: None, + sql: "SELECT 1".to_string(), + session_id: Some(session_id.clone()), + })) + .await; + assert_eq!(result_text(&retry_query), "ok"); + + let closed = server.close_session(Parameters(CloseSessionRequest { session_id })).await; + assert!(result_text(&closed).contains("closed")); + assert!(backend.pinned_sessions.lock().unwrap().is_empty()); + assert_eq!(backend.closed_sessions.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn open_session_rejects_non_sql_connections_and_unknown_sessions_fail_closed() { + let redis = connection("redis", "redis", "redis", "0"); + let pg = connection("pg", "pg", "postgres", "app"); + let server = DbxMcpServer::with_runtime_options( + Arc::new(FakeBackend { connections: vec![redis, pg], ..Default::default() }), + McpScope::default(), + false, + ); + let rejected = + server.open_session(Parameters(OpenSessionRequest { selector: selector("redis"), database: None })).await; + assert!(result_text(&rejected).contains("SESSION_UNSUPPORTED")); + + let missing = server + .execute_query(Parameters(ExecuteQueryRequest { + selector: selector("pg"), + database: None, + sql: "SELECT 1".to_string(), + session_id: Some("mcp-session-nope".to_string()), + })) + .await; + assert!(result_text(&missing).contains("SESSION_NOT_FOUND")); + } } diff --git a/crates/dbx-mcp/src/session.rs b/crates/dbx-mcp/src/session.rs new file mode 100644 index 0000000000..65c3cbac89 --- /dev/null +++ b/crates/dbx-mcp/src/session.rs @@ -0,0 +1,208 @@ +use std::collections::HashMap; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use tokio::sync::Mutex; +use uuid::Uuid; + +/// Idle time after which an MCP session is considered expired and its pinned +/// backend connection pool may be reclaimed. +const SESSION_IDLE_TTL: Duration = Duration::from_secs(30 * 60); + +/// Maximum number of concurrent MCP sessions. Bounds how many pinned backend +/// connection pools an agent can hold at once. +const MAX_SESSIONS: usize = 32; + +#[derive(Debug, Clone)] +pub struct McpSession { + /// Opaque handle returned to the MCP client (`dbx_open_session` result). + pub id: String, + pub connection_id: String, + pub database: String, + /// Value forwarded to the backend as `client_session_id`, pinning all + /// queries in this session to the same connection pool. + pub client_session_id: String, + last_used: Instant, +} + +#[must_use = "expired MCP sessions must be closed by the caller"] +pub struct McpSessionStoreResult { + value: T, + expired: Vec, +} + +impl McpSessionStoreResult { + fn new(value: T, expired: Vec) -> Self { + Self { value, expired } + } + + pub fn into_parts(self) -> (T, Vec) { + (self.value, self.expired) + } +} + +#[derive(Default)] +struct McpSessionState { + active: HashMap, + closing: HashMap, +} + +#[derive(Default)] +pub struct McpSessionStore { + state: Mutex, +} + +impl McpSessionStore { + pub fn new() -> Arc { + Arc::new(Self::default()) + } + + /// Open a new session bound to `connection_id` + `database`. + /// + /// Returns `Err` with a human-readable message when the session cap is + /// reached; expired sessions are swept before the cap is enforced. + pub async fn open(&self, connection_id: &str, database: &str) -> McpSessionStoreResult> { + let mut state = self.state.lock().await; + let expired = sweep_expired(&mut state.active); + if state.active.len() + state.closing.len() >= MAX_SESSIONS { + return McpSessionStoreResult::new( + Err(format!( + "Too many open MCP sessions (max {MAX_SESSIONS}). Close unused sessions with dbx_close_session." + )), + expired, + ); + } + let id = format!("mcp-session-{}", Uuid::new_v4()); + let session = McpSession { + id: id.clone(), + connection_id: connection_id.to_string(), + database: database.to_string(), + // Prefixed so these pools are easy to distinguish from desktop UI + // sessions in backend diagnostics. `:` is normalized away by the + // backend pool key sanitizer. + client_session_id: format!("mcp:{id}"), + last_used: Instant::now(), + }; + state.active.insert(id, session.clone()); + McpSessionStoreResult::new(Ok(session), expired) + } + + /// Resolve a session id and refresh its idle timer. + pub async fn resolve(&self, session_id: &str) -> McpSessionStoreResult> { + let mut state = self.state.lock().await; + let expired = sweep_expired(&mut state.active); + let session = state.active.get_mut(session_id).map(|session| { + session.last_used = Instant::now(); + session.clone() + }); + McpSessionStoreResult::new(session, expired) + } + + /// Reserve a session for closing. It remains counted against the session + /// cap until the backend pool is closed successfully. + pub async fn begin_close(&self, session_id: &str) -> McpSessionStoreResult> { + let mut state = self.state.lock().await; + let expired = sweep_expired(&mut state.active); + let session = state.active.remove(session_id); + if let Some(session) = &session { + state.closing.insert(session.id.clone(), session.clone()); + } + McpSessionStoreResult::new(session, expired) + } + + pub async fn finish_close(&self, session_id: &str) { + self.state.lock().await.closing.remove(session_id); + } + + pub async fn restore_after_failed_close(&self, mut session: McpSession) { + let mut state = self.state.lock().await; + if state.closing.remove(&session.id).is_some() { + session.last_used = Instant::now(); + state.active.insert(session.id.clone(), session); + } + } + + #[cfg(test)] + pub(crate) async fn expire_for_test(&self, session_id: &str) { + self.state.lock().await.active.get_mut(session_id).unwrap().last_used = + Instant::now() - SESSION_IDLE_TTL - Duration::from_secs(1); + } +} + +fn sweep_expired(sessions: &mut HashMap) -> Vec { + let now = Instant::now(); + let mut expired = Vec::new(); + sessions.retain(|_, session| { + let active = now.duration_since(session.last_used) < SESSION_IDLE_TTL; + if !active { + expired.push(session.clone()); + } + active + }); + expired +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn open_resolve_and_remove_roundtrip() { + let store = McpSessionStore::new(); + let (session, expired) = store.open("conn-1", "analytics").await.into_parts(); + assert!(expired.is_empty()); + let session = session.unwrap(); + assert!(session.id.starts_with("mcp-session-")); + assert!(session.client_session_id.contains(&session.id)); + + let (resolved, expired) = store.resolve(&session.id).await.into_parts(); + assert!(expired.is_empty()); + let resolved = resolved.unwrap(); + assert_eq!(resolved.connection_id, "conn-1"); + assert_eq!(resolved.database, "analytics"); + + let (closing, expired) = store.begin_close(&session.id).await.into_parts(); + assert!(expired.is_empty()); + assert_eq!(closing.unwrap().id, session.id); + assert!(store.resolve(&session.id).await.into_parts().0.is_none()); + store.finish_close(&session.id).await; + assert!(store.begin_close(&session.id).await.into_parts().0.is_none()); + } + + #[tokio::test] + async fn session_cap_is_enforced() { + let store = McpSessionStore::new(); + for _ in 0..MAX_SESSIONS { + store.open("conn-1", "").await.into_parts().0.unwrap(); + } + let error = store.open("conn-1", "").await.into_parts().0.unwrap_err(); + assert!(error.contains("Too many open MCP sessions")); + } + + #[tokio::test] + async fn expired_sessions_are_swept_and_free_capacity() { + let store = McpSessionStore::new(); + let mut session_ids = Vec::new(); + for _ in 0..MAX_SESSIONS { + let session = store.open("conn-1", "").await.into_parts().0.unwrap(); + session_ids.push(session.id); + } + for session_id in &session_ids { + store.expire_for_test(session_id).await; + } + // All sessions are expired: the sweep must reclaim them before the cap + // check, return them for backend cleanup, and allow a new session. + let (opened, expired) = store.open("conn-1", "").await.into_parts(); + opened.unwrap(); + assert_eq!(expired.len(), MAX_SESSIONS); + + // Resolving an expired session must fail instead of silently pinning a + // fresh backend connection. + let session = store.open("conn-1", "").await.into_parts().0.unwrap(); + store.expire_for_test(&session.id).await; + let (resolved, expired) = store.resolve(&session.id).await.into_parts(); + assert!(resolved.is_none()); + assert_eq!(expired.len(), 1); + assert_eq!(expired[0].id, session.id); + } +} diff --git a/crates/dbx-mcp/tests/protocol.rs b/crates/dbx-mcp/tests/protocol.rs index 0ecda6756a..8f81079672 100644 --- a/crates/dbx-mcp/tests/protocol.rs +++ b/crates/dbx-mcp/tests/protocol.rs @@ -112,10 +112,12 @@ async fn initializes_lists_tools_and_calls_a_tool() { let tools = client.peer().list_tools(None).await.expect("list tools"); let names = tools.tools.iter().map(|tool| tool.name.as_ref()).collect::>(); - assert_eq!(names.len(), 10); + assert_eq!(names.len(), 12); assert!(names.contains(&"dbx_list_connections")); assert!(names.contains(&"dbx_execute_redis_command")); assert!(names.contains(&"dbx_execute_and_show")); + assert!(names.contains(&"dbx_open_session")); + assert!(names.contains(&"dbx_close_session")); let result = client.peer().call_tool(CallToolRequestParams::new("dbx_list_connections")).await.expect("call tool"); let response = result.content[0].as_text().expect("text response"); diff --git a/crates/dbx-web/src/routes/mcp_policy.rs b/crates/dbx-web/src/routes/mcp_policy.rs index f5f65e0b1f..56e6bfcb62 100644 --- a/crates/dbx-web/src/routes/mcp_policy.rs +++ b/crates/dbx-web/src/routes/mcp_policy.rs @@ -344,6 +344,7 @@ pub async fn ensure_sql( connection_id: &str, database: &str, sql: &str, + allow_database_switch: bool, ) -> Result<(), AppError> { if !is_mcp_request(headers) { return Ok(()); @@ -351,7 +352,7 @@ pub async fn ensure_sql( let policy = load_policy(state).await?; ensure_allowed(&policy, connection_id)?; let config = load_connection(state, connection_id).await?; - if dbx_core::sql_risk::mcp_sql_has_forbidden_database_switch(sql, config.db_type) { + if !allow_database_switch && dbx_core::sql_risk::mcp_sql_has_forbidden_database_switch(sql, config.db_type) { return Err(AppError::from( "SQL_BLOCKED: MCP does not allow USE or persistent database switching.".to_string(), )); diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rs index 00beeb41d1..bba1c7e6ce 100644 --- a/crates/dbx-web/src/routes/query.rs +++ b/crates/dbx-web/src/routes/query.rs @@ -331,7 +331,9 @@ pub async fn execute_query( headers: HeaderMap, Json(req): Json, ) -> Result, AppError> { - super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql).await?; + let allow_database_switch = req.client_session_id.as_deref().is_some_and(|id| !id.trim().is_empty()); + super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql, allow_database_switch) + .await?; let execution_id = req.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let registered = state.app.running_queries.register_task( @@ -375,7 +377,9 @@ pub async fn execute_multi( headers: HeaderMap, Json(req): Json, ) -> Result>, AppError> { - super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql).await?; + let allow_database_switch = req.client_session_id.as_deref().is_some_and(|id| !id.trim().is_empty()); + super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, &req.sql, allow_database_switch) + .await?; let execution_id = req.execution_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); let registered = state.app.running_queries.register_task( @@ -420,7 +424,7 @@ pub async fn execute_batch( Json(req): Json, ) -> Result, AppError> { for statement in &req.statements { - super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, statement).await?; + super::mcp_policy::ensure_sql(&state, &headers, &req.connection_id, &req.database, statement, false).await?; } tracing::debug!(connection_id = %req.connection_id, "execute_batch"); let result = dbx_core::query::execute_statements(