diff --git a/crates/ide-host/src/mcp/mod.rs b/crates/ide-host/src/mcp/mod.rs index ae80c62b5..7d21d0a15 100644 --- a/crates/ide-host/src/mcp/mod.rs +++ b/crates/ide-host/src/mcp/mod.rs @@ -60,6 +60,22 @@ fn allowed(tool: &ide_mcp::Tool, trusted: bool) -> bool { trusted || tool.read_only } +fn tools_for(host: &Host, root: &Path, trusted: bool) -> Vec { + let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect(); + if let Some(plugins) = host.plugin_host() { + all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool)); + } + all.into_iter().filter(|t| allowed(t, trusted)).collect() +} + +/// Lists the built-in IDE and plugin-contributed MCP tools visible to `window`. +pub(crate) fn list_tools_for_window(host: &Host, window: &str) -> Vec { + match host.project(window).ok().filter(|p| !p.light) { + Some(project) => tools_for(host, &project.root, project.is_trusted()), + None => tools_for(host, Path::new(""), true), + } +} + impl Registry { /// The window that answers for `root`: one with the root open, or one it is attached in. fn window(&self, root: &Path) -> Result)>, String> { @@ -127,11 +143,7 @@ impl ToolRegistry for Registry { } fn tools(&self, root: &Path) -> Result, String> { let trusted = self.lists_as_trusted(root)?; - let mut all: Vec<_> = tools().into_iter().map(|t| t.metadata).collect(); - if let Some(plugins) = self.0.plugin_host() { - all.extend(plugins.mcp_tools(root).into_iter().map(|(_, _, tool)| tool)); - } - Ok(all.into_iter().filter(|t| allowed(t, trusted)).collect()) + Ok(tools_for(&self.0, root, trusted)) } fn call( &self, diff --git a/crates/ide-host/src/mcp/service.rs b/crates/ide-host/src/mcp/service.rs index 10b1fe4f6..826a19f4e 100644 --- a/crates/ide-host/src/mcp/service.rs +++ b/crates/ide-host/src/mcp/service.rs @@ -246,6 +246,29 @@ pub fn mcp_server_status(host: &Host, window: &str) -> IdeResult IdeResult { + let started = Instant::now(); + let tools = super::list_tools_for_window(host, window) + .into_iter() + .map(|tool| ide_agent::McpToolSummary { + name: tool.name, + description: (!tool.description.trim().is_empty()).then_some(tool.description), + }) + .collect(); + Ok(ide_agent::McpProbeResult { + ok: true, + server_name: Some("OpenIDEA".into()), + server_version: Some(env!("CARGO_PKG_VERSION").into()), + protocol_version: Some(ide_mcp::PROTOCOL_VERSION.into()), + tools, + duration_ms: u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX), + error: None, + }) +} + /// Settings › Agents › IDE MCP Server › Regenerate Token: forgets the kept token, and restarts the /// server with a new one. Clients configured with the old token stop working. #[command(trust = outside_restricted)] @@ -328,6 +351,36 @@ mod tests { assert_eq!(port_to_wait_for((local, 51234), Some(64342)), None); assert_eq!(port_to_wait_for((local, 64342), None), None); } + + #[tokio::test] + async fn mcp_server_tools_lists_core_tools_and_respects_restricted_mode() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let project_dir = base.join("sample"); + std::fs::create_dir_all(&project_dir).unwrap(); + let host = Arc::new(Host::new(crate::HostConfig::for_test(&base))); + + // Without an open project (e.g. Welcome screen Settings), all built-in tools are listed. + let without_project = mcp_server_tools(&host, "welcome").unwrap(); + assert!(without_project.ok); + assert_eq!(without_project.server_name.as_deref(), Some("OpenIDEA")); + assert!(without_project.tools.iter().any(|t| t.name == "search_text")); + assert!(without_project.tools.iter().any(|t| t.name == "run_command")); + + // Opening an untrusted project filters out write/run tools, matching Registry::tools. + host.open_project("main", &project_dir).unwrap(); + let restricted = mcp_server_tools(&host, "main").unwrap(); + assert!(restricted.ok); + assert!(restricted.tools.iter().any(|t| t.name == "search_text")); + assert!(!restricted.tools.iter().any(|t| t.name == "run_command")); + assert!(restricted.tools.len() < without_project.tools.len()); + + // Trusting the project restores the full tool set. + host.set_project_trust(&project_dir, true, false).await.unwrap(); + let trusted = mcp_server_tools(&host, "main").unwrap(); + assert_eq!(trusted.tools.len(), without_project.tools.len()); + assert!(trusted.tools.iter().any(|t| t.name == "run_command")); + } } ide_command::domain!( @@ -338,6 +391,7 @@ ide_command::domain!( mcp_respond, mcp_respond_with, mcp_server_status, + mcp_server_tools, mcp_ui_ready, mcp_unload_background_project, ); diff --git a/crates/ide-mcp/src/lib.rs b/crates/ide-mcp/src/lib.rs index 594dee3d5..ac5e0f6e5 100644 --- a/crates/ide-mcp/src/lib.rs +++ b/crates/ide-mcp/src/lib.rs @@ -28,6 +28,9 @@ pub use discovery::{Discovery, discovery_path, kept_token, token_path}; pub use server::{McpServer, ServerOptions, local_address}; pub use tokio_util::sync::CancellationToken; +/// The latest MCP protocol version advertised by the built-in IDE server. +pub const PROTOCOL_VERSION: &str = protocol::LATEST; + use std::path::{Path, PathBuf}; /// The header naming the project a request is about (an absolute path). diff --git a/e2e/agentMcp.spec.ts b/e2e/agentMcp.spec.ts index f3d32af21..79dd0ead6 100644 --- a/e2e/agentMcp.spec.ts +++ b/e2e/agentMcp.spec.ts @@ -234,6 +234,34 @@ test("manages multi-level MCP servers in Settings and per-session overrides via handlers.agent_mcp_list = () => servers; handlers.agent_mcp_discover_sources = () => discoveredSources; handlers.agent_mcp_test = () => probeResult; + handlers.mcp_server_tools = () => ({ + ok: true, + serverName: "OpenIDEA", + serverVersion: "0.1.55", + protocolVersion: "2025-06-18", + durationMs: 1, + error: null, + tools: [ + { name: "check_files", description: "Checks files with the language servers and returns their problems" }, + { name: "search_text", description: "Searches for a text substring within project files" }, + ], + }); + handlers.mcp_server_status = () => ({ + running: true, + error: null, + address: "127.0.0.1", + port: 26371, + portUnavailable: null, + project: "/dev/acme-api", + url: "http://127.0.0.1:26371/mcp?project=%2Fdev%2Facme-api", + token: "test-token", + stdioCommand: [ + "/Applications/OpenIDEA.app/Contents/MacOS/openidea", + "--mcp-stdio", + "--project", + "/dev/acme-api", + ], + }); handlers.agent_mcp_set_enabled = ({ id, enabled }) => { servers = servers.map((s) => (s.id === id ? { ...s, enabled: Boolean(enabled) } : s)); return servers; @@ -317,6 +345,13 @@ test("manages multi-level MCP servers in Settings and per-session overrides via "true", ); + // Expand the built-in `openidea` MCP card and verify its tools are shown coherently. + await expect(settingsDialog.getByText("2 MCP tools")).toBeVisible(); + await settingsDialog.getByRole("button", { name: "Test openidea" }).click(); + await expect(settingsDialog.getByText("Tools (2)")).toBeVisible(); + await expect(settingsDialog.getByText("check_files")).toBeVisible(); + await expect(settingsDialog.getByText("Running on port 26371")).toBeVisible(); + // Probe `github-mcp-server` and inspect discovered tools inside the expandable card. await settingsDialog.getByRole("button", { name: "Test github-mcp-server" }).click(); await expect(settingsDialog.getByText("Tools (3)")).toBeVisible(); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index c2b85f788..21d69850c 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -475,6 +475,7 @@ mcp_report_problems trusted project_host bin mcp_respond trusted project_host bindings sync mcp_respond_with trusted project_host bindings sync mcp_server_status outside_restricted project_host bindings sync +mcp_server_tools always project_host bindings sync mcp_set_focused_editor trusted project_host bindings sync mcp_set_open_editors trusted project_host bindings sync mcp_ui_ready trusted project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index 9e3d22a07..813bb4d31 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1281,6 +1281,11 @@ export const commands = { /** Like `mcp_respond`, with a value for requests that ask for one (the started debug session id). */ mcpRespondWith: (id: number, allow: boolean, error: string | null, value: string | null) => typedError(__TAURI_INVOKE("mcp_respond_with", { id, allow, error, value })), mcpServerStatus: () => typedError(__TAURI_INVOKE("mcp_server_status")), + /** + * Lists the tools advertised by OpenIDEA's built-in MCP server (core IDE tools plus + * enabled plugin-contributed `mcpTools`) for the window's project. + */ + mcpServerTools: () => typedError(__TAURI_INVOKE("mcp_server_tools")), mcpSetFocusedEditor: (editor: { path: IpcPath, /** Zero-based lines and UTF-16 columns, end exclusive. */ diff --git a/src/features/agents/McpServers.module.css b/src/features/agents/McpServers.module.css index f94118713..d10441214 100644 --- a/src/features/agents/McpServers.module.css +++ b/src/features/agents/McpServers.module.css @@ -20,27 +20,11 @@ .builtinCard { display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-3); - padding: 8px 12px; + flex-direction: column; border-radius: var(--radius-control); background: var(--bg-elev); box-shadow: inset 0 0 0 1px var(--border); -} - -.builtinMain { - display: flex; - flex-direction: column; - gap: var(--space-0-5); - min-width: 0; -} - -.builtinHeader { - display: flex; - align-items: center; - gap: var(--space-1-5); - flex-wrap: wrap; + overflow: hidden; } .sectionNote { @@ -128,6 +112,10 @@ } .toolDesc { + display: -webkit-box; + overflow: hidden; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; color: var(--fg-muted); line-height: 1.35; } diff --git a/src/features/agents/McpServersPage.tsx b/src/features/agents/McpServersPage.tsx index 00e7fedb9..2895dc553 100644 --- a/src/features/agents/McpServersPage.tsx +++ b/src/features/agents/McpServersPage.tsx @@ -16,6 +16,8 @@ import type { McpScope, McpServer, McpServerInput, + McpServerStatus, + McpToolSummary, McpTransport, } from "@/bindings"; import { executeAction } from "@/platform/actions"; @@ -39,7 +41,15 @@ import { copyText, type MenuItem, } from "@/ui"; -import { IDE_MCP_SETTINGS_PAGE, defaultMcpBackend, useMcpCatalog, type McpBackend } from "./mcpModel"; +import { DEFAULT_MCP_ADDRESS } from "../settings/model/schema"; +import { + BUILTIN_MCP_ID, + BUILTIN_MCP_NAME, + IDE_MCP_SETTINGS_PAGE, + defaultMcpBackend, + useMcpCatalog, + type McpBackend, +} from "./mcpModel"; import { providerIcon } from "./model"; import { useAgents } from "./store"; import page from "./SettingsPage.module.css"; @@ -182,14 +192,102 @@ function serializeServerToJson(server?: McpServer): string { return JSON.stringify({ mcpServers: { [server.name]: entry } }, null, 2); } +/** The built-in server's tools and status; a failed listing becomes a failed probe. */ +async function readBuiltin(backend: McpBackend): Promise<{ probe: McpProbeResult; status: McpServerStatus | null }> { + const status = backend.builtinStatus ? backend.builtinStatus().catch(() => null) : Promise.resolve(null); + try { + const probe = await backend.listBuiltinTools!(); + return { probe, status: await status }; + } catch (e: unknown) { + const error = e instanceof Error ? e.message : String(e); + const probe: McpProbeResult = { + ok: false, + serverName: "OpenIDEA", + serverVersion: null, + protocolVersion: null, + tools: [], + durationMs: 0, + error, + }; + return { probe, status: await status }; + } +} + +function ToolsPanel({ + probe, + isProbing, + tools, +}: { + probe?: McpProbeResult; + isProbing: boolean; + tools?: readonly McpToolSummary[]; +}) { + const tx = useTx(); + const visibleTools = tools ?? probe?.tools ?? []; + return ( +
+
+ + {probe?.ok ? formatMessage(tx("Tools ({count})"), { count: visibleTools.length }) : tx("Tools & Connection")} + + {probe?.ok && ( + + {[probe.serverName, probe.serverVersion ? `v${probe.serverVersion}` : null, `${probe.durationMs} ms`] + .filter(Boolean) + .join(" · ")} + + )} +
+ + {isProbing ? ( +
+ Connecting and listing tools… +
+ ) : probe ? ( + probe.ok ? ( + visibleTools.length > 0 ? ( +
+ {visibleTools.map((tool) => ( +
+ {tool.name} + {tool.description && ( + + {tool.description} + + )} +
+ ))} +
+ ) : ( + + Connected, no tools advertised by this server. + + ) + ) : ( +
+ + {probe.error ?? tx("Connection failed")} +
+ ) + ) : ( + + Test the connection to list the server's tools. + + )} +
+ ); +} + export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpBackend }) { const tx = useTx(); const ideMcpEnabled = useProject((s) => s.settings?.mcpServer?.enabled ?? false); const hasProject = useProject((s) => !!s.project?.root); + const projectTrusted = useProject((s) => (s.project ? s.project.trusted : true)); const providers = useAgents((s) => s.providers); const [tab, setTab] = useState("all"); const [servers, setServers] = useState([]); const [sources, setSources] = useState([]); + const [builtinStatus, setBuiltinStatus] = useState(null); const [query, setQuery] = useState(""); const [error, setError] = useState(null); const [busyId, setBusyId] = useState(null); @@ -241,10 +339,36 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB .catch((e: unknown) => setError(e instanceof Error ? e.message : String(e))); }, [backend, syncCatalog]); + const probeBuiltin = useCallback( + async (expandCard = false) => { + if (!backend.listBuiltinTools) return; + setProbing((prev) => ({ ...prev, [BUILTIN_MCP_ID]: true })); + if (expandCard) setExpanded((prev) => ({ ...prev, [BUILTIN_MCP_ID]: true })); + const { probe, status } = await readBuiltin(backend); + setProbes((prev) => ({ ...prev, [BUILTIN_MCP_ID]: probe })); + if (status !== null) setBuiltinStatus(status); + setProbing((prev) => ({ ...prev, [BUILTIN_MCP_ID]: false })); + }, + [backend], + ); + useEffect(() => { load(); }, [load]); + useEffect(() => { + if (!backend.listBuiltinTools) return; + let live = true; + void readBuiltin(backend).then(({ probe, status }) => { + if (!live) return; + setProbes((prev) => ({ ...prev, [BUILTIN_MCP_ID]: probe })); + if (status !== null) setBuiltinStatus(status); + }); + return () => { + live = false; + }; + }, [backend, ideMcpEnabled, projectTrusted]); + const userServerNames = useMemo( () => new Set(servers.filter((s) => s.scope === "user").map((s) => s.name)), [servers], @@ -532,6 +656,35 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB return out; }, [sources, selectedImports]); + const builtinProbe = probes[BUILTIN_MCP_ID]; + const builtinProbing = !!probing[BUILTIN_MCP_ID]; + const builtinExpanded = !!expanded[BUILTIN_MCP_ID]; + const builtinRunning = builtinStatus ? builtinStatus.running : ideMcpEnabled; + const builtinSummary = "OpenIDEA's code intelligence, diagnostics, refactorings and run configurations."; + + const { showBuiltin, visibleBuiltinTools } = useMemo(() => { + const allTools = builtinProbe?.tools ?? []; + const q = query.trim().toLowerCase(); + if (!q) return { showBuiltin: true, visibleBuiltinTools: allTools }; + const cardMatches = + BUILTIN_MCP_NAME.includes(q) || "built-in ide".includes(q) || builtinSummary.toLowerCase().includes(q); + if (cardMatches) return { showBuiltin: true, visibleBuiltinTools: allTools }; + const matchingTools = allTools.filter( + (t) => t.name.toLowerCase().includes(q) || (t.description ?? "").toLowerCase().includes(q), + ); + return { showBuiltin: matchingTools.length > 0, visibleBuiltinTools: matchingTools }; + }, [builtinProbe, query]); + + const builtinStateLabel = useMemo(() => { + if (!builtinStatus) return ideMcpEnabled ? tx("Enabled") : tx("Not running"); + if (builtinStatus.running) { + const port = builtinStatus.port; + const at = builtinStatus.address && builtinStatus.address !== DEFAULT_MCP_ADDRESS ? builtinStatus.address : null; + return at ? tx`Running on ${at}, port ${port}` : tx`Running on port ${port}`; + } + return builtinStatus.error ?? tx("Not running"); + }, [builtinStatus, ideMcpEnabled, tx]); + return (

@@ -626,26 +779,123 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB

)} - {tab === "all" && ( + {tab === "all" && showBuiltin && (
-
-
- - openidea - - Built-in IDE - - - All agents - +
+ + +
+ {backend.listBuiltinTools && ( + void probeBuiltin(true)} + /> + )} + +
- - OpenIDEA's code intelligence, diagnostics, refactorings and run configurations. -
- + + {builtinExpanded && ( +
+
+ + Status + + {builtinStateLabel} + {builtinStatus?.stdioCommand && builtinStatus.stdioCommand.length > 0 && ( + <> + + Command + + {builtinStatus.stdioCommand.join(" ")} + + )} + {builtinStatus?.url && ( + <> + + Endpoint + + {builtinStatus.url} + + )} +
+ + {backend.listBuiltinTools && ( + + )} + +
+
+ + {backend.listBuiltinTools && ( + + )} +
+
+
+ )}
)} @@ -847,62 +1097,7 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB )}
- {backend.testServer && ( -
-
- - {probe?.ok - ? formatMessage(tx("Tools ({count})"), { count: probe.tools.length }) - : tx("Tools & Connection")} - - {probe?.ok && ( - - {[ - probe.serverName, - probe.serverVersion ? `v${probe.serverVersion}` : null, - `${probe.durationMs} ms`, - ] - .filter(Boolean) - .join(" · ")} - - )} -
- - {isProbing ? ( -
- Connecting and listing tools… -
- ) : probe ? ( - probe.ok ? ( - probe.tools.length > 0 ? ( -
- {probe.tools.map((tool) => ( -
- {tool.name} - {tool.description && ( - {tool.description} - )} -
- ))} -
- ) : ( - - Connected, no tools advertised by this server. - - ) - ) : ( -
- - {probe.error ?? tx("Connection failed")} -
- ) - ) : ( - - Test the connection to list the server's tools. - - )} -
- )} + {backend.testServer && }
diff --git a/src/features/agents/mcpModel.ts b/src/features/agents/mcpModel.ts index 2055ae83e..af578549c 100644 --- a/src/features/agents/mcpModel.ts +++ b/src/features/agents/mcpModel.ts @@ -12,11 +12,13 @@ import type { McpScope, McpServer, McpServerInput, + McpServerStatus, } from "@/bindings"; import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; import { useProject } from "@/platform/project"; export const BUILTIN_MCP_NAME = "openidea"; +export const BUILTIN_MCP_ID = "builtin::openidea"; export const IDE_MCP_SETTINGS_PAGE = "agents.mcpServer"; export interface McpBackend { @@ -29,6 +31,8 @@ export interface McpBackend { discoverSources?(): Promise; importSelected?(scope: McpScope, selections: McpImportSelection[], overwrite: boolean): Promise; testServer?(id: string): Promise; + listBuiltinTools?(): Promise; + builtinStatus?(): Promise; } export const defaultMcpBackend: McpBackend = { @@ -45,6 +49,22 @@ export const defaultMcpBackend: McpBackend = { : Promise.resolve([]), importSelected: (scope, selections, overwrite) => call(commands.agentMcpImportSelected(scope, selections, overwrite)), testServer: (id) => call(commands.agentMcpTest(id)), + listBuiltinTools: () => + typeof commands.mcpServerTools === "function" + ? call(commands.mcpServerTools()) + : Promise.resolve({ + ok: false, + serverName: "OpenIDEA", + serverVersion: null, + protocolVersion: null, + tools: [], + durationMs: 0, + error: "Unavailable", + }), + builtinStatus: () => + typeof commands.mcpServerStatus === "function" + ? call(commands.mcpServerStatus()).catch(() => null) + : Promise.resolve(null), }; export const normalizeProviderId = (id: string): string => (id.endsWith("-acp") ? id.slice(0, -4) : id); diff --git a/src/features/agents/mcpServers.test.tsx b/src/features/agents/mcpServers.test.tsx index a14026b43..68f6c2e97 100644 --- a/src/features/agents/mcpServers.test.tsx +++ b/src/features/agents/mcpServers.test.tsx @@ -7,6 +7,7 @@ import type { McpScope, McpServer, McpServerInput, + McpServerStatus, } from "@/bindings"; import { McpServersPage, type McpBackend } from "./McpServersPage"; @@ -154,6 +155,35 @@ class FakeMcpBackend implements McpBackend { ], })); + listBuiltinTools = vi.fn(async (): Promise => ({ + ok: true, + serverName: "OpenIDEA", + serverVersion: "0.1.55", + protocolVersion: "2025-06-18", + durationMs: 1, + error: null, + tools: [ + { name: "check_files", description: "Checks files with language servers" }, + { name: "search_text", description: "Searches for a text substring within project files" }, + { + name: "dengliu_kubernetes__get_pod_logs", + description: "Fetch pod logs (plugin: Kubernetes [dengliu.kubernetes])", + }, + ], + })); + + builtinStatus = vi.fn(async (): Promise => ({ + running: true, + error: null, + address: "127.0.0.1", + port: 26371, + portUnavailable: null, + project: "/workspace/demo", + url: "http://127.0.0.1:26371/mcp?project=%2Fworkspace%2Fdemo", + token: "secret-token", + stdioCommand: ["/Applications/OpenIDEA.app/Contents/MacOS/openidea", "--mcp-stdio", "--project", "/workspace/demo"], + })); + remove = vi.fn(async (id: string) => { this.removed.push(id); this.servers = this.servers.filter((s) => s.id !== id); @@ -343,4 +373,24 @@ describe("McpServersPage", () => { await waitFor(() => expect(backend.removed).toEqual(["user::linear"])); await waitFor(() => expect(screen.queryByText("linear")).toBeNull()); }); + + it("expands the built-in openidea MCP card to inspect core and plugin tools", async () => { + const backend = new FakeMcpBackend(); + render(); + + await waitFor(() => expect(screen.getByText("3 MCP tools")).toBeInTheDocument()); + fireEvent.click(screen.getByRole("button", { name: /Built-in IDE/i })); + + expect(await screen.findByText("Tools (3)")).toBeInTheDocument(); + expect(screen.getByText("Running on port 26371")).toBeInTheDocument(); + expect(screen.getByText("check_files")).toBeInTheDocument(); + expect(screen.getByText("dengliu_kubernetes__get_pod_logs")).toBeInTheDocument(); + + // Searching by a built-in tool name keeps the openidea card visible and narrows displayed tools. + const search = screen.getByPlaceholderText("Type to search..."); + fireEvent.change(search, { target: { value: "pod_logs" } }); + expect(screen.getByText("Tools (1)")).toBeInTheDocument(); + expect(screen.getByText("dengliu_kubernetes__get_pod_logs")).toBeInTheDocument(); + expect(screen.queryByText("check_files")).not.toBeInTheDocument(); + }); });