feat(mcp): add global query timeout override

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-08-30 12:26:54 +08:00
1 parent 7ba30ae761
commit e6f8b2187a
24 files changed
+615 -35

No files matched your search

+93 -4
View File
@@ -2,11 +2,13 @@ use std::collections::HashMap;
use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};
use serde_json::json;
use serde_json::Value;
use crate::agent_events::{ToolCall, ToolDefinition, ToolResult};
use crate::connection::AppState;
use crate::db::vector_driver;
use crate::models::connection::DatabaseType;
use crate::models::connection::{ConnectionConfig, SPANNER_MIN_QUERY_TIMEOUT_SECS};
use crate::query::QueryExecutionOptions;
use crate::query_execution_sql::{build_explain_sql, supports_explain_plan, supports_sql_query, ExplainSqlOptions};
use crate::sql_dialect::{build_table_data_select_sql, TableDataSelectSqlOptions};
@@ -63,6 +65,33 @@ fn tool_uses_database(tool_name: &str) -> bool {
)
}
/// Resolve the query timeout (seconds) for an agent/MCP query.
///
/// Precedence: an explicit per-call `requested` value wins; otherwise inherit
/// the connection's `effective_query_timeout_secs()`; the legacy 30s survives
/// only when no connection config is available to resolve against. `Some(0)`
/// from either source means "no limit" (unlimited, and it bypasses the Spanner
/// floor — see `ConnectionConfig::effective_query_timeout_secs`). A finite
/// value on a Spanner connection gets the 120s floor.
pub fn agent_query_timeout_secs(requested: Option<u64>, connection: Option<&ConnectionConfig>) -> u64 {
match requested {
Some(0) => 0,
Some(n) => {
if connection.is_some_and(|config| config.db_type == DatabaseType::Spanner) {
n.max(SPANNER_MIN_QUERY_TIMEOUT_SECS)
} else {
n
}
}
None => connection.map_or(QUERY_TIMEOUT_SECS, ConnectionConfig::effective_query_timeout_secs),
}
}
/// Legacy fallback query timeout for agent queries. Matches the current fixed
/// `Some(30)` behavior and remains the last resort when no connection config
/// can be resolved (that path fails the query at pool lookup anyway).
const QUERY_TIMEOUT_SECS: u64 = 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryCellWindow {
offset: usize,
@@ -833,10 +862,16 @@ async fn execute_execute_query(
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
// Execute query using existing infrastructure. Timeout resolves as
// per-call `timeout_secs` > connection effective timeout (see
// `agent_query_timeout_secs`); MCP injects the policy value as
// `timeout_secs` in the arguments.
let options = QueryExecutionOptions {
max_rows: Some(limit),
timeout_secs: Some(30),
timeout_secs: Some(agent_query_timeout_secs(
tool_call.arguments.get("timeout_secs").and_then(Value::as_u64),
connection_config.as_ref(),
)),
client_session_id: client_session_id.map(str::to_string),
..Default::default()
};
@@ -1085,8 +1120,18 @@ async fn execute_explain_query(
}
};
// Execute the EXPLAIN query
let options = QueryExecutionOptions { max_rows: Some(100), timeout_secs: Some(30), ..Default::default() };
// Execute the EXPLAIN query. Timeout resolves like the execute path
// (per-call `timeout_secs` > connection effective timeout) so the global
// MCP timeout override covers EXPLAIN too.
let connection_config = state.configs.read().await.get(connection_id).cloned();
let options = QueryExecutionOptions {
max_rows: Some(100),
timeout_secs: Some(agent_query_timeout_secs(
tool_call.arguments.get("timeout_secs").and_then(Value::as_u64),
connection_config.as_ref(),
)),
..Default::default()
};
let result = match crate::query::execute_sql_statement_with_options(
state,
connection_id,
@@ -1280,6 +1325,50 @@ async fn resolve_chroma_collection_uuid(
mod tests {
use super::*;
#[test]
fn agent_query_timeout_resolves_by_precedence() {
// Explicit per-call value wins.
assert_eq!(agent_query_timeout_secs(Some(45), Some(&postgres_connection(60))), 45);
// 0 = unlimited bypasses the Spanner floor.
assert_eq!(agent_query_timeout_secs(Some(0), Some(&spanner_connection(60))), 0);
// Finite value on Spanner gets the 120s floor.
assert_eq!(agent_query_timeout_secs(Some(60), Some(&spanner_connection(60))), 120);
// No request + connection => inherit the connection's effective timeout.
assert_eq!(agent_query_timeout_secs(None, Some(&postgres_connection(60))), 60);
assert_eq!(agent_query_timeout_secs(None, Some(&postgres_connection(120))), 120);
assert_eq!(agent_query_timeout_secs(None, Some(&postgres_connection(0))), 0);
// No request, no connection => legacy 30s fallback.
assert_eq!(agent_query_timeout_secs(None, None), 30);
}
fn postgres_connection(query_timeout_secs: u64) -> ConnectionConfig {
let mut config = test_connection();
config.db_type = DatabaseType::Postgres;
config.query_timeout_secs = query_timeout_secs;
config
}
fn spanner_connection(query_timeout_secs: u64) -> ConnectionConfig {
let mut config = test_connection();
config.db_type = DatabaseType::Spanner;
config.query_timeout_secs = query_timeout_secs;
config
}
fn test_connection() -> ConnectionConfig {
serde_json::from_value(json!({
"id": "agent-timeout-test",
"name": "timeout-test",
"db_type": "postgres",
"host": "127.0.0.1",
"port": 5432,
"username": "",
"password": "",
"ssl": false,
}))
.expect("test connection config")
}
#[tokio::test]
async fn database_tool_locks_are_connection_scoped_and_cancel_safe() {
let first = connection_tool_lock("agent-tool-lock-a").lock_owned().await;
+10 -10
View File
@@ -463,6 +463,15 @@ pub fn default_connect_timeout_secs() -> u64 {
10
}
/// Cloud Spanner schema changes are long-running operations rather than plain
/// statements. Measured against the real service, `CREATE INDEX` on an *empty*
/// table took 22.9-33.6s over seven runs, so the generic default fails
/// intermittently — and the failure is misleading, because the operation keeps
/// running server-side and completes, leaving a retry to report
/// `Duplicate name in schema`. Raising a floor mirrors what
/// `connection::agent_connect_timeout` already does for Access.
pub const SPANNER_MIN_QUERY_TIMEOUT_SECS: u64 = 120;
pub fn default_query_timeout_secs() -> u64 {
60
}
@@ -824,21 +833,12 @@ impl ConnectionConfig {
}
}
/// Cloud Spanner schema changes are long-running operations rather than plain
/// statements. Measured against the real service, `CREATE INDEX` on an *empty*
/// table took 22.9-33.6s over seven runs, so the generic default fails
/// intermittently — and the failure is misleading, because the operation keeps
/// running server-side and completes, leaving a retry to report
/// `Duplicate name in schema`. Raising a floor mirrors what
/// `connection::agent_connect_timeout` already does for Access.
const SPANNER_MIN_QUERY_TIMEOUT_SECS: u64 = 120;
pub fn effective_query_timeout_secs(&self) -> u64 {
if self.query_timeout_secs == 0 {
// An explicit 0 is the UI's "no limit"; a floor must not impose one.
return 0;
}
let floor = if self.db_type == DatabaseType::Spanner { Self::SPANNER_MIN_QUERY_TIMEOUT_SECS } else { 1 };
let floor = if self.db_type == DatabaseType::Spanner { SPANNER_MIN_QUERY_TIMEOUT_SECS } else { 1 };
self.query_timeout_secs.max(floor)
}
+15
View File
@@ -224,6 +224,8 @@ pub struct McpGlobalPolicy {
#[serde(default)]
pub allow_dangerous_sql: bool,
pub allowed_connection_ids: Option<Vec<String>>,
#[serde(default)]
pub query_timeout_secs: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
@@ -233,6 +235,8 @@ pub struct McpGlobalPolicyState {
pub read_only: bool,
pub allow_dangerous_sql: bool,
pub allowed_connection_ids: Option<Vec<String>>,
#[serde(default)]
pub query_timeout_secs: Option<u64>,
}
impl McpGlobalPolicyState {
@@ -241,6 +245,7 @@ impl McpGlobalPolicyState {
read_only: self.read_only,
allow_dangerous_sql: self.allow_dangerous_sql,
allowed_connection_ids: self.allowed_connection_ids.clone(),
query_timeout_secs: self.query_timeout_secs,
}
}
}
@@ -1639,6 +1644,7 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
allowed_connection_ids: policy.allowed_connection_ids,
query_timeout_secs: policy.query_timeout_secs,
});
};
let settings = serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(&json)
@@ -1650,6 +1656,7 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
allowed_connection_ids: policy.allowed_connection_ids,
query_timeout_secs: policy.query_timeout_secs,
});
};
let policy = serde_json::from_value::<McpGlobalPolicy>(value.clone())
@@ -1659,6 +1666,7 @@ impl Storage {
read_only: policy.read_only,
allow_dangerous_sql: policy.allow_dangerous_sql,
allowed_connection_ids: policy.allowed_connection_ids,
query_timeout_secs: policy.query_timeout_secs,
})
})
.await;
@@ -6020,6 +6028,7 @@ mod tests {
read_only: false,
allow_dangerous_sql: false,
allowed_connection_ids: None,
query_timeout_secs: None,
}
);
@@ -6029,6 +6038,7 @@ mod tests {
read_only: true,
allow_dangerous_sql: true,
allowed_connection_ids: Some(vec!["conn-1".to_string(), "conn-2".to_string()]),
query_timeout_secs: Some(120),
})
.await
.unwrap();
@@ -6040,6 +6050,7 @@ mod tests {
read_only: true,
allow_dangerous_sql: true,
allowed_connection_ids: Some(vec!["conn-1".to_string(), "conn-2".to_string()]),
query_timeout_secs: Some(120),
}
);
assert_eq!(storage.load_password_hash().await.unwrap().as_deref(), Some("preserved"));
@@ -6047,6 +6058,7 @@ mod tests {
assert_eq!(settings[MCP_GLOBAL_POLICY_KEY]["readOnly"], true);
assert_eq!(settings[MCP_GLOBAL_POLICY_KEY]["allowDangerousSql"], true);
assert_eq!(settings[MCP_GLOBAL_POLICY_KEY]["allowedConnectionIds"][0], "conn-1");
assert_eq!(settings[MCP_GLOBAL_POLICY_KEY]["queryTimeoutSecs"], 120);
assert!(settings[MCP_GLOBAL_POLICY_KEY].get("configured").is_none());
storage.save_desktop_settings(&DesktopSettings::default()).await.unwrap();
@@ -6119,6 +6131,7 @@ mod tests {
let policy = storage.load_mcp_global_policy().await.unwrap();
assert!(policy.configured);
assert!(!policy.allow_dangerous_sql);
assert_eq!(policy.query_timeout_secs, None);
}
#[tokio::test]
@@ -6134,6 +6147,7 @@ mod tests {
read_only: false,
allow_dangerous_sql: false,
allowed_connection_ids: Some(vec![kept.id.clone()]),
query_timeout_secs: None,
})
.await
.unwrap();
@@ -6157,6 +6171,7 @@ mod tests {
read_only: true,
allow_dangerous_sql: false,
allowed_connection_ids: None,
query_timeout_secs: None,
})
.await
.unwrap();