Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(mcp): run MCP tool calls only on a consent approval
thinhlpg15c24b706767
diff --git a/src-tauri/src/core/app/mod.rs b/src-tauri/src/core/app/mod.rsindex 698b62afe..acbf2bdfd 100644--- a/src-tauri/src/core/app/mod.rs+++ b/src-tauri/src/core/app/mod.rs@@ -9,3 +9,6 @@ pub mod paths;// Desktop settings.json store, driven by Tauri commands + a flush thread.#[cfg(not(feature = "cli"))]pub mod settings_store;+// Saved tool grants, kept in the settings store.+#[cfg(not(feature = "cli"))]+pub mod tool_grants;diff --git a/src-tauri/src/core/app/tool_grants.rs b/src-tauri/src/core/app/tool_grants.rsnew file mode 100644index 000000000..ebc7cc242--- /dev/null+++ b/src-tauri/src/core/app/tool_grants.rs@@ -0,0 +1,98 @@+//! Saves the configuration-level tool grants (`tauri_plugin_agent_tools::consent`)+//! in the settings store, under their own key.+//!+//! On first load it takes over the grants the web app used to keep itself+//! (`tool-approval`): "allow all MCP", trusted servers and tools trusted+//! everywhere carry over as they were, since the user set each one+//! explicitly and can now see and revoke them. Grants for one conversation+//! were never meant to outlive it and are dropped. The old key is removed once+//! the grants are saved under the new one.++use serde::Deserialize;+use tauri_plugin_agent_tools::consent::{GrantsPersistence, SavedGrants};++use super::settings_store::{settings_get, settings_remove, settings_set};++pub const TOOL_GRANTS_KEY: &str = "tool-grants";+pub const LEGACY_TOOL_APPROVAL_KEY: &str = "tool-approval";++#[derive(Deserialize, Default)]+#[serde(rename_all = "camelCase")]+struct LegacyState {+ #[serde(default)]+ approved_servers: Vec<String>,+ #[serde(default)]+ approved_tools_global: Vec<String>,+ #[serde(default, rename = "allowAllMCPPermissions")]+ allow_all_mcp_permissions: bool,+}++#[derive(Deserialize)]+struct LegacyBlob {+ #[serde(default)]+ state: LegacyState,+}++/// The grants a `tool-approval` blob held that carry over; `None` when it is+/// unreadable, so nothing is guessed.+fn from_legacy(raw: &str) -> Option<SavedGrants> {+ let blob: LegacyBlob = serde_json::from_str(raw).ok()?;+ Some(SavedGrants {+ allow_all_mcp: blob.state.allow_all_mcp_permissions,+ servers: blob.state.approved_servers.into_iter().collect(),+ tools: blob.state.approved_tools_global.into_iter().collect(),+ })+}++pub struct SettingsGrants;++impl GrantsPersistence for SettingsGrants {+ fn load(&self) -> SavedGrants {+ if let Some(raw) = settings_get(TOOL_GRANTS_KEY.to_string()) {+ return serde_json::from_str(&raw).unwrap_or_else(|e| {+ // Unreadable means nothing is trusted: ask rather than allow.+ log::warn!("Ignoring unreadable saved tool grants: {e}");+ SavedGrants::default()+ });+ }+ let Some(legacy) = settings_get(LEGACY_TOOL_APPROVAL_KEY.to_string()) else {+ return SavedGrants::default();+ };+ let Some(grants) = from_legacy(&legacy) else {+ log::warn!("Ignoring unreadable legacy tool approvals");+ return SavedGrants::default();+ };+ self.save(&grants);+ let _ = settings_remove(LEGACY_TOOL_APPROVAL_KEY.to_string());+ grants+ }++ fn save(&self, grants: &SavedGrants) {+ match serde_json::to_string(grants) {+ Ok(raw) => {+ if let Err(e) = settings_set(TOOL_GRANTS_KEY.to_string(), raw) {+ log::error!("Could not save tool grants: {e}");+ }+ }+ Err(e) => log::error!("Could not serialize tool grants: {e}"),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn legacy_grants_carry_over_except_per_conversation_ones() {+ let raw = r#"{"state":{"approvedTools":{"t1":["mcp:fs/read"]},+ "approvedServers":["fs"],"approvedToolsGlobal":["ext:acme/notes"],+ "allowAllMCPPermissions":true},"version":0}"#;+ let grants = from_legacy(raw).unwrap();+ assert!(grants.allow_all_mcp);+ assert_eq!(grants.servers.into_iter().collect::<Vec<_>>(), ["fs"]);+ assert_eq!(grants.tools.into_iter().collect::<Vec<_>>(), ["ext:acme/notes"]);+ assert!(from_legacy("not json").is_none());+ assert_eq!(from_legacy(r#"{"version":0}"#), Some(SavedGrants::default()));+ }+}diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex 2611d3918..507798a7a 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -408,6 +408,9 @@ pub async fn get_server_summaries(/// (`ToolWithServer::generation`). A call to a server that has since been/// replaced is refused instead of running on the new process/// * `arguments` - Optional map of argument names to values+/// * `thread_id`, `call_id` - The conversation and tool call the user approved+/// (`tauri_plugin_agent_tools::consent`). The call runs only on that+/// approval, given for this tool on the server that is about to run it/// * `cancellation_token` - Optional token to allow cancellation from JS side/// * `max_output_chars` - Optional caller-derived per-result character budget/// (the desktop chat derives one from the active model's context window);@@ -424,6 +427,8 @@ pub async fn call_tool(server_name: Option<String>,server_generation: Option<u64>,arguments: Option<Map<String, Value>>,+ thread_id: Option<String>,+ call_id: Option<String>,cancellation_token: Option<String>,max_output_chars: Option<u64>,) -> Result<CallToolResult, String> {@@ -470,6 +475,17 @@ pub async fn call_tool(log::info!("Found tool {tool_name} in server {srv_name}");+ if let Err(e) = tauri_plugin_agent_tools::consent::store().consume(+ thread_id.as_deref().unwrap_or_default(),+ call_id.as_deref().unwrap_or_default(),+ &tool_name,+ Some(srv_name),+ tauri_plugin_agent_tools::consent::ToolOrigin::Mcp,+ ) {+ cleanup_cancellation_token(&state, &cancellation_token).await;+ return Err(e);+ }+// Call the tool with timeout and cancellation supportlet mut params = CallToolRequestParams::new(tool_name.clone());if let Some(args) = arguments {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 8bb4f24c5..b1f32655a 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -411,6 +411,10 @@ pub fn run() {tauri_plugin_agent_tools::tools::hooks::set_resolver(std::sync::Arc::new(|project| {crate::core::agent::hooks_config::resolve_hooks_for(project)}));+ // Where the configuration-level tool grants ("Allow always") are saved.+ tauri_plugin_agent_tools::consent::store().set_persistence(std::sync::Arc::new(+ crate::core::app::tool_grants::SettingsGrants,+ ));let builder = tauri::Builder::default();// Shadowed rather than mutated: under `e2e` the plugin below is the only