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.

feat: distinct mcp server

Vanalitef3d645fb61f4
diff --git a/core/src/browser/extensions/mcp.ts b/core/src/browser/extensions/mcp.ts
index 74a008d40..d47065e29 100644
--- a/core/src/browser/extensions/mcp.ts
+++ b/core/src/browser/extensions/mcp.ts
@@ -15,7 +15,7 @@ export abstract class MCPExtension extends BaseExtension implements MCPInterface
}
abstract getTools(): Promise<MCPTool[]>
- abstract callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult>
+ abstract callTool(toolName: string, args: Record<string, unknown>, serverName?: string): Promise<MCPToolCallResult>
abstract getConnectedServers(): Promise<string[]>
abstract refreshTools(): Promise<void>
abstract isHealthy(): Promise<boolean>
diff --git a/core/src/types/mcp/mcpInterface.ts b/core/src/types/mcp/mcpInterface.ts
index a656e9f66..77f12d3f7 100644
--- a/core/src/types/mcp/mcpInterface.ts
+++ b/core/src/types/mcp/mcpInterface.ts
@@ -12,8 +12,11 @@ export interface MCPInterface {
/**
* Call a specific MCP tool
+ * @param toolName - Name of the tool to call
+ * @param args - Arguments to pass to the tool
+ * @param serverName - Optional server name to disambiguate tools with same name
*/
- callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult>
+ callTool(toolName: string, args: Record<string, unknown>, serverName?: string): Promise<MCPToolCallResult>
/**
* Get list of connected MCP servers
diff --git a/extensions-web/src/mcp-web/index.ts b/extensions-web/src/mcp-web/index.ts
index 7d5c2ba46..3f4c20964 100644
--- a/extensions-web/src/mcp-web/index.ts
+++ b/extensions-web/src/mcp-web/index.ts
@@ -149,7 +149,7 @@ export default class MCPExtensionWeb extends MCPExtension {
return this.tools
}
- async callTool(toolName: string, args: Record<string, unknown>): Promise<MCPToolCallResult> {
+ async callTool(toolName: string, args: Record<string, unknown>, serverName?: string): Promise<MCPToolCallResult> {
if (!this.mcpClient) {
return {
error: 'MCP client not initialized',
@@ -244,14 +244,14 @@ export default class MCPExtensionWeb extends MCPExtension {
}
/**
- * Returns the list of tool names that should be disabled by default for new users
+ * Returns the list of tool keys (server::tool format) that should be disabled by default for new users
* All MCP web tools are disabled by default to prevent accidental API usage
- * @returns Array of tool names to disable by default
+ * @returns Array of tool keys (server::tool) to disable by default
*/
async getDefaultDisabledTools(): Promise<string[]> {
try {
const tools = await this.getTools()
- return tools.map(tool => tool.name)
+ return tools.map(tool => `${tool.server}::${tool.name}`)
} catch (error) {
console.error('Failed to get default disabled tools:', error)
return []
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 158fa4bcf..5763512b2 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -190,6 +190,7 @@ pub async fn get_tools(state: State<'_, AppState>) -> Result<Vec<ToolWithServer>
/// # Arguments
/// * `state` - Application state containing MCP server connections
/// * `tool_name` - Name of the tool to call
+/// * `server_name` - Optional name of the server to call the tool from (for disambiguation)
/// * `arguments` - Optional map of argument names to values
/// * `cancellation_token` - Optional token to allow cancellation from JS side
///
@@ -198,21 +199,23 @@ pub async fn get_tools(state: State<'_, AppState>) -> Result<Vec<ToolWithServer>
///
/// This function:
/// 1. Locks the MCP servers mutex to access server connections
-/// 2. Searches through all servers for one containing the named tool
-/// 3. When found, calls the tool on that server with the provided arguments
-/// 4. Supports cancellation via cancellation_token
-/// 5. Returns error if no server has the requested tool
+/// 2. If server_name is provided, looks for the tool in that specific server
+/// 3. Otherwise, searches through all servers for one containing the named tool
+/// 4. When found, calls the tool on that server with the provided arguments
+/// 5. Supports cancellation via cancellation_token
+/// 6. Returns error if no server has the requested tool or if specified server not found
#[tauri::command]
pub async fn call_tool(
state: State<'_, AppState>,
tool_name: String,
+ server_name: Option<String>,
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::<()>();
-
+
if let Some(token) = &cancellation_token {
let mut cancellations = state.tool_call_cancellations.lock().await;
cancellations.insert(token.clone(), cancel_tx);
@@ -220,8 +223,23 @@ pub async fn call_tool(
let servers = state.mcp_servers.lock().await;
- // Iterate through servers and find the first one that contains the tool
- for (_, service) in servers.iter() {
+ // If server_name is provided, only check that specific server
+ let servers_to_check: Vec<(&String, &crate::core::state::RunningServiceEnum)> = if let Some(ref server) = server_name {
+ servers.iter()
+ .filter(|(name, _)| *name == server)
+ .collect()
+ } else {
+ servers.iter().collect()
+ };
+
+ if servers_to_check.is_empty() {
+ if let Some(server) = server_name {
+ return Err(format!("Server '{server}' not found"));
+ }
+ }
+
+ // Iterate through servers and find the one that contains the tool
+ for (srv_name, service) in servers_to_check.iter() {
let tools = match service.list_all_tools().await {
Ok(tools) => tools,
Err(_) => continue, // Skip this server if we can't list tools
@@ -231,7 +249,7 @@ pub async fn call_tool(
continue; // Tool not found in this server, try next
}
- println!("Found tool {tool_name} in server");
+ println!("Found tool {tool_name} in server {srv_name}");
// Call the tool with timeout and cancellation support
let tool_call = service.call_tool(CallToolRequestParam {
diff --git a/web-app/src/containers/DropdownToolsAvailable.tsx b/web-app/src/containers/DropdownToolsAvailable.tsx
index a809d69b7..1317e550b 100644
--- a/web-app/src/containers/DropdownToolsAvailable.tsx
+++ b/web-app/src/containers/DropdownToolsAvailable.tsx
@@ -61,30 +61,32 @@ export default function DropdownToolsAvailable({
}
}, [currentThread?.id, tools, initializeThreadTools])
- const handleToolToggle = (toolName: string, checked: boolean) => {
+ const handleToolToggle = (serverName: string, toolName: string, checked: boolean) => {
if (initialMessage) {
// Update default tools for new threads/index page
const currentDefaults = getDefaultDisabledTools()
+ const toolKey = `${serverName}::${toolName}`
if (checked) {
setDefaultDisabledTools(
- currentDefaults.filter((name) => name !== toolName)
+ currentDefaults.filter((key) => key !== toolKey)
)
} else {
- setDefaultDisabledTools([...currentDefaults, toolName])
+ setDefaultDisabledTools([...currentDefaults, toolKey])
}
} else if (currentThread?.id) {
// Update tools for specific thread
- setToolDisabledForThread(currentThread.id, toolName, checked)
+ setToolDisabledForThread(currentThread.id, serverName, toolName, checked)
}
}
- const isToolChecked = (toolName: string): boolean => {
+ const isToolChecked = (serverName: string, toolName: string): boolean => {
if (initialMessage) {
// Use default tools for index page
- return !getDefaultDisabledTools().includes(toolName)
+ const toolKey = `${serverName}::${toolName}`
+ return !getDefaultDisabledTools().includes(toolKey)
} else if (currentThread?.id) {
// Use thread-specific tools
- return !isToolDisabled(currentThread.id, toolName)
+ return !isToolDisabled(currentThread.id, serverName, toolName)
}
return false
}
@@ -96,23 +98,26 @@ export default function DropdownToolsAvailable({
const allToolsByServer = getToolsByServer()
const serverTools = allToolsByServer[serverName] || []
serverTools.forEach((tool) => {
- handleToolToggle(tool.name, !disable)
+ handleToolToggle(tool.server, tool.name, !disable)
})
}
const areAllServerToolsDisabled = (serverName: string): boolean => {
const allToolsByServer = getToolsByServer()
const serverTools = allToolsByServer[serverName] || []
- return serverTools.every((tool) => !isToolChecked(tool.name))
+ return serverTools.every((tool) => !isToolChecked(tool.server, tool.name))
}
const getEnabledToolsCount = (): number => {
- const disabledTools = initialMessage
+ const disabledToolKeys = initialMessage
? getDefaultDisabledTools()
: currentThread?.id
? getDisabledToolsForThread(currentThread.id)
: []
- return tools.filter((tool) => !disabledTools.includes(tool.name)).length
+ return tools.filter((tool) => {
+ const toolKey = `${tool.server}::${tool.name}`
+ return !disabledToolKeys.includes(toolKey)
+ }).length
}
const getToolsByServer = () => {
@@ -175,7 +180,7 @@ export default function DropdownToolsAvailable({
</span>
<span className="text-xs text-main-view-fg/50 inline-flex items-center mr-1 border border-main-view-fg/20 px-1 rounded-sm">
{
- serverTools.filter((tool) => isToolChecked(tool.name))
+ serverTools.filter((tool) => isToolChecked(tool.server, tool.name))
.length
}
</span>
@@ -207,25 +212,25 @@ export default function DropdownToolsAvailable({
)}
<div className="max-h-56 overflow-y-auto">
{serverTools.map((tool) => {
- const isChecked = isToolChecked(tool.name)
+ const isChecked = isToolChecked(tool.server, tool.name)
return (
<DropDrawerItem
onClick={(e) => {
- handleToolToggle(tool.name, !isChecked)
+ handleToolToggle(tool.server, tool.name, !isChecked)
e.preventDefault()
}}
onSelect={(e) => {
- handleToolToggle(tool.name, !isChecked)
+ handleToolToggle(tool.server, tool.name, !isChecked)
e.preventDefault()
}}
- key={tool.name}
+ key={`${tool.server}::${tool.name}`}
className="mt-1 first:mt-0 py-1.5"
icon={
<Switch
checked={isChecked}
onCheckedChange={(checked) => {
console.log('checked', checked)
- handleToolToggle(tool.name, checked)
+ handleToolToggle(tool.server, tool.name, checked)
}}
onClick={(e) => {
e.stopPropagation()
diff --git a/web-app/src/hooks/useToolAvailable.ts b/web-app/src/hooks/useToolAvailable.ts
index 707b84a59..78432ecc9 100644
--- a/web-app/src/hooks/useToolAvailable.ts
+++ b/web-app/src/hooks/useToolAvailable.ts
@@ -3,23 +3,29 @@ import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
import { MCPTool } from '@/types/completion'
+// Helper function to create composite key for server+tool
+const createToolKey = (serverName: string, toolName: string) => {
+ return `${serverName}::${toolName}`
+}
+
type ToolDisabledState = {
- // Track disabled tools per thread
- disabledTools: Record<string, string[]> // threadId -> toolNames[]
- // Global default disabled tools (for new threads/index page)
+ // Track disabled tools per thread using server::tool composite keys
+ disabledTools: Record<string, string[]> // threadId -> toolKeys[] (server::tool format)
+ // Global default disabled tools (for new threads/index page) using composite keys
defaultDisabledTools: string[]
// Flag to track if defaults have been initialized from extension
defaultsInitialized: boolean
- // Actions
+ // Actions - now require both server and tool name
setToolDisabledForThread: (
threadId: string,
+ serverName: string,
toolName: string,
available: boolean
) => void
- isToolDisabled: (threadId: string, toolName: string) => boolean
+ isToolDisabled: (threadId: string, serverName: string, toolName: string) => boolean
getDisabledToolsForThread: (threadId: string) => string[]
- setDefaultDisabledTools: (toolNames: string[]) => void
+ setDefaultDisabledTools: (toolKeys: string[]) => void
getDefaultDisabledTools: () => string[]
isDefaultsInitialized: () => boolean
markDefaultsAsInitialized: () => void
@@ -36,19 +42,21 @@ export const useToolAvailable = create<ToolDisabledState>()(
setToolDisabledForThread: (
threadId: string,
+ serverName: string,
toolName: string,
available: boolean
) => {
set((state) => {
const currentTools = state.disabledTools[threadId] || []
+ const toolKey = createToolKey(serverName, toolName)
let updatedTools: string[]
if (available) {
// Remove disabled tool
- updatedTools = [...currentTools.filter((tool) => tool !== toolName)]
+ updatedTools = [...currentTools.filter((key) => key !== toolKey)]
} else {
// Disable tool
- updatedTools = [...currentTools, toolName]
+ updatedTools = [...currentTools, toolKey]
}
return {
@@ -60,13 +68,14 @@ export const useToolAvailable = create<ToolDisabledState>()(
})
},
- isToolDisabled: (threadId: string, toolName: string) => {
+ isToolDisabled: (threadId: string, serverName: string, toolName: string) => {
const state = get()
+ const toolKey = createToolKey(serverName, toolName)
// If no thread-specific settings, use default
if (!state.disabledTools[threadId]) {
- return state.defaultDisabledTools.includes(toolName)
+ return state.defaultDisabledTools.includes(toolKey)
}
- return state.disabledTools[threadId]?.includes(toolName) || false
+ return state.disabledTools[threadId]?.includes(toolKey) || false
},
getDisabledToolsForThread: (threadId: string) => {
@@ -78,8 +87,8 @@ export const useToolAvailable = create<ToolDisabledState>()(
return state.disabledTools[threadId] || []
},
- setDefaultDisabledTools: (toolNames: string[]) => {
- set({ defaultDisabledTools: toolNames })
+ setDefaultDisabledTools: (toolKeys: string[]) => {
+ set({ defaultDisabledTools: toolKeys })
},
getDefaultDisabledTools: () => {
@@ -103,8 +112,8 @@ export const useToolAvailable = create<ToolDisabledState>()(
// Initialize with default tools only
// Don't auto-enable all tools if defaults are explicitly empty
- const initialTools = state.defaultDisabledTools.filter((toolName) =>
- allTools.some((tool) => tool.name === toolName)
+ const initialTools = state.defaultDisabledTools.filter((toolKey) =>
+ allTools.some((tool) => createToolKey(tool.server, tool.name) === toolKey)
)
set((currentState) => ({
diff --git a/web-app/src/lib/completion.ts b/web-app/src/lib/completion.ts
index d30c4435d..b1e140410 100644
--- a/web-app/src/lib/completion.ts
+++ b/web-app/src/lib/completion.ts
@@ -423,6 +423,7 @@ export const captureProactiveScreenshots = async (
try {
const { promise } = getServiceHub().mcp().callToolWithCancellation({
toolName: screenshotTool.name,
+ serverName: screenshotTool.server,
arguments: {},
})
const screenshotResult = await promise
@@ -439,6 +440,7 @@ export const captureProactiveScreenshots = async (
try {
const { promise } = getServiceHub().mcp().callToolWithCancellation({
toolName: snapshotTool.name,
+ serverName: snapshotTool.server,
arguments: {},
})
const snapshotResult = await promise
@@ -575,6 +577,16 @@ export const postMessageProcessing = async (
const isRagTool = ragToolNames.has(toolName)
const isBrowserTool = isBrowserMCPTool(toolName)
+ // Find server name for this tool from available tools
+ let serverName: string | undefined
+ try {
+ const availableTools = await getServiceHub().mcp().getTools()
+ const matchingTool = availableTools.find(t => t.name === toolName)
+ serverName = matchingTool?.server
+ } catch (e) {
+ console.warn('Failed to lookup server for tool:', toolName, e)
+ }
+
// Auto-approve RAG tools (local/safe operations), require permission for MCP tools
const approved = isRagTool
? true
@@ -608,6 +620,7 @@ export const postMessageProcessing = async (
}
: getServiceHub().mcp().callToolWithCancellation({
toolName,
+ serverName,
arguments: toolArgs,
})
diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.ts
index b3094bc98..0f0d0ad33 100644
--- a/web-app/src/services/mcp/tauri.ts
+++ b/web-app/src/services/mcp/tauri.ts
@@ -67,6 +67,7 @@ export class TauriMCPService extends DefaultMCPService {
async callTool(args: {
toolName: string
+ serverName?: string
arguments: object
}): Promise<{ error: string; content: { text: string }[] }> {
return window.core?.api?.callTool(args)
@@ -74,6 +75,7 @@ export class TauriMCPService extends DefaultMCPService {
callToolWithCancellation(args: {
toolName: string
+ serverName?: string
arguments: object
cancellationToken?: string
}): {
@@ -83,18 +85,18 @@ export class TauriMCPService extends DefaultMCPService {
} {
// Generate a unique cancellation token if not provided
const token = args.cancellationToken ?? `tool_call_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
-
+
// Create the tool call promise with cancellation token
const promise = window.core?.api?.callTool({
...args,
cancellationToken: token
})
-
+
// Create cancel function
const cancel = async () => {
await window.core?.api?.cancelToolCall({ cancellationToken: token })
}
-
+
return { promise, cancel, token }
}