diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 0715db9cf5..34e8a30ce1 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -13,13 +13,34 @@ use std::sync::Arc; /// What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell /// line) in the Run tool window's agent tab `name`, on pipes, answered once the process -/// started or failed to. +/// started or failed to. `RunConfiguration` starts a run configuration (a serialized +/// `RunConfig`, its before launch tasks already done) in the Run tool window as the user's +/// Run would, answered the same way. #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(tag = "type", rename_all = "camelCase", rename_all_fields = "camelCase")] pub enum McpUiRequest { - Confirm { client: String, tool: String, subject: String, project: String, detail: Option }, - OpenFile { path: crate::IpcPath, line: Option, column: Option }, - AgentRun { name: String, command: String, cwd: crate::IpcPath, env: BTreeMap }, + Confirm { + client: String, + tool: String, + subject: String, + project: String, + detail: Option, + }, + OpenFile { + path: crate::IpcPath, + line: Option, + column: Option, + }, + AgentRun { + name: String, + command: String, + cwd: crate::IpcPath, + env: BTreeMap, + }, + RunConfiguration { + #[specta(type = specta_typescript::Unknown)] + config: serde_json::Value, + }, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] diff --git a/crates/ide-host/src/mcp/requests.rs b/crates/ide-host/src/mcp/requests.rs index 99c33f60ee..4bffed71eb 100644 --- a/crates/ide-host/src/mcp/requests.rs +++ b/crates/ide-host/src/mcp/requests.rs @@ -38,6 +38,11 @@ impl Requests { let _ = pending.answer.send(error.map_or(Ok(allow), Err)); Ok(()) } + /// Whether `window` answers requests (a project loaded for MCP alone has no window). + pub(super) fn window_ready(&self, window: &str) -> bool { + self.0.lock().ready.contains(window) + } + pub(super) async fn ask(&self, call: &Call, request: McpUiRequest) -> IdeResult<()> { let id = super::tool::request_id().0; let (tx, rx) = oneshot::channel(); diff --git a/crates/ide-host/src/mcp/run/configs.rs b/crates/ide-host/src/mcp/run/configs.rs index 14802dca4d..a5e9316082 100644 --- a/crates/ide-host/src/mcp/run/configs.rs +++ b/crates/ide-host/src/mcp/run/configs.rs @@ -15,8 +15,9 @@ use ide_core::{IdeError, IdeResult, RunId, Severity}; use ide_run::{OutputChunk, RunConfig}; use parking_lot::Mutex; use serde_json::{Map, Value, json}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::Path; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, LazyLock}; use std::time::{Duration, Instant}; @@ -286,6 +287,79 @@ workingDirectory, envs).", /// not the user's own runs. static STARTED: LazyLock>> = LazyLock::new(Default::default); +/// Run configuration parameter naming the `execute_run_configuration` call a start belongs to. +pub const CONFIG_RUN_PARAM: &str = "mcp.configRun"; + +/// The `execute_run_configuration` calls waiting for the Run tool window to start their run. +struct ConfigLaunch { + output: Arc>, + started: Option>, +} +static LAUNCHES: LazyLock>> = LazyLock::new(Default::default); +static NEXT_LAUNCH: AtomicU64 = AtomicU64::new(1); + +/// The Run tool window's start of an `execute_run_configuration` run: its output also goes to +/// the call's output file, and the call learns the run it started. +pub(crate) struct ConfigRunLaunch { + token: u64, + output: Arc>, +} + +/// The call `config` was started for (its first start only; a rerun from the tab is the user's). +pub(crate) fn config_run_launch(config: &RunConfig) -> Option { + let token = config.extras.params.get(CONFIG_RUN_PARAM)?.parse().ok()?; + let launches = LAUNCHES.lock(); + let launch = launches.get(&token).filter(|l| l.started.is_none())?; + Some(ConfigRunLaunch { token, output: launch.output.clone() }) +} + +impl ConfigRunLaunch { + pub(crate) fn wrap_output(&self, on_output: crate::ops::Emit) -> crate::ops::Emit { + let output = self.output.clone(); + Arc::new(move |chunk: OutputChunk| { + // As JetBrains skips `ProcessOutputType.SYSTEM` (`Process finished…`). + if let OutputChunk::Stdout { text } | OutputChunk::Stderr { text } = &chunk { + output.lock().append(text); + } + on_output(chunk); + }) + } + + pub(crate) fn started(&self, result: &IdeResult) { + if let Some(launch) = LAUNCHES.lock().get_mut(&self.token) { + launch.started = Some(result.clone().map_err(|e| e.message)); + } + } +} + +/// Starts `config` in the Run tool window, as the user's Run would: a tab with its console and +/// Stop. Its before launch tasks already ran. +async fn start_in_run_window( + call: &Call, + mut config: RunConfig, + output: Arc>, +) -> IdeResult { + struct Forget(u64); + impl Drop for Forget { + fn drop(&mut self) { + LAUNCHES.lock().remove(&self.0); + } + } + let token = NEXT_LAUNCH.fetch_add(1, Ordering::Relaxed); + LAUNCHES.lock().insert(token, ConfigLaunch { output, started: None }); + let _forget = Forget(token); + config.extras.params.insert(CONFIG_RUN_PARAM.into(), token.to_string()); + let config = serde_json::to_value(&config).map_err(|e| IdeError::invalid(e.to_string()))?; + let asked = call.ask(ide_core::event::McpUiRequest::RunConfiguration { config }).await; + let started = LAUNCHES.lock().get_mut(&token).and_then(|l| l.started.take()); + match (asked, started) { + (_, Some(Ok(info))) => Ok(info), + (_, Some(Err(message))) => Err(IdeError::invalid(message)), + (Err(e), None) => Err(e), + (Ok(()), None) => Err(IdeError::invalid("the run did not start")), + } +} + pub(super) fn started_by_mcp(id: RunId) -> bool { STARTED.lock().contains(&id) } @@ -753,9 +827,9 @@ Behavior: Returns the execution result including current output snapshot, optional exit code, and optional `fullOutputPath`. In OpenIDEA the user is asked first for every call; `programArguments` replace the configuration's \ -arguments (appended to a command that is one shell line, such as `npm run dev`); the run does not appear in the Run \ -tool window: while it is still running, the result carries `runId`, which `stop_run` stops; output files are private \ -and deleted after a day.", +arguments (appended to a command that is one shell line, such as `npm run dev`); the run appears in the Run tool \ +window like a run the user started, with its console and Stop; while it is still running, the result carries `runId`, \ +which `stop_run` stops; output files are private and deleted after a day.", |call| async move { let target = execution_target( call.opt_str("configurationName")?, @@ -811,9 +885,15 @@ one by one", }; let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?)); let output_path = collector.lock().path.clone(); - let sink = collector.clone(); - let emit = process_output(move |text| sink.lock().append(text)); - let info = match crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await { + let started = if call.has_window() { + start_in_run_window(&call, config, collector.clone()).await + } else { + // A project loaded for MCP alone has no Run tool window to show it in. + let sink = collector.clone(); + let emit = process_output(move |text| sink.lock().append(text)); + crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await + }; + let info = match started { Ok(info) => info, Err(e) => { let _ = std::fs::remove_file(&output_path); diff --git a/crates/ide-host/src/mcp/run/mod.rs b/crates/ide-host/src/mcp/run/mod.rs index 5d7e2b0801..9ca3569687 100644 --- a/crates/ide-host/src/mcp/run/mod.rs +++ b/crates/ide-host/src/mcp/run/mod.rs @@ -3,7 +3,7 @@ pub(crate) mod agent; mod agent_tools; mod build; -mod configs; +pub(crate) mod configs; mod output; mod process; mod targets; diff --git a/crates/ide-host/src/mcp/tool.rs b/crates/ide-host/src/mcp/tool.rs index d1789b4737..fd528c4413 100644 --- a/crates/ide-host/src/mcp/tool.rs +++ b/crates/ide-host/src/mcp/tool.rs @@ -70,6 +70,10 @@ impl Call { pub async fn ask(&self, request: ide_core::event::McpUiRequest) -> IdeResult<()> { self.host.mcp_requests.ask(self, request).await } + /// Whether the project has a window to show what the tool starts (not one loaded for MCP alone). + pub fn has_window(&self) -> bool { + self.host.mcp_requests.window_ready(&self.window) + } /// Asks the user before a tool changes the project or starts a process, unless brave mode /// is on — read from the IDE's own settings only, which a project's settings can't set. pub async fn confirm(&self, subject: &str, detail: Option) -> IdeResult<()> { diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 47b54ffa0c..6bd482806c 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -334,10 +334,19 @@ pub async fn run_start( Some(agent) => agent.wrap_output(on_output), None => on_output, }; + // `execute_run_configuration` asked the Run tool window to start it. + let mcp = crate::mcp::run::configs::config_run_launch(&config); + let on_output = match &mcp { + Some(mcp) => mcp.wrap_output(on_output), + None => on_output, + }; let result = start_inner(host, window, config, on_output, agent.as_ref(), &cancel).await; if let Some(agent) = &agent { agent.started(&result); } + if let Some(mcp) = &mcp { + mcp.started(&result); + } if let Some(id) = request { host.end_request(id); } diff --git a/crates/ide-host/tests/mcp.rs b/crates/ide-host/tests/mcp.rs index e63e9718c5..fa93c0fec1 100644 --- a/crates/ide-host/tests/mcp.rs +++ b/crates/ide-host/tests/mcp.rs @@ -731,6 +731,38 @@ async fn reformat_uses_the_formatter_chain_and_preserves_a_dirty_buffer() { assert!(p.documents.is_dirty(doc.id).unwrap()); } +/// Answers `execute_run_configuration`'s window requests the way the Run tool window does: +/// starts the configuration in a tab and says whether it started. Returns what it started. +fn config_run_window(h: &Harness) -> Arc>> { + let started = Arc::new(std::sync::Mutex::new(Vec::new())); + let (host, events, out) = (h.host.clone(), h.events.clone(), started.clone()); + tokio::spawn(async move { + let mut handled = std::collections::HashSet::new(); + loop { + let request = events.lock().unwrap().iter().find_map(|e| match e { + IdeEvent::McpRequest { id, request: ide_core::event::McpUiRequest::RunConfiguration { config } } + if !handled.contains(id) => + { + Some((*id, config.clone())) + } + _ => None, + }); + let Some((id, config)) = request else { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + continue; + }; + handled.insert(id); + let config: ide_run::RunConfig = serde_json::from_value(config).unwrap(); + out.lock().unwrap().push(config.clone()); + let result = + ide_host::ops::run::run_start(&host, "main", config, ide_host::ops::Channel::new(|_| {}), None).await; + let error = result.err().map(|e| e.message); + let _ = host.mcp_requests.answer("main", id, error.is_none(), error); + } + }); + started +} + #[tokio::test(flavor = "multi_thread")] async fn execute_reports_output_exit_code_and_requires_confirmation() { let h = Harness::new(); @@ -765,6 +797,7 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() { assert!(error.contains("denied by the user")); assert!(h.host.processes.list().is_empty()); h.events.lock().unwrap().clear(); + let tabs = config_run_window(&h); let run = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})); let allow = async { let id = h.request().await; @@ -773,6 +806,39 @@ async fn execute_reports_output_exit_code_and_requires_confirmation() { let (result, ()) = tokio::join!(run, allow); assert_eq!(result["exitCode"], 7); assert!(result["output"].as_str().unwrap().contains("captured-output")); + // It ran in a Run tool window tab, as the user's Run would. + let tabs = tabs.lock().unwrap(); + assert_eq!(tabs.len(), 1); + assert_eq!(tabs[0].name, "MCP test"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_project_without_a_window_runs_a_configuration_on_its_own() { + let h = Harness::new(); + h.trust().await; + let config = ide_run::RunConfig { + id: "test".into(), + name: "MCP test".into(), + kind: "shell".into(), + command: if cfg!(windows) { "echo windowless& exit 3" } else { "echo windowless; exit 3" }.into(), + args: vec![], + cwd: None, + env: Default::default(), + detected: false, + is_test: false, + debug_adapter: None, + allow_parallel: false, + extras: Default::default(), + }; + ide_run::save_user_configs(&h.root, &[config]).unwrap(); + h.host + .global_settings + .set(ide_workspace::SettingsScope::Global, "mcpServer.runWithoutConfirmation", json!(true)) + .unwrap(); + let result = h.json("execute_run_configuration", json!({"configurationName":"MCP test","timeout":10000})).await; + assert_eq!(result["exitCode"], 3, "{result}"); + assert!(result["output"].as_str().unwrap().contains("windowless")); + assert!(!h.events.lock().unwrap().iter().any(|e| matches!(e, IdeEvent::McpRequest { .. })), "nothing asked"); } #[tokio::test(flavor = "multi_thread")] @@ -795,6 +861,7 @@ async fn a_configuration_left_running_is_stopped_by_its_run_id() { }; ide_run::save_user_configs(&h.root, &[config]).unwrap(); h.host.mcp_requests.set_ready("main", true); + let _tabs = config_run_window(&h); let run = h.json("execute_run_configuration", json!({"configurationName":"Server","waitForExit":false})); let allow = async { let id = h.request().await; diff --git a/docs/en/guide/mcp.mdx b/docs/en/guide/mcp.mdx index 7b51f5b92f..b03bcdfcd1 100644 --- a/docs/en/guide/mcp.mdx +++ b/docs/en/guide/mcp.mdx @@ -117,6 +117,8 @@ Notes on what they do: `run_command` runs a shell command line in a tab of the Run tool window, with the shell of **Settings › Tools › Terminal**. The agent names the tab and OpenIDEA shows it as `_agent_`, so you see the output as it comes and can type into the command, rerun it or stop it like any run. +Run configurations an agent starts with `execute_run_configuration` open a tab in the Run tool window too, as when you press Run: the console shows their output and Stop ends them. In a background project without a window (brave mode) they run without a tab. + As JetBrains IDEs do, the command runs on pipes, not a terminal: programs print plain lines instead of progress bars and redraws. The agent gets that output cleaned of escape sequences and cut to 2000 lines (`maxLinesCount`); beyond that the end stays, or the start or both ends with `truncateMode`. The tab's raw output log stays complete. - **Servers return once they are up.** The call waits 10 seconds by default for the command to finish. A server, watcher or app never finishes: the agent passes `pattern` with its ready line (`Listening on`, `Started … in`) and gets the answer as soon as the line appears, while the command keeps running. diff --git a/docs/zh/guide/mcp.mdx b/docs/zh/guide/mcp.mdx index cf663b46ae..6937cd84f6 100644 --- a/docs/zh/guide/mcp.mdx +++ b/docs/zh/guide/mcp.mdx @@ -116,6 +116,8 @@ stdio 配置大致如下(路径以你机器上的为准): `run_command` 在运行工具窗口的一个标签页中,用 **设置 › 工具 › 终端** 中配置的 shell 执行一条命令行。标签名由智能体指定,OpenIDEA 显示为 `_agent_<名称>`。输出实时可见,你也可以像对待其他运行一样向命令输入、重新运行或停止它。 +智能体用 `execute_run_configuration` 启动的运行配置同样会在运行工具窗口中打开一个标签页,和你点击运行时一样:控制台显示输出,停止按钮可以结束它。没有窗口的后台项目(勇敢模式)中则不打开标签页。 + 和 JetBrains 的 IDE 一样,命令通过管道运行,而不是在终端里运行:程序输出的是普通文本行,不会有进度条和屏幕重绘。智能体拿到的输出会去掉控制字符,并截断到 2000 行(`maxLinesCount`);超出部分默认保留结尾,也可以用 `truncateMode` 改为保留开头或两头。标签页的原始输出日志保持完整。 - **服务启动好就返回。** 调用默认最多等 10 秒让命令结束。服务器、监视进程或应用不会结束:智能体传入 `pattern`(它就绪时输出的那一行,如 `Listening on`、`Started … in`),这一行一出现就返回,命令继续运行。 diff --git a/src/bindings.ts b/src/bindings.ts index 759aa63045..5f04129142 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -10392,9 +10392,11 @@ export type McpTransport = "stdio" | "http" | "sse"; /** * What a built-in MCP tool asks the project window for. `AgentRun` runs `command` (a shell * line) in the Run tool window's agent tab `name`, on pipes, answered once the process - * started or failed to. + * started or failed to. `RunConfiguration` starts a run configuration (a serialized + * `RunConfig`, its before launch tasks already done) in the Run tool window as the user's + * Run would, answered the same way. */ -export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } }; +export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown }; export type MemoryCategory = /** The backend and its WebView processes. */ diff --git a/src/features/mcp/requests.test.tsx b/src/features/mcp/requests.test.tsx index c60714de56..bd85d3dde4 100644 --- a/src/features/mcp/requests.test.tsx +++ b/src/features/mcp/requests.test.tsx @@ -97,4 +97,13 @@ describe("MCP confirmations", () => { await handleMcpRequest(10, request); expect(mocks.respond).toHaveBeenCalledWith(10, false, "The command did not start"); }); + it("starts an agent's run configuration in the Run tool window and says whether it started", async () => { + const config = { id: "server", name: "Server", kind: "shell", command: "npm run dev" }; + await handleMcpRequest(11, { type: "runConfiguration", config }); + expect(mocks.execute).toHaveBeenCalledWith("run.mcpStart", config); + expect(mocks.respond).toHaveBeenCalledWith(11, true, null); + mocks.execute.mockRejectedValueOnce(new Error("The run did not start")); + await handleMcpRequest(12, { type: "runConfiguration", config }); + expect(mocks.respond).toHaveBeenCalledWith(12, false, "The run did not start"); + }); }); diff --git a/src/features/mcp/requests.ts b/src/features/mcp/requests.ts index d5ae018409..279507333a 100644 --- a/src/features/mcp/requests.ts +++ b/src/features/mcp/requests.ts @@ -44,6 +44,16 @@ export async function handleMcpRequest( ); return; } + if (request.type === "runConfiguration") { + // A run configuration an agent started: a Run tool window tab, as if the user pressed Run. + try { + await executeActionOrThrow("run.mcpStart", request.config); + await send(id, true); + } catch (error) { + await send(id, false, error instanceof Error ? error.message : String(error)).catch(() => {}); + } + return; + } if (request.type === "agentRun") { // The Run tool window starts it in the agent tab; the answer says whether it started. try { diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 6ed98be16b..c6b5c49e02 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -862,6 +862,21 @@ export function activate(): () => void { when: "projectOpen", run: ({ arg }) => startAgentRun(arg as AgentRunRequest), }, + { + id: "run.mcpStart", + title: "Run Configuration for an Agent", + description: + "Starts the configuration the MCP server's `execute_run_configuration` prepared (before launch tasks done) in a Run tool window tab; throws when it did not start.", + category: "Run", + hidden: true, + when: "projectOpen", + run: async ({ arg }) => { + const session = await startRun(arg as import("@/bindings").RunConfig, undefined, undefined, { + prepared: true, + }); + if (!session || session.status === "failed") throw new Error("The run did not start"); + }, + }, { id: "run.pluginStart", title: "Run Plugin Configuration",