feat(mcp): add streamable http server and fine-grained authorization
This commit is contained in:
47 files changed
+4960
-509
No files matched your search
@@ -36,6 +36,7 @@ const APP_STATE_OPEN_TABS_KEY: &str = "open_tabs";
|
||||
const APP_STATE_SAVED_SQL_EDITOR_POSITIONS_KEY: &str = "saved_sql_editor_positions";
|
||||
const APP_STATE_TRANSFER_TASK_LIBRARY_KEY: &str = "transfer_task_library";
|
||||
const MCP_GLOBAL_POLICY_KEY: &str = "mcp_global_policy";
|
||||
const MCP_HTTP_SERVER_SETTINGS_KEY: &str = "mcp_http_server_settings";
|
||||
const MAX_RETRIES_KEY: &str = "max_retries";
|
||||
const APP_STATE_AI_GLOBAL_INSTRUCTIONS_KEY: &str = "ai_global_custom_instructions";
|
||||
const APP_STATE_AI_CHAT_SELECTION_KEY: &str = "ai_chat_selection_v1";
|
||||
@@ -224,10 +225,110 @@ pub struct McpGlobalPolicy {
|
||||
#[serde(default)]
|
||||
pub allow_dangerous_sql: bool,
|
||||
pub allowed_connection_ids: Option<Vec<String>>,
|
||||
/// `None` exposes every built-in MCP tool. A list is an explicit
|
||||
/// allowlist and is enforced independently of connection permissions.
|
||||
#[serde(default)]
|
||||
pub allowed_tool_names: Option<Vec<String>>,
|
||||
/// Per-connection rules may only reduce the global execution ceiling.
|
||||
/// Keeping this in the global document preserves compatibility with the
|
||||
/// existing policy API while allowing each exposed connection to be safer.
|
||||
#[serde(default)]
|
||||
pub connection_policies: Vec<McpConnectionPolicy>,
|
||||
#[serde(default)]
|
||||
pub query_timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
fn default_mcp_connection_execution_mode_configured() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpConnectionPolicy {
|
||||
pub connection_id: String,
|
||||
/// When true, this connection is read-only even if the MCP-wide policy
|
||||
/// permits writes.
|
||||
#[serde(default)]
|
||||
pub read_only: bool,
|
||||
/// Enables high-risk SQL only when the MCP-wide policy also enables it.
|
||||
/// The default is deliberately false, so adding a connection rule narrows
|
||||
/// a full-access global policy to safe writes unless chosen otherwise.
|
||||
#[serde(default)]
|
||||
pub allow_dangerous_sql: bool,
|
||||
/// Whether the operation ceiling is explicitly overridden for this
|
||||
/// connection. Missing on older saved policies defaults to true so their
|
||||
/// existing safe-write/read-only behavior is preserved; database-only
|
||||
/// rules leave it false and inherit the global ceiling.
|
||||
#[serde(default = "default_mcp_connection_execution_mode_configured")]
|
||||
pub execution_mode_configured: bool,
|
||||
/// Limits which databases below this connection can be reached by MCP.
|
||||
/// The default preserves existing installations: all databases remain
|
||||
/// available until a user explicitly narrows the scope.
|
||||
#[serde(default)]
|
||||
pub database_scope: McpDatabaseScope,
|
||||
/// Exact database names allowed when `database_scope` is `selected`.
|
||||
/// An empty selected list intentionally denies every database.
|
||||
#[serde(default)]
|
||||
pub allowed_databases: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum McpDatabaseScope {
|
||||
#[default]
|
||||
All,
|
||||
Selected,
|
||||
None,
|
||||
}
|
||||
|
||||
/// Configuration for the optional MCP Streamable HTTP server managed by the
|
||||
/// desktop application. Credentials deliberately do not live here: the
|
||||
/// desktop service stores its token in a private file under the DBX data dir.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpHttpServerSettings {
|
||||
#[serde(default)]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "default_mcp_http_host")]
|
||||
pub host: String,
|
||||
#[serde(default = "default_mcp_http_port")]
|
||||
pub port: u16,
|
||||
#[serde(default = "default_mcp_http_path")]
|
||||
pub path: String,
|
||||
#[serde(default)]
|
||||
pub allow_remote: bool,
|
||||
#[serde(default)]
|
||||
pub allowed_hosts: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for McpHttpServerSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
host: default_mcp_http_host(),
|
||||
port: default_mcp_http_port(),
|
||||
path: default_mcp_http_path(),
|
||||
allow_remote: false,
|
||||
allowed_hosts: Vec::new(),
|
||||
allowed_origins: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_mcp_http_host() -> String {
|
||||
"127.0.0.1".to_string()
|
||||
}
|
||||
|
||||
fn default_mcp_http_port() -> u16 {
|
||||
5225
|
||||
}
|
||||
|
||||
fn default_mcp_http_path() -> String {
|
||||
"/mcp".to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct McpGlobalPolicyState {
|
||||
@@ -236,6 +337,10 @@ pub struct McpGlobalPolicyState {
|
||||
pub allow_dangerous_sql: bool,
|
||||
pub allowed_connection_ids: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub allowed_tool_names: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub connection_policies: Vec<McpConnectionPolicy>,
|
||||
#[serde(default)]
|
||||
pub query_timeout_secs: Option<u64>,
|
||||
}
|
||||
|
||||
@@ -245,11 +350,135 @@ impl McpGlobalPolicyState {
|
||||
read_only: self.read_only,
|
||||
allow_dangerous_sql: self.allow_dangerous_sql,
|
||||
allowed_connection_ids: self.allowed_connection_ids.clone(),
|
||||
allowed_tool_names: self.allowed_tool_names.clone(),
|
||||
connection_policies: self.connection_policies.clone(),
|
||||
query_timeout_secs: self.query_timeout_secs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl McpGlobalPolicy {
|
||||
/// Produces the single fail-closed representation persisted by the MCP
|
||||
/// policy API. This protects the policy boundary even when a caller does
|
||||
/// not use the desktop settings form (for example, a Web API client).
|
||||
pub fn normalized(&self) -> Self {
|
||||
let allowed_connection_ids = self.allowed_connection_ids.as_ref().map(|ids| {
|
||||
let mut ids =
|
||||
ids.iter().map(|id| id.trim()).filter(|id| !id.is_empty()).map(ToOwned::to_owned).collect::<Vec<_>>();
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
ids
|
||||
});
|
||||
let allowed_tool_names = self.allowed_tool_names.as_ref().map(|tools| {
|
||||
let mut tools = tools
|
||||
.iter()
|
||||
.map(|tool| tool.trim())
|
||||
.filter(|tool| !tool.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
tools.sort();
|
||||
tools.dedup();
|
||||
tools
|
||||
});
|
||||
|
||||
let mut policies = HashMap::<String, McpConnectionPolicy>::new();
|
||||
for rule in &self.connection_policies {
|
||||
let connection_id = rule.connection_id.trim();
|
||||
if connection_id.is_empty() {
|
||||
continue;
|
||||
}
|
||||
policies
|
||||
.entry(connection_id.to_string())
|
||||
.and_modify(|current| {
|
||||
// Multiple rules are treated as a conjunction: any
|
||||
// read-only rule wins and high-risk access requires every
|
||||
// duplicate rule to explicitly permit it.
|
||||
if rule.execution_mode_configured {
|
||||
if current.execution_mode_configured {
|
||||
current.read_only |= rule.read_only;
|
||||
current.allow_dangerous_sql &= rule.allow_dangerous_sql;
|
||||
} else {
|
||||
current.read_only = rule.read_only;
|
||||
current.allow_dangerous_sql = rule.allow_dangerous_sql;
|
||||
}
|
||||
current.execution_mode_configured = true;
|
||||
}
|
||||
let (scope, databases) = intersect_mcp_database_scopes(
|
||||
current.database_scope,
|
||||
¤t.allowed_databases,
|
||||
rule.database_scope,
|
||||
&rule.allowed_databases,
|
||||
);
|
||||
current.database_scope = scope;
|
||||
current.allowed_databases = databases;
|
||||
})
|
||||
.or_insert_with(|| McpConnectionPolicy {
|
||||
connection_id: connection_id.to_string(),
|
||||
read_only: rule.read_only,
|
||||
allow_dangerous_sql: rule.allow_dangerous_sql,
|
||||
execution_mode_configured: rule.execution_mode_configured,
|
||||
database_scope: rule.database_scope,
|
||||
allowed_databases: normalize_mcp_database_names(&rule.allowed_databases),
|
||||
});
|
||||
}
|
||||
let mut connection_policies = policies.into_values().collect::<Vec<_>>();
|
||||
connection_policies.sort_by(|left, right| left.connection_id.cmp(&right.connection_id));
|
||||
for rule in &mut connection_policies {
|
||||
if rule.read_only {
|
||||
rule.allow_dangerous_sql = false;
|
||||
}
|
||||
rule.allowed_databases = normalize_mcp_database_names(&rule.allowed_databases);
|
||||
if rule.database_scope != McpDatabaseScope::Selected {
|
||||
rule.allowed_databases.clear();
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
read_only: self.read_only,
|
||||
allow_dangerous_sql: !self.read_only && self.allow_dangerous_sql,
|
||||
allowed_connection_ids,
|
||||
allowed_tool_names,
|
||||
connection_policies,
|
||||
query_timeout_secs: self.query_timeout_secs,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_mcp_database_names(databases: &[String]) -> Vec<String> {
|
||||
let mut databases = databases
|
||||
.iter()
|
||||
.map(|database| database.trim())
|
||||
.filter(|database| !database.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
databases.sort();
|
||||
databases.dedup();
|
||||
databases
|
||||
}
|
||||
|
||||
fn intersect_mcp_database_scopes(
|
||||
left_scope: McpDatabaseScope,
|
||||
left_databases: &[String],
|
||||
right_scope: McpDatabaseScope,
|
||||
right_databases: &[String],
|
||||
) -> (McpDatabaseScope, Vec<String>) {
|
||||
use McpDatabaseScope::{All, None, Selected};
|
||||
match (left_scope, right_scope) {
|
||||
(None, _) | (_, None) => (None, Vec::new()),
|
||||
(All, All) => (All, Vec::new()),
|
||||
(All, Selected) => (Selected, normalize_mcp_database_names(right_databases)),
|
||||
(Selected, All) => (Selected, normalize_mcp_database_names(left_databases)),
|
||||
(Selected, Selected) => {
|
||||
let right = normalize_mcp_database_names(right_databases);
|
||||
let databases = normalize_mcp_database_names(left_databases)
|
||||
.into_iter()
|
||||
.filter(|database| right.binary_search(database).is_ok())
|
||||
.collect();
|
||||
(Selected, databases)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_sidebar_table_page_size() -> usize {
|
||||
1000
|
||||
}
|
||||
@@ -1644,6 +1873,8 @@ impl Storage {
|
||||
read_only: policy.read_only,
|
||||
allow_dangerous_sql: policy.allow_dangerous_sql,
|
||||
allowed_connection_ids: policy.allowed_connection_ids,
|
||||
allowed_tool_names: policy.allowed_tool_names,
|
||||
connection_policies: policy.connection_policies,
|
||||
query_timeout_secs: policy.query_timeout_secs,
|
||||
});
|
||||
};
|
||||
@@ -1656,16 +1887,21 @@ impl Storage {
|
||||
read_only: policy.read_only,
|
||||
allow_dangerous_sql: policy.allow_dangerous_sql,
|
||||
allowed_connection_ids: policy.allowed_connection_ids,
|
||||
allowed_tool_names: policy.allowed_tool_names,
|
||||
connection_policies: policy.connection_policies,
|
||||
query_timeout_secs: policy.query_timeout_secs,
|
||||
});
|
||||
};
|
||||
let policy = serde_json::from_value::<McpGlobalPolicy>(value.clone())
|
||||
.map_err(|e| format!("invalid MCP policy: {e}"))?;
|
||||
.map_err(|e| format!("invalid MCP policy: {e}"))?
|
||||
.normalized();
|
||||
Ok(McpGlobalPolicyState {
|
||||
configured: true,
|
||||
read_only: policy.read_only,
|
||||
allow_dangerous_sql: policy.allow_dangerous_sql,
|
||||
allowed_connection_ids: policy.allowed_connection_ids,
|
||||
allowed_tool_names: policy.allowed_tool_names,
|
||||
connection_policies: policy.connection_policies,
|
||||
query_timeout_secs: policy.query_timeout_secs,
|
||||
})
|
||||
})
|
||||
@@ -1674,7 +1910,7 @@ impl Storage {
|
||||
}
|
||||
|
||||
pub async fn save_mcp_global_policy(&self, policy: &McpGlobalPolicy) -> Result<(), String> {
|
||||
let policy = serde_json::to_value(policy).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
|
||||
let policy = serde_json::to_value(policy.normalized()).map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))?;
|
||||
self.with_conn(move |conn| {
|
||||
let current: Option<String> = conn
|
||||
.query_row("SELECT settings_json FROM app_settings WHERE id = 1", [], |row| row.get(0))
|
||||
@@ -1695,6 +1931,22 @@ impl Storage {
|
||||
.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: {e}"))
|
||||
}
|
||||
|
||||
pub async fn load_mcp_http_server_settings(&self) -> Result<McpHttpServerSettings, String> {
|
||||
let settings = self.load_app_settings_json().await?;
|
||||
match settings.get(MCP_HTTP_SERVER_SETTINGS_KEY) {
|
||||
Some(value) => serde_json::from_value(value.clone())
|
||||
.map_err(|error| format!("invalid MCP HTTP server settings: {error}")),
|
||||
None => Ok(McpHttpServerSettings::default()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn save_mcp_http_server_settings(&self, settings: &McpHttpServerSettings) -> Result<(), String> {
|
||||
let mut app_settings = self.load_app_settings_json().await?;
|
||||
let value = serde_json::to_value(settings).map_err(|error| error.to_string())?;
|
||||
app_settings.insert(MCP_HTTP_SERVER_SETTINGS_KEY.to_string(), value);
|
||||
self.save_app_settings_json(&app_settings).await
|
||||
}
|
||||
|
||||
pub async fn save_desktop_settings(&self, desktop_settings: &DesktopSettings) -> Result<(), String> {
|
||||
let mut settings = self.load_app_settings_json().await?;
|
||||
settings.remove("run_in_background");
|
||||
@@ -2619,7 +2871,8 @@ fn load_mcp_global_policy_in_tx(tx: &rusqlite::Transaction<'_>) -> Result<McpGlo
|
||||
.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: invalid app settings JSON: {e}"))?;
|
||||
match settings.get(MCP_GLOBAL_POLICY_KEY) {
|
||||
Some(value) => serde_json::from_value::<McpGlobalPolicy>(value.clone())
|
||||
.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: invalid MCP policy: {e}"))?,
|
||||
.map_err(|e| format!("MCP_POLICY_UNAVAILABLE: invalid MCP policy: {e}"))?
|
||||
.normalized(),
|
||||
None => McpGlobalPolicy::default(),
|
||||
}
|
||||
}
|
||||
@@ -6028,6 +6281,8 @@ mod tests {
|
||||
read_only: false,
|
||||
allow_dangerous_sql: false,
|
||||
allowed_connection_ids: None,
|
||||
allowed_tool_names: None,
|
||||
connection_policies: Vec::new(),
|
||||
query_timeout_secs: None,
|
||||
}
|
||||
);
|
||||
@@ -6039,6 +6294,7 @@ mod tests {
|
||||
allow_dangerous_sql: true,
|
||||
allowed_connection_ids: Some(vec!["conn-1".to_string(), "conn-2".to_string()]),
|
||||
query_timeout_secs: Some(120),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -6048,15 +6304,17 @@ mod tests {
|
||||
McpGlobalPolicyState {
|
||||
configured: true,
|
||||
read_only: true,
|
||||
allow_dangerous_sql: true,
|
||||
allow_dangerous_sql: false,
|
||||
allowed_connection_ids: Some(vec!["conn-1".to_string(), "conn-2".to_string()]),
|
||||
allowed_tool_names: None,
|
||||
connection_policies: Vec::new(),
|
||||
query_timeout_secs: Some(120),
|
||||
}
|
||||
);
|
||||
assert_eq!(storage.load_password_hash().await.unwrap().as_deref(), Some("preserved"));
|
||||
let settings = storage.load_app_settings_json().await.unwrap();
|
||||
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]["allowDangerousSql"], false);
|
||||
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());
|
||||
@@ -6148,6 +6406,7 @@ mod tests {
|
||||
allow_dangerous_sql: false,
|
||||
allowed_connection_ids: Some(vec![kept.id.clone()]),
|
||||
query_timeout_secs: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -6172,6 +6431,7 @@ mod tests {
|
||||
allow_dangerous_sql: false,
|
||||
allowed_connection_ids: None,
|
||||
query_timeout_secs: None,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
Reference in new issue
Block a user