Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: add mcp tool call timeout config (#6891)

Louis01932068648a
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 6eb6dab40..f28dd56f4 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -1,19 +1,31 @@
use rmcp::model::{CallToolRequestParam, CallToolResult};
-use serde_json::{Map, Value};
-use tauri::{AppHandle, Emitter, Runtime, State};
-use tokio::time::timeout;
+use serde_json::{json, Map, Value};
+use tauri::{AppHandle, Emitter, Manager, Runtime, State};
use tokio::sync::oneshot;
+use tokio::time::timeout;
use super::{
- constants::{DEFAULT_MCP_CONFIG, MCP_TOOL_CALL_TIMEOUT},
+ constants::DEFAULT_MCP_CONFIG,
helpers::{restart_active_mcp_servers, start_mcp_server_with_restart, stop_mcp_servers},
};
-use crate::core::{app::commands::get_jan_data_folder_path, state::AppState};
+use crate::core::{
+ app::commands::get_jan_data_folder_path,
+ mcp::models::McpSettings,
+ state::AppState,
+};
use crate::core::{
mcp::models::ToolWithServer,
state::{RunningServiceEnum, SharedMcpServers},
};
-use std::fs;
+use std::{fs, time::Duration};
+
+async fn tool_call_timeout(state: &State<'_, AppState>) -> Duration {
+ state
+ .mcp_settings
+ .lock()
+ .await
+ .tool_call_timeout_duration()
+}
#[tauri::command]
pub async fn activate_mcp_server<R: Runtime>(
@@ -142,18 +154,19 @@ pub async fn get_connected_servers(
/// 6. Returns the combined list of all available tools with server information
#[tauri::command]
pub async fn get_tools(state: State<'_, AppState>) -> Result<Vec<ToolWithServer>, String> {
+ let timeout_duration = tool_call_timeout(&state).await;
let servers = state.mcp_servers.lock().await;
let mut all_tools: Vec<ToolWithServer> = Vec::new();
for (server_name, service) in servers.iter() {
// List tools with timeout
let tools_future = service.list_all_tools();
- let tools = match timeout(MCP_TOOL_CALL_TIMEOUT, tools_future).await {
+ let tools = match timeout(timeout_duration, tools_future).await {
Ok(result) => result.map_err(|e| e.to_string())?,
Err(_) => {
log::warn!(
"Listing tools timed out after {} seconds",
- MCP_TOOL_CALL_TIMEOUT.as_secs()
+ timeout_duration.as_secs()
);
continue; // Skip this server and continue with others
}
@@ -196,6 +209,7 @@ pub async fn call_tool(
arguments: Option<Map<String, Value>>,
cancellation_token: Option<String>,
) -> Result<CallToolResult, String> {
+ let timeout_duration = tool_call_timeout(&state).await;
// Set up cancellation if token is provided
let (cancel_tx, cancel_rx) = oneshot::channel::<()>();
@@ -228,12 +242,12 @@ pub async fn call_tool(
// Race between timeout, tool call, and cancellation
let result = if cancellation_token.is_some() {
tokio::select! {
- result = timeout(MCP_TOOL_CALL_TIMEOUT, tool_call) => {
+ result = timeout(timeout_duration, tool_call) => {
match result {
Ok(call_result) => call_result.map_err(|e| e.to_string()),
Err(_) => Err(format!(
"Tool call '{tool_name}' timed out after {} seconds",
- MCP_TOOL_CALL_TIMEOUT.as_secs()
+ timeout_duration.as_secs()
)),
}
}
@@ -242,11 +256,11 @@ pub async fn call_tool(
}
}
} else {
- match timeout(MCP_TOOL_CALL_TIMEOUT, tool_call).await {
+ match timeout(timeout_duration, tool_call).await {
Ok(call_result) => call_result.map_err(|e| e.to_string()),
Err(_) => Err(format!(
"Tool call '{tool_name}' timed out after {} seconds",
- MCP_TOOL_CALL_TIMEOUT.as_secs()
+ timeout_duration.as_secs()
)),
}
};
@@ -288,9 +302,15 @@ pub async fn cancel_tool_call(
}
}
+fn parse_mcp_settings(value: Option<&Value>) -> McpSettings {
+ value
+ .and_then(|v| serde_json::from_value::<McpSettings>(v.clone()).ok())
+ .unwrap_or_default()
+}
+
#[tauri::command]
pub async fn get_mcp_configs<R: Runtime>(app: AppHandle<R>) -> Result<String, String> {
- let mut path = get_jan_data_folder_path(app);
+ let mut path = get_jan_data_folder_path(app.clone());
path.push("mcp_config.json");
// Create default empty config if file doesn't exist
@@ -300,14 +320,99 @@ pub async fn get_mcp_configs<R: Runtime>(app: AppHandle<R>) -> Result<String, St
.map_err(|e| format!("Failed to create default MCP config: {e}"))?;
}
- fs::read_to_string(path).map_err(|e| e.to_string())
+ let config_string = fs::read_to_string(&path).map_err(|e| e.to_string())?;
+
+ let mut config_value: Value = if config_string.trim().is_empty() {
+ json!({})
+ } else {
+ serde_json::from_str(&config_string).unwrap_or_else(|error| {
+ log::error!("Failed to parse existing MCP config, regenerating defaults: {error}");
+ json!({})
+ })
+ };
+
+ if !config_value.is_object() {
+ config_value = json!({});
+ }
+
+ let mut mutated = false;
+ let config_object = config_value.as_object_mut().unwrap();
+
+ let settings = parse_mcp_settings(config_object.get("mcpSettings"));
+ if !config_object.contains_key("mcpSettings") {
+ config_object.insert(
+ "mcpSettings".to_string(),
+ serde_json::to_value(&settings)
+ .map_err(|e| format!("Failed to serialize MCP settings: {e}"))?,
+ );
+ mutated = true;
+ }
+
+ if !config_object.contains_key("mcpServers") {
+ config_object.insert("mcpServers".to_string(), json!({}));
+ mutated = true;
+ }
+
+ // Persist any mutations back to disk
+ if mutated {
+ fs::write(
+ &path,
+ serde_json::to_string_pretty(&config_value)
+ .map_err(|e| format!("Failed to serialize MCP config: {e}"))?,
+ )
+ .map_err(|e| format!("Failed to write MCP config: {e}"))?;
+ }
+
+ // Update in-memory state with latest settings
+ {
+ let state = app.state::<AppState>();
+ let mut settings_guard = state.mcp_settings.lock().await;
+ *settings_guard = settings.clone();
+ }
+
+ serde_json::to_string_pretty(&config_value)
+ .map_err(|e| format!("Failed to serialize MCP config: {e}"))
}
#[tauri::command]
pub async fn save_mcp_configs<R: Runtime>(app: AppHandle<R>, configs: String) -> Result<(), String> {
- let mut path = get_jan_data_folder_path(app);
+ let mut path = get_jan_data_folder_path(app.clone());
path.push("mcp_config.json");
log::info!("save mcp configs, path: {path:?}");
- fs::write(path, configs).map_err(|e| e.to_string())
+ let mut config_value: Value = serde_json::from_str(&configs)
+ .map_err(|e| format!("Invalid MCP config payload: {e}"))?;
+
+ if !config_value.is_object() {
+ return Err("MCP config must be a JSON object".to_string());
+ }
+
+ let config_object = config_value.as_object_mut().unwrap();
+ let settings = parse_mcp_settings(config_object.get("mcpSettings"));
+
+ if !config_object.contains_key("mcpSettings") {
+ config_object.insert(
+ "mcpSettings".to_string(),
+ serde_json::to_value(&settings).expect("Failed to serialize MCP settings"),
+ );
+ }
+
+ if !config_object.contains_key("mcpServers") {
+ config_object.insert("mcpServers".to_string(), json!({}));
+ }
+
+ fs::write(
+ &path,
+ serde_json::to_string_pretty(&config_value)
+ .map_err(|e| format!("Failed to serialize MCP config: {e}"))?,
+ )
+ .map_err(|e| e.to_string())?;
+
+ {
+ let state = app.state::<AppState>();
+ let mut settings_guard = state.mcp_settings.lock().await;
+ *settings_guard = settings;
+ }
+
+ Ok(())
}
diff --git a/src-tauri/src/core/mcp/constants.rs b/src-tauri/src/core/mcp/constants.rs
index 5ca605913..a0e029268 100644
--- a/src-tauri/src/core/mcp/constants.rs
+++ b/src-tauri/src/core/mcp/constants.rs
@@ -1,10 +1,8 @@
-use std::time::Duration;
-
-// MCP Constants
-pub const MCP_TOOL_CALL_TIMEOUT: Duration = Duration::from_secs(30);
-pub const MCP_BASE_RESTART_DELAY_MS: u64 = 1000; // Start with 1 second
-pub const MCP_MAX_RESTART_DELAY_MS: u64 = 30000; // Cap at 30 seconds
-pub const MCP_BACKOFF_MULTIPLIER: f64 = 2.0; // Double the delay each time
+// Default MCP runtime settings
+pub const DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS: u64 = 30;
+pub const DEFAULT_MCP_BASE_RESTART_DELAY_MS: u64 = 1000; // Start with 1 second
+pub const DEFAULT_MCP_MAX_RESTART_DELAY_MS: u64 = 30000; // Cap at 30 seconds
+pub const DEFAULT_MCP_BACKOFF_MULTIPLIER: f64 = 2.0; // Double the delay each time
pub const DEFAULT_MCP_CONFIG: &str = r#"{
"mcpServers": {
@@ -48,5 +46,11 @@ pub const DEFAULT_MCP_CONFIG: &str = r#"{
"env": {},
"active": false
}
+ },
+ "mcpSettings": {
+ "toolCallTimeoutSeconds": 30,
+ "baseRestartDelayMs": 1000,
+ "maxRestartDelayMs": 30000,
+ "backoffMultiplier": 2.0
}
}"#;
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index fe914c79a..8083a8162 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -17,12 +17,9 @@ use tokio::{
time::{sleep, timeout},
};
-use super::constants::{
- MCP_BACKOFF_MULTIPLIER, MCP_BASE_RESTART_DELAY_MS, MCP_MAX_RESTART_DELAY_MS,
-};
use crate::core::{
app::commands::get_jan_data_folder_path,
- mcp::models::McpServerConfig,
+ mcp::models::{McpServerConfig, McpSettings},
state::{AppState, RunningServiceEnum, SharedMcpServers},
};
use jan_utils::{can_override_npx, can_override_uvx};
@@ -33,16 +30,25 @@ use jan_utils::{can_override_npx, can_override_uvx};
/// * `attempt` - The current restart attempt number (1-based)
///
/// # Returns
-/// * `u64` - Delay in milliseconds, capped at MCP_MAX_RESTART_DELAY_MS
-pub fn calculate_exponential_backoff_delay(attempt: u32) -> u64 {
+/// * `u64` - Delay in milliseconds, capped at configured maximum
+pub fn calculate_exponential_backoff_delay(attempt: u32, settings: &McpSettings) -> u64 {
use std::cmp;
+ let attempt = attempt.max(1);
+ let base_delay_ms = settings.base_restart_delay_ms.max(1);
+ let max_delay_ms = settings.max_restart_delay_ms.max(base_delay_ms);
+ let backoff_multiplier = if settings.backoff_multiplier <= 0.0 {
+ 1.0
+ } else {
+ settings.backoff_multiplier
+ };
+
// Calculate base exponential delay: base_delay * multiplier^(attempt-1)
let exponential_delay =
- (MCP_BASE_RESTART_DELAY_MS as f64) * MCP_BACKOFF_MULTIPLIER.powi((attempt - 1) as i32);
+ (base_delay_ms as f64) * backoff_multiplier.powi((attempt - 1) as i32);
// Cap the delay at maximum
- let capped_delay = cmp::min(exponential_delay as u64, MCP_MAX_RESTART_DELAY_MS);
+ let capped_delay = cmp::min(exponential_delay.round() as u64, max_delay_ms);
// Add jitter (±25% randomness) to prevent thundering herd
let jitter_range = (capped_delay as f64 * 0.25) as u64;
@@ -62,7 +68,9 @@ pub fn calculate_exponential_backoff_delay(attempt: u32) -> u64 {
};
// Apply jitter while ensuring delay stays positive and within bounds
- ((capped_delay as i64 + jitter) as u64).clamp(100, MCP_MAX_RESTART_DELAY_MS)
+ let min_delay_ms = cmp::min(base_delay_ms, max_delay_ms).max(100);
+ let upper_bound = cmp::max(max_delay_ms, min_delay_ms);
+ ((capped_delay as i64 + jitter) as u64).clamp(min_delay_ms, upper_bound)
}
/// Runs MCP commands by reading configuration from a JSON file and initializing servers
@@ -90,6 +98,18 @@ pub async fn run_mcp_commands<R: Runtime>(
let mcp_servers: serde_json::Value = serde_json::from_str(&config_content)
.map_err(|e| format!("Failed to parse config: {e}"))?;
+ // Update runtime MCP settings from config
+ {
+ let settings = mcp_servers
+ .get("mcpSettings")
+ .and_then(|value| serde_json::from_value::<McpSettings>(value.clone()).ok())
+ .unwrap_or_default();
+
+ let app_state = app.state::<AppState>();
+ let mut guard = app_state.mcp_settings.lock().await;
+ *guard = settings;
+ }
+
let server_map = mcp_servers
.get("mcpServers")
.and_then(Value::as_object)
@@ -241,6 +261,7 @@ pub async fn start_mcp_server_with_restart<R: Runtime>(
let restart_counts = app_state.mcp_restart_counts.clone();
let active_servers_state = app_state.mcp_active_servers.clone();
let successfully_connected = app_state.mcp_successfully_connected.clone();
+ let mcp_settings = app_state.mcp_settings.clone();
// Store active server config for restart purposes
store_active_server_config(&active_servers_state, &name, &config).await;
@@ -274,12 +295,13 @@ pub async fn start_mcp_server_with_restart<R: Runtime>(
app,
servers_state,
name,
- config,
- max_restarts,
- restart_counts,
- successfully_connected,
- )
- .await;
+ config,
+ max_restarts,
+ restart_counts,
+ successfully_connected,
+ mcp_settings,
+ )
+ .await;
Ok(())
} else {
@@ -308,6 +330,7 @@ pub async fn start_restart_loop<R: Runtime>(
max_restarts: u32,
restart_counts: Arc<Mutex<HashMap<String, u32>>>,
successfully_connected: Arc<Mutex<HashMap<String, bool>>>,
+ mcp_settings: Arc<Mutex<McpSettings>>,
) {
loop {
let current_restart_count = {
@@ -338,7 +361,12 @@ pub async fn start_restart_loop<R: Runtime>(
);
// Calculate exponential backoff delay
- let delay_ms = calculate_exponential_backoff_delay(current_restart_count);
+ let settings_snapshot = {
+ let settings_guard = mcp_settings.lock().await;
+ settings_guard.clone()
+ };
+ let delay_ms =
+ calculate_exponential_backoff_delay(current_restart_count, &settings_snapshot);
log::info!(
"Waiting {delay_ms}ms before restart attempt {current_restart_count} for MCP server {name}"
);
@@ -854,11 +882,13 @@ pub async fn spawn_server_monitoring_task<R: Runtime>(
max_restarts: u32,
restart_counts: Arc<Mutex<HashMap<String, u32>>>,
successfully_connected: Arc<Mutex<HashMap<String, bool>>>,
+ mcp_settings: Arc<Mutex<McpSettings>>,
) {
let app_clone = app.clone();
let servers_clone = servers_state.clone();
let name_clone = name.clone();
let config_clone = config.clone();
+ let mcp_settings_clone = mcp_settings.clone();
tauri::async_runtime::spawn(async move {
// Monitor the server using RunningService's JoinHandle<QuitReason>
@@ -880,6 +910,7 @@ pub async fn spawn_server_monitoring_task<R: Runtime>(
max_restarts,
restart_counts,
successfully_connected,
+ mcp_settings_clone.clone(),
)
.await;
}
diff --git a/src-tauri/src/core/mcp/models.rs b/src-tauri/src/core/mcp/models.rs
index cd3debbc8..979c2273d 100644
--- a/src-tauri/src/core/mcp/models.rs
+++ b/src-tauri/src/core/mcp/models.rs
@@ -15,6 +15,54 @@ pub struct McpServerConfig {
pub headers: serde_json::Map<String, Value>,
}
+fn default_tool_call_timeout_seconds() -> u64 {
+ super::constants::DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS
+}
+
+fn default_base_restart_delay_ms() -> u64 {
+ super::constants::DEFAULT_MCP_BASE_RESTART_DELAY_MS
+}
+
+fn default_max_restart_delay_ms() -> u64 {
+ super::constants::DEFAULT_MCP_MAX_RESTART_DELAY_MS
+}
+
+fn default_backoff_multiplier() -> f64 {
+ super::constants::DEFAULT_MCP_BACKOFF_MULTIPLIER
+}
+
+/// Runtime MCP settings that can be adjusted via UI
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpSettings {
+ #[serde(default = "default_tool_call_timeout_seconds")]
+ pub tool_call_timeout_seconds: u64,
+ #[serde(default = "default_base_restart_delay_ms")]
+ pub base_restart_delay_ms: u64,
+ #[serde(default = "default_max_restart_delay_ms")]
+ pub max_restart_delay_ms: u64,
+ #[serde(default = "default_backoff_multiplier")]
+ pub backoff_multiplier: f64,
+}
+
+impl Default for McpSettings {
+ fn default() -> Self {
+ Self {
+ tool_call_timeout_seconds: super::constants::DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS,
+ base_restart_delay_ms: super::constants::DEFAULT_MCP_BASE_RESTART_DELAY_MS,
+ max_restart_delay_ms: super::constants::DEFAULT_MCP_MAX_RESTART_DELAY_MS,
+ backoff_multiplier: super::constants::DEFAULT_MCP_BACKOFF_MULTIPLIER,
+ }
+ }
+}
+
+impl McpSettings {
+ /// Returns the tool call timeout duration, enforcing a minimum of 1 second to avoid zero-duration timeouts.
+ pub fn tool_call_timeout_duration(&self) -> std::time::Duration {
+ std::time::Duration::from_secs(self.tool_call_timeout_seconds.max(1))
+ }
+}
+
/// Tool with server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolWithServer {
diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rs
index 71967cd96..8352eb9a4 100644
--- a/src-tauri/src/core/mcp/tests.rs
+++ b/src-tauri/src/core/mcp/tests.rs
@@ -1,18 +1,25 @@
use super::helpers::{add_server_config, add_server_config_with_path, run_mcp_commands};
use crate::core::app::commands::get_jan_data_folder_path;
-use crate::core::state::SharedMcpServers;
+use crate::core::state::{AppState, SharedMcpServers};
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Arc;
-use tauri::test::mock_app;
+use tauri::{test::mock_app, Manager};
use tokio::sync::Mutex;
#[tokio::test]
async fn test_run_mcp_commands() {
let app = mock_app();
+ // Register AppState so state::<AppState>() calls succeed
+ let servers_state: SharedMcpServers = Arc::new(Mutex::new(HashMap::new()));
+ app.manage(AppState {
+ mcp_servers: servers_state.clone(),
+ ..Default::default()
+ });
+
// Get the app path where the config should be created
let app_path = get_jan_data_folder_path(app.handle().clone());
let config_path = app_path.join("mcp_config.json");
@@ -28,7 +35,6 @@ async fn test_run_mcp_commands() {
.expect("Failed to write to config file");
// Call the run_mcp_commands function
- let servers_state: SharedMcpServers = Arc::new(Mutex::new(HashMap::new()));
let result = run_mcp_commands(app.handle(), servers_state).await;
// Assert that the function returns Ok(())
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index ddbbcf7bd..bb8c4ef0a 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -1,6 +1,6 @@
use std::{collections::HashMap, sync::Arc};
-use crate::core::downloads::models::DownloadManagerState;
+use crate::core::{downloads::models::DownloadManagerState, mcp::models::McpSettings};
use rmcp::{
model::{CallToolRequestParam, CallToolResult, InitializeRequestParam, Tool},
service::RunningService,
@@ -28,6 +28,7 @@ pub struct AppState {
pub mcp_successfully_connected: Arc<Mutex<HashMap<String, bool>>>,
pub server_handle: Arc<Mutex<Option<ServerHandle>>>,
pub tool_call_cancellations: Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>,
+ pub mcp_settings: Arc<Mutex<McpSettings>>,
}
impl RunningServiceEnum {
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 276c62150..caedf787d 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2,7 +2,7 @@ mod core;
use core::{
app::commands::get_jan_data_folder_path,
downloads::models::DownloadManagerState,
- mcp::helpers::clean_up_mcp_servers,
+ mcp::{helpers::clean_up_mcp_servers, models::McpSettings},
setup::{self, setup_mcp},
state::AppState,
};
@@ -124,6 +124,7 @@ pub fn run() {
mcp_successfully_connected: Arc::new(Mutex::new(HashMap::new())),
server_handle: Arc::new(Mutex::new(None)),
tool_call_cancellations: Arc::new(Mutex::new(HashMap::new())),
+ mcp_settings: Arc::new(Mutex::new(McpSettings::default())),
})
.setup(|app| {
app.handle().plugin(
diff --git a/web-app/src/containers/__tests__/ChatInput.test.tsx b/web-app/src/containers/__tests__/ChatInput.test.tsx
index a1c24d3e3..05f70edac 100644
--- a/web-app/src/containers/__tests__/ChatInput.test.tsx
+++ b/web-app/src/containers/__tests__/ChatInput.test.tsx
@@ -111,6 +111,7 @@ const mockGetConnectedServers = vi.fn(() => Promise.resolve(['server1']))
const mockGetTools = vi.fn(() => Promise.resolve([]))
const mockStopAllModels = vi.fn()
const mockCheckMmprojExists = vi.fn(() => Promise.resolve(true))
+const mockGetActiveModels = vi.fn(() => Promise.resolve([]))
const mockListen = vi.fn(() => Promise.resolve(() => {}))
@@ -122,6 +123,7 @@ const mockServiceHub = {
models: () => ({
stopAllModels: mockStopAllModels,
checkMmprojExists: mockCheckMmprojExists,
+ getActiveModels: mockGetActiveModels,
}),
events: () => ({
listen: mockListen,
diff --git a/web-app/src/containers/dialogs/EditJsonMCPserver.tsx b/web-app/src/containers/dialogs/EditJsonMCPserver.tsx
index 0fce117a5..3c4a4d56b 100644
--- a/web-app/src/containers/dialogs/EditJsonMCPserver.tsx
+++ b/web-app/src/containers/dialogs/EditJsonMCPserver.tsx
@@ -7,17 +7,25 @@ import {
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
-import { MCPServerConfig } from '@/hooks/useMCPServers'
+import { MCPServerConfig, MCPServers, MCPSettings } from '@/hooks/useMCPServers'
import CodeEditor from '@uiw/react-textarea-code-editor'
import '@uiw/react-textarea-code-editor/dist.css'
import { useTranslation } from '@/i18n/react-i18next-compat'
+type MCPConfigJson =
+ | MCPServerConfig
+ | MCPServers
+ | {
+ mcpServers: MCPServers
+ mcpSettings?: MCPSettings
+ }
+
interface EditJsonMCPserverProps {
open: boolean
onOpenChange: (open: boolean) => void
serverName: string | null // null means editing all servers
- initialData: MCPServerConfig | Record<string, MCPServerConfig>
- onSave: (data: MCPServerConfig | Record<string, MCPServerConfig>) => void
+ initialData: MCPConfigJson
+ onSave: (data: MCPConfigJson) => void
}
export default function EditJsonMCPserver({
@@ -50,7 +58,7 @@ export default function EditJsonMCPserver({
const handleSave = () => {
try {
- const parsedData = JSON.parse(jsonContent)
+ const parsedData = JSON.parse(jsonContent) as MCPConfigJson
onSave(parsedData)
onOpenChange(false)
setError(null)
diff --git a/web-app/src/hooks/__tests__/useMCPServers.test.ts b/web-app/src/hooks/__tests__/useMCPServers.test.ts
index 2e7810be1..b777e7d03 100644
--- a/web-app/src/hooks/__tests__/useMCPServers.test.ts
+++ b/web-app/src/hooks/__tests__/useMCPServers.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
-import { useMCPServers } from '../useMCPServers'
+import { useMCPServers, DEFAULT_MCP_SETTINGS } from '../useMCPServers'
import type { MCPServerConfig } from '../useMCPServers'
// Mock the ServiceHub
@@ -23,6 +23,7 @@ describe('useMCPServers', () => {
useMCPServers.setState({
open: true,
mcpServers: {},
+ settings: { ...DEFAULT_MCP_SETTINGS },
loading: false,
deletedServerKeys: [],
})
@@ -33,6 +34,7 @@ describe('useMCPServers', () => {
expect(result.current.open).toBe(true)
expect(result.current.mcpServers).toEqual({})
+ expect(result.current.settings).toEqual(DEFAULT_MCP_SETTINGS)
expect(result.current.loading).toBe(false)
expect(result.current.deletedServerKeys).toEqual([])
expect(typeof result.current.getServerConfig).toBe('function')
@@ -41,6 +43,8 @@ describe('useMCPServers', () => {
expect(typeof result.current.editServer).toBe('function')
expect(typeof result.current.deleteServer).toBe('function')
expect(typeof result.current.setServers).toBe('function')
+ expect(typeof result.current.setSettings).toBe('function')
+ expect(typeof result.current.updateSettings).toBe('function')
expect(typeof result.current.syncServers).toBe('function')
expect(typeof result.current.syncServersAndRestart).toBe('function')
})
@@ -343,6 +347,36 @@ describe('useMCPServers', () => {
})
})
+ describe('setSettings', () => {
+ it('should replace runtime settings', () => {
+ const { result } = renderHook(() => useMCPServers())
+
+ const newSettings = {
+ ...DEFAULT_MCP_SETTINGS,
+ toolCallTimeoutSeconds: 45,
+ }
+
+ act(() => {
+ result.current.setSettings(newSettings)
+ })
+
+ expect(result.current.settings).toEqual(newSettings)
+ expect(result.current.settings).not.toBe(DEFAULT_MCP_SETTINGS)
+ })
+ })
+
+ describe('updateSettings', () => {
+ it('should merge runtime settings', () => {
+ const { result } = renderHook(() => useMCPServers())
+
+ act(() => {
+ result.current.updateSettings({ toolCallTimeoutSeconds: 45 })
+ })
+
+ expect(result.current.settings.toolCallTimeoutSeconds).toBe(45)
+ })
+ })
+
describe('syncServers', () => {
it('should call updateMCPConfig with current servers', async () => {
const { result } = renderHook(() => useMCPServers())
@@ -366,6 +400,7 @@ describe('useMCPServers', () => {
mcpServers: {
'test-server': serverConfig,
},
+ mcpSettings: result.current.settings,
})
)
})
@@ -380,6 +415,7 @@ describe('useMCPServers', () => {
expect(mockUpdateMCPConfig).toHaveBeenCalledWith(
JSON.stringify({
mcpServers: {},
+ mcpSettings: result.current.settings,
})
)
})
@@ -408,6 +444,7 @@ describe('useMCPServers', () => {
mcpServers: {
'python-server': serverConfig,
},
+ mcpSettings: result.current.settings,
})
)
expect(mockRestartMCPServers).toHaveBeenCalled()
diff --git a/web-app/src/hooks/useMCPServers.ts b/web-app/src/hooks/useMCPServers.ts
index d6da04baa..e82820026 100644
--- a/web-app/src/hooks/useMCPServers.ts
+++ b/web-app/src/hooks/useMCPServers.ts
@@ -18,9 +18,24 @@ export type MCPServers = {
[key: string]: MCPServerConfig
}
+export type MCPSettings = {
+ toolCallTimeoutSeconds: number
+ baseRestartDelayMs: number
+ maxRestartDelayMs: number
+ backoffMultiplier: number
+}
+
+export const DEFAULT_MCP_SETTINGS: MCPSettings = {
+ toolCallTimeoutSeconds: 30,
+ baseRestartDelayMs: 1000,
+ maxRestartDelayMs: 30000,
+ backoffMultiplier: 2,
+}
+
type MCPServerStoreState = {
open: boolean
mcpServers: MCPServers
+ settings: MCPSettings
loading: boolean
deletedServerKeys: string[]
getServerConfig: (key: string) => MCPServerConfig | undefined
@@ -34,6 +49,8 @@ type MCPServerStoreState = {
) => void
deleteServer: (key: string) => void
setServers: (servers: MCPServers) => void
+ setSettings: (settings: MCPSettings) => void
+ updateSettings: (partial: Partial<MCPSettings>) => void
syncServers: () => Promise<void>
syncServersAndRestart: () => Promise<void>
}
@@ -41,6 +58,7 @@ type MCPServerStoreState = {
export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
open: true,
mcpServers: {}, // Start with empty object
+ settings: { ...DEFAULT_MCP_SETTINGS },
loading: false,
deletedServerKeys: [],
setLeftPanel: (value) => set({ open: value }),
@@ -94,6 +112,20 @@ export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
const mcpServers = { ...state.mcpServers, ...servers }
return { mcpServers }
}),
+ setSettings: (settings) =>
+ set(() => ({
+ settings: {
+ ...DEFAULT_MCP_SETTINGS,
+ ...settings,
+ },
+ })),
+ updateSettings: (partial) =>
+ set((state) => ({
+ settings: {
+ ...state.settings,
+ ...partial,
+ },
+ })),
// Delete an MCP server by key
deleteServer: (key) =>
set((state) => {
@@ -110,18 +142,20 @@ export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
}
}),
syncServers: async () => {
- const mcpServers = get().mcpServers
+ const { mcpServers, settings } = get()
await getServiceHub().mcp().updateMCPConfig(
JSON.stringify({
mcpServers,
+ mcpSettings: settings,
})
)
},
syncServersAndRestart: async () => {
- const mcpServers = get().mcpServers
+ const { mcpServers, settings } = get()
await getServiceHub().mcp().updateMCPConfig(
JSON.stringify({
mcpServers,
+ mcpSettings: settings,
})
).then(() => getServiceHub().mcp().restartMCPServers())
},
diff --git a/web-app/src/locales/de-DE/mcp-servers.json b/web-app/src/locales/de-DE/mcp-servers.json
index 3a033e08b..3bc06d341 100644
--- a/web-app/src/locales/de-DE/mcp-servers.json
+++ b/web-app/src/locales/de-DE/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Argumente",
"env": "Umgebung",
"serverStatusActive": "Server {{serverKey}} erfolgreich aktiviert",
- "serverStatusInactive": "Server {{serverKey}} erfolgreich deaktiviert"
+ "serverStatusInactive": "Server {{serverKey}} erfolgreich deaktiviert",
+ "runtimeSettings": {
+ "title": "Laufzeiteinstellungen",
+ "description": "Konfiguriere, wie Jan MCP-Server verwaltet und erneut versucht.",
+ "toolCallTimeout": "Zeitlimit für Tool-Aufruf (Sekunden)",
+ "toolCallTimeoutDesc": "Maximale Wartezeit auf eine Antwort eines MCP-Tools, bevor abgebrochen wird."
+ }
}
diff --git a/web-app/src/locales/en/mcp-servers.json b/web-app/src/locales/en/mcp-servers.json
index dcd794330..0ef36998e 100644
--- a/web-app/src/locales/en/mcp-servers.json
+++ b/web-app/src/locales/en/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Args",
"env": "Env",
"serverStatusActive": "Server {{serverKey}} activated successfully",
- "serverStatusInactive": "Server {{serverKey}} deactivated successfully"
+ "serverStatusInactive": "Server {{serverKey}} deactivated successfully",
+ "runtimeSettings": {
+ "title": "Runtime Settings",
+ "description": "Configure how Jan manages and retries MCP servers.",
+ "toolCallTimeout": "Tool call timeout (seconds)",
+ "toolCallTimeoutDesc": "Maximum time to wait for an MCP tool response before timing out."
+ }
}
diff --git a/web-app/src/locales/id/mcp-servers.json b/web-app/src/locales/id/mcp-servers.json
index 9006ecd04..cbc2a1e5f 100644
--- a/web-app/src/locales/id/mcp-servers.json
+++ b/web-app/src/locales/id/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Argumen",
"env": "Lingkungan",
"serverStatusActive": "Server {{serverKey}} berhasil diaktifkan",
- "serverStatusInactive": "Server {{serverKey}} berhasil dinonaktifkan"
-}
\ No newline at end of file
+ "serverStatusInactive": "Server {{serverKey}} berhasil dinonaktifkan",
+ "runtimeSettings": {
+ "title": "Pengaturan Runtime",
+ "description": "Atur bagaimana Jan mengelola dan mencoba ulang server MCP.",
+ "toolCallTimeout": "Batas waktu pemanggilan alat (detik)",
+ "toolCallTimeoutDesc": "Waktu maksimum menunggu respons alat MCP sebelum waktu habis."
+ }
+}
diff --git a/web-app/src/locales/ja/mcp-servers.json b/web-app/src/locales/ja/mcp-servers.json
index 71b9fd672..5941bdb0d 100644
--- a/web-app/src/locales/ja/mcp-servers.json
+++ b/web-app/src/locales/ja/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "引数",
"env": "環境変数",
"serverStatusActive": "サーバー {{serverKey}} が正常にアクティブ化されました",
- "serverStatusInactive": "サーバー {{serverKey}} が正常に非アクティブ化されました"
-}
\ No newline at end of file
+ "serverStatusInactive": "サーバー {{serverKey}} が正常に非アクティブ化されました",
+ "runtimeSettings": {
+ "title": "ランタイム設定",
+ "description": "JanがMCPサーバーを管理し再試行する方法を設定します。",
+ "toolCallTimeout": "ツール呼び出しタイムアウト(秒)",
+ "toolCallTimeoutDesc": "MCPツールの応答を待機する最大時間(タイムアウトまで)。"
+ }
+}
diff --git a/web-app/src/locales/pl/mcp-servers.json b/web-app/src/locales/pl/mcp-servers.json
index 995583d95..ce778cf14 100644
--- a/web-app/src/locales/pl/mcp-servers.json
+++ b/web-app/src/locales/pl/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Argumenty",
"env": "Zmienne Środowiskowe",
"serverStatusActive": "Pomyślnie aktywowano serwer {{serverKey}}",
- "serverStatusInactive": "Pomyślnie dezaktywowano serwer {{serverKey}}"
+ "serverStatusInactive": "Pomyślnie dezaktywowano serwer {{serverKey}}",
+ "runtimeSettings": {
+ "title": "Ustawienia środowiska uruchomieniowego",
+ "description": "Skonfiguruj, jak Jan zarządza i ponawia próby połączenia z serwerami MCP.",
+ "toolCallTimeout": "Limit czasu wywołania narzędzia (sekundy)",
+ "toolCallTimeoutDesc": "Maksymalny czas oczekiwania na odpowiedź narzędzia MCP przed przekroczeniem limitu czasu."
+ }
}
diff --git a/web-app/src/locales/pt-BR/mcp-servers.json b/web-app/src/locales/pt-BR/mcp-servers.json
index 13ff1ed03..8db01d34e 100644
--- a/web-app/src/locales/pt-BR/mcp-servers.json
+++ b/web-app/src/locales/pt-BR/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Args",
"env": "Env",
"serverStatusActive": "Servidor {{serverKey}} ativado com sucesso",
- "serverStatusInactive": "Servidor {{serverKey}} desativado com sucesso"
+ "serverStatusInactive": "Servidor {{serverKey}} desativado com sucesso",
+ "runtimeSettings": {
+ "title": "Configurações de Execução",
+ "description": "Configure como o Jan gerencia e tenta novamente os servidores MCP.",
+ "toolCallTimeout": "Tempo limite de chamada da ferramenta (segundos)",
+ "toolCallTimeoutDesc": "Tempo máximo de espera por uma resposta da ferramenta MCP antes de atingir o tempo limite."
+ }
}
diff --git a/web-app/src/locales/vn/mcp-servers.json b/web-app/src/locales/vn/mcp-servers.json
index bd44cd9a9..f3b2f69e4 100644
--- a/web-app/src/locales/vn/mcp-servers.json
+++ b/web-app/src/locales/vn/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "Đối số",
"env": "Môi trường",
"serverStatusActive": "Máy chủ {{serverKey}} đã được kích hoạt thành công",
- "serverStatusInactive": "Máy chủ {{serverKey}} đã được hủy kích hoạt thành công"
-}
\ No newline at end of file
+ "serverStatusInactive": "Máy chủ {{serverKey}} đã được hủy kích hoạt thành công",
+ "runtimeSettings": {
+ "title": "Cài đặt thời gian chạy",
+ "description": "Cấu hình cách Jan quản lý và thử lại các máy chủ MCP.",
+ "toolCallTimeout": "Thời gian chờ lệnh (giây)",
+ "toolCallTimeoutDesc": "Thời gian tối đa chờ phản hồi từ công cụ MCP trước khi hết thời gian."
+ }
+}
diff --git a/web-app/src/locales/zh-CN/mcp-servers.json b/web-app/src/locales/zh-CN/mcp-servers.json
index 4fdd16055..25c238c45 100644
--- a/web-app/src/locales/zh-CN/mcp-servers.json
+++ b/web-app/src/locales/zh-CN/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "参数",
"env": "环境",
"serverStatusActive": "服务器 {{serverKey}} 激活成功",
- "serverStatusInactive": "服务器 {{serverKey}} 停用成功"
+ "serverStatusInactive": "服务器 {{serverKey}} 停用成功",
+ "runtimeSettings": {
+ "title": "运行时设置",
+ "description": "配置 Jan 如何管理和重试 MCP 服务器。",
+ "toolCallTimeout": "工具调用超时时间(秒)",
+ "toolCallTimeoutDesc": "在超时前等待 MCP 工具响应的最长时间。"
+ }
}
diff --git a/web-app/src/locales/zh-TW/mcp-servers.json b/web-app/src/locales/zh-TW/mcp-servers.json
index 9e51fbb21..5d9316c81 100644
--- a/web-app/src/locales/zh-TW/mcp-servers.json
+++ b/web-app/src/locales/zh-TW/mcp-servers.json
@@ -43,5 +43,11 @@
"args": "參數",
"env": "環境",
"serverStatusActive": "伺服器 {{serverKey}} 啟用成功",
- "serverStatusInactive": "伺服器 {{serverKey}} 停用成功"
+ "serverStatusInactive": "伺服器 {{serverKey}} 停用成功",
+ "runtimeSettings": {
+ "title": "執行階段設定",
+ "description": "設定 Jan 如何管理及重試 MCP 伺服器。",
+ "toolCallTimeout": "工具呼叫逾時(秒)",
+ "toolCallTimeoutDesc": "等待 MCP 工具回應的最長時間,超過即逾時。"
+ }
}
diff --git a/web-app/src/providers/DataProvider.tsx b/web-app/src/providers/DataProvider.tsx
index d9d09ef71..dfd899da0 100644
--- a/web-app/src/providers/DataProvider.tsx
+++ b/web-app/src/providers/DataProvider.tsx
@@ -3,7 +3,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { useAppUpdater } from '@/hooks/useAppUpdater'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useEffect } from 'react'
-import { useMCPServers } from '@/hooks/useMCPServers'
+import { useMCPServers, DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
import { useAssistant } from '@/hooks/useAssistant'
import { useNavigate } from '@tanstack/react-router'
import { route } from '@/constants/routes'
@@ -19,7 +19,7 @@ export function DataProvider() {
useModelProvider()
const { checkForUpdate } = useAppUpdater()
- const { setServers } = useMCPServers()
+ const { setServers, setSettings } = useMCPServers()
const { setAssistants, initializeWithLastUsed } = useAssistant()
const { setThreads } = useThreads()
const navigate = useNavigate()
@@ -46,7 +46,10 @@ export function DataProvider() {
serviceHub
.mcp()
.getMCPConfig()
- .then((data) => setServers(data.mcpServers ?? {}))
+ .then((data) => {
+ setServers(data.mcpServers ?? {})
+ setSettings(data.mcpSettings ?? DEFAULT_MCP_SETTINGS)
+ })
serviceHub
.assistants()
.getAssistants()
diff --git a/web-app/src/providers/__tests__/DataProvider.test.tsx b/web-app/src/providers/__tests__/DataProvider.test.tsx
index 19fd0418c..15d2ce064 100644
--- a/web-app/src/providers/__tests__/DataProvider.test.tsx
+++ b/web-app/src/providers/__tests__/DataProvider.test.tsx
@@ -45,6 +45,7 @@ vi.mock('@/hooks/useAppUpdater', () => ({
vi.mock('@/hooks/useMCPServers', () => ({
useMCPServers: vi.fn(() => ({
setServers: vi.fn(),
+ setSettings: vi.fn(),
})),
}))
diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsx
index 9e759dc81..d759cd801 100644
--- a/web-app/src/routes/settings/mcp-servers.tsx
+++ b/web-app/src/routes/settings/mcp-servers.tsx
@@ -9,12 +9,13 @@ import {
IconTrash,
IconCodeCircle,
} from '@tabler/icons-react'
-import { useMCPServers, MCPServerConfig } from '@/hooks/useMCPServers'
+import { useMCPServers, MCPServerConfig, MCPSettings, DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
import { useEffect, useState } from 'react'
import AddEditMCPServer from '@/containers/dialogs/AddEditMCPServer'
import DeleteMCPServerConfirm from '@/containers/dialogs/DeleteMCPServerConfirm'
import EditJsonMCPserver from '@/containers/dialogs/EditJsonMCPserver'
import { Switch } from '@/components/ui/switch'
+import { Input } from '@/components/ui/input'
import { twMerge } from 'tailwind-merge'
import { useServiceHub } from '@/hooks/useServiceHub'
import { useToolApproval } from '@/hooks/useToolApproval'
@@ -101,6 +102,7 @@ function MCPServersDesktop() {
const serviceHub = useServiceHub()
const {
mcpServers,
+ settings,
addServer,
editServer,
renameServer,
@@ -108,6 +110,8 @@ function MCPServersDesktop() {
syncServers,
syncServersAndRestart,
getServerConfig,
+ setSettings,
+ updateSettings,
} = useMCPServers()
const { allowAllMCPPermissions, setAllowAllMCPPermissions } =
useToolApproval()
@@ -126,7 +130,13 @@ function MCPServersDesktop() {
const [jsonEditorOpen, setJsonEditorOpen] = useState(false)
const [jsonServerName, setJsonServerName] = useState<string | null>(null)
const [jsonEditorData, setJsonEditorData] = useState<
- MCPServerConfig | Record<string, MCPServerConfig> | undefined
+ | MCPServerConfig
+ | Record<string, MCPServerConfig>
+ | {
+ mcpServers: Record<string, MCPServerConfig>
+ mcpSettings?: MCPSettings
+ }
+ | undefined
>(undefined)
const [connectedServers, setConnectedServers] = useState<string[]>([])
const [loadingServers, setLoadingServers] = useState<{
@@ -134,6 +144,20 @@ function MCPServersDesktop() {
}>({})
const setErrorMessage = useAppState((state) => state.setErrorMessage)
+ const updateToolCallTimeout = (rawValue: string) => {
+ if (rawValue === '') {
+ updateSettings({
+ toolCallTimeoutSeconds: DEFAULT_MCP_SETTINGS.toolCallTimeoutSeconds,
+ })
+ return
+ }
+
+ const numericValue = Number(rawValue)
+ if (!Number.isNaN(numericValue)) {
+ updateSettings({ toolCallTimeoutSeconds: numericValue })
+ }
+ }
+
const handleOpenDialog = (serverKey?: string) => {
if (serverKey) {
// Edit mode
@@ -204,13 +228,19 @@ function MCPServersDesktop() {
} else {
// Edit all servers JSON
setJsonServerName(null)
- setJsonEditorData(mcpServers)
+ setJsonEditorData({
+ mcpServers,
+ mcpSettings: settings,
+ })
}
setJsonEditorOpen(true)
}
const handleSaveJson = async (
- data: MCPServerConfig | Record<string, MCPServerConfig>
+ data:
+ | MCPServerConfig
+ | Record<string, MCPServerConfig>
+ | { mcpServers?: Record<string, MCPServerConfig>; mcpSettings?: MCPSettings }
) => {
if (jsonServerName) {
try {
@@ -223,6 +253,29 @@ function MCPServersDesktop() {
toggleServer(jsonServerName, (data as MCPServerConfig).active || false)
} else {
// Save all servers
+ let nextServers: Record<string, MCPServerConfig> = {}
+ let nextSettings: MCPSettings | undefined
+
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
+ if ('mcpServers' in data || 'mcpSettings' in data) {
+ const payload = data as {
+ mcpServers?: Record<string, MCPServerConfig>
+ mcpSettings?: MCPSettings
+ }
+ nextServers = payload.mcpServers ?? {}
+ nextSettings = payload.mcpSettings
+ } else {
+ nextServers = data as Record<string, MCPServerConfig>
+ }
+ }
+
+ if (nextSettings) {
+ setSettings({
+ ...DEFAULT_MCP_SETTINGS,
+ ...nextSettings,
+ })
+ }
+
// Clear existing servers first
Object.keys(mcpServers).forEach((serverKey) => {
toggleServer(serverKey, false)
@@ -230,12 +283,12 @@ function MCPServersDesktop() {
})
// Add all servers from the JSON
- Object.entries(data as Record<string, MCPServerConfig>).forEach(
- ([key, config]) => {
- addServer(key, config)
- toggleServer(key, config.active || false)
- }
- )
+ Object.entries(nextServers).forEach(([key, config]) => {
+ addServer(key, config)
+ toggleServer(key, config.active || false)
+ })
+
+ await syncServers()
}
}
@@ -372,6 +425,23 @@ function MCPServersDesktop() {
</div>
}
/>
+ <CardItem
+ title={t('mcp-servers:runtimeSettings.toolCallTimeout')}
+ description={t('mcp-servers:runtimeSettings.toolCallTimeoutDesc')}
+ actions={
+ <Input
+ type="number"
+ min={1}
+ step={1}
+ value={settings.toolCallTimeoutSeconds}
+ onChange={(event) => updateToolCallTimeout(event.target.value)}
+ onBlur={() => {
+ void syncServers()
+ }}
+ className="w-28"
+ />
+ }
+ />
</Card>
{Object.keys(mcpServers).length === 0 ? (
@@ -529,7 +599,10 @@ function MCPServersDesktop() {
onOpenChange={setJsonEditorOpen}
serverName={jsonServerName}
initialData={
- jsonEditorData as MCPServerConfig | Record<string, MCPServerConfig>
+ jsonEditorData ?? {
+ mcpServers,
+ mcpSettings: settings,
+ }
}
onSave={handleSaveJson}
/>
diff --git a/web-app/src/services/__tests__/mcp.test.ts b/web-app/src/services/__tests__/mcp.test.ts
index a2af0cc76..c294a5151 100644
--- a/web-app/src/services/__tests__/mcp.test.ts
+++ b/web-app/src/services/__tests__/mcp.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { TauriMCPService } from '../mcp/tauri'
import { MCPTool } from '@/types/completion'
+import { DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
// Mock the global window.core.api
const mockCore = {
@@ -111,8 +112,11 @@ describe('TauriMCPService', () => {
it('should get and parse MCP config correctly', async () => {
const mockConfigString = '{"server1": {"path": "/path/to/server"}, "server2": {"command": "node server.js"}}'
const expectedConfig = {
- server1: { path: '/path/to/server' },
- server2: { command: 'node server.js' },
+ mcpServers: {
+ server1: { path: '/path/to/server' },
+ server2: { command: 'node server.js' },
+ },
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
}
mockCore.api.getMcpConfigs.mockResolvedValue(mockConfigString)
@@ -123,28 +127,37 @@ describe('TauriMCPService', () => {
expect(result).toEqual(expectedConfig)
})
- it('should return empty object when config is null', async () => {
+ it('should return default config when config is null', async () => {
mockCore.api.getMcpConfigs.mockResolvedValue(null)
const result = await mcpService.getMCPConfig()
- expect(result).toEqual({})
+ expect(result).toEqual({
+ mcpServers: {},
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
+ })
})
- it('should return empty object when config is undefined', async () => {
+ it('should return default config when config is undefined', async () => {
mockCore.api.getMcpConfigs.mockResolvedValue(undefined)
const result = await mcpService.getMCPConfig()
- expect(result).toEqual({})
+ expect(result).toEqual({
+ mcpServers: {},
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
+ })
})
- it('should return empty object when config is empty string', async () => {
+ it('should return default config when config is empty string', async () => {
mockCore.api.getMcpConfigs.mockResolvedValue('')
const result = await mcpService.getMCPConfig()
- expect(result).toEqual({})
+ expect(result).toEqual({
+ mcpServers: {},
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
+ })
})
it('should handle invalid JSON gracefully', async () => {
diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.ts
index 244e002c3..b3094bc98 100644
--- a/web-app/src/services/mcp/tauri.ts
+++ b/web-app/src/services/mcp/tauri.ts
@@ -4,7 +4,8 @@
import { invoke } from '@tauri-apps/api/core'
import { MCPTool } from '@/types/completion'
-import type { MCPServerConfig } from '@/hooks/useMCPServers'
+import { DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
+import type { MCPServerConfig, MCPServers, MCPSettings } from '@/hooks/useMCPServers'
import type { MCPConfig } from './types'
import { DefaultMCPService } from './default'
@@ -18,9 +19,42 @@ export class TauriMCPService extends DefaultMCPService {
}
async getMCPConfig(): Promise<MCPConfig> {
- const configString = (await window.core?.api?.getMcpConfigs()) ?? '{}'
- const mcpConfig = JSON.parse(configString || '{}') as MCPConfig
- return mcpConfig
+ const rawConfig = await window.core?.api?.getMcpConfigs()
+ const configString = typeof rawConfig === 'string' ? rawConfig.trim() : ''
+
+ const defaultResponse = (): MCPConfig => ({
+ mcpServers: {},
+ mcpSettings: { ...DEFAULT_MCP_SETTINGS },
+ })
+
+ if (!configString) {
+ return defaultResponse()
+ }
+
+ const parsed = JSON.parse(configString) as MCPConfig & Record<string, unknown>
+
+ if (!parsed || typeof parsed !== 'object') {
+ return defaultResponse()
+ }
+
+ const { mcpServers, mcpSettings, ...legacyServers } = parsed
+ const hasLegacyServers = Object.keys(legacyServers).length > 0
+
+ const normalizedServers: MCPServers =
+ (isPlainObject(mcpServers) ? (mcpServers as MCPServers) : undefined) ??
+ (hasLegacyServers && isPlainObject(legacyServers)
+ ? (legacyServers as MCPServers)
+ : ({} as MCPServers))
+
+ const normalizedSettings: MCPSettings = {
+ ...DEFAULT_MCP_SETTINGS,
+ ...(isPlainObject(mcpSettings) ? (mcpSettings as MCPSettings) : {}),
+ }
+
+ return {
+ mcpServers: normalizedServers,
+ mcpSettings: normalizedSettings,
+ }
}
async getTools(): Promise<MCPTool[]> {
@@ -76,3 +110,7 @@ export class TauriMCPService extends DefaultMCPService {
return await invoke('deactivate_mcp_server', { name })
}
}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
diff --git a/web-app/src/services/mcp/types.ts b/web-app/src/services/mcp/types.ts
index eef8e1bf3..b04c5bd07 100644
--- a/web-app/src/services/mcp/types.ts
+++ b/web-app/src/services/mcp/types.ts
@@ -3,10 +3,11 @@
*/
import { MCPTool, MCPToolCallResult } from '@janhq/core'
-import type { MCPServerConfig, MCPServers } from '@/hooks/useMCPServers'
+import type { MCPServerConfig, MCPServers, MCPSettings } from '@/hooks/useMCPServers'
export interface MCPConfig {
mcpServers?: MCPServers
+ mcpSettings?: MCPSettings
}
export interface ToolCallWithCancellationResult {
diff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.ts
index 79045cec0..30a953692 100644
--- a/web-app/src/test/setup.ts
+++ b/web-app/src/test/setup.ts
@@ -117,6 +117,7 @@ const mockServiceHub = {
deleteModel: vi.fn().mockResolvedValue(undefined),
updateModel: vi.fn().mockResolvedValue(undefined),
startModel: vi.fn().mockResolvedValue(undefined),
+ getActiveModels: vi.fn().mockResolvedValue([]),
isModelSupported: vi.fn().mockResolvedValue('GREEN'),
checkMmprojExists: vi.fn().mockResolvedValue(true), // cspell: disable-line
stopAllModels: vi.fn().mockResolvedValue(undefined),