From b07eaf22f647c1791c73da1f0239e8a875e2bca6 Mon Sep 17 00:00:00 2001 From: hugocasa Date: Wed, 4 Nov 2026 22:25:00 +0100 Subject: [PATCH] feat: background long runs of per-runnable MCP tools and offer get_run Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../tests/mcp_selection_get_run.rs | 97 +++++++++++++ backend/windmill-api-jobs/src/execution.rs | 44 ++++-- .../windmill-api/src/ai_session_tools/mod.rs | 3 + .../windmill-api/src/ai_session_tools/runs.rs | 2 +- backend/windmill-api/src/jobs.rs | 136 ++++++++++++++++-- backend/windmill-api/src/mcp/core.rs | 86 +++++++++-- backend/windmill-mcp/src/server/backend.rs | 20 ++- backend/windmill-mcp/src/server/runner.rs | 74 +++++++++- backend/windmill-mcp/src/server/session.rs | 2 +- 10 files changed, 430 insertions(+), 36 deletions(-) create mode 100644 backend/windmill-api-integration-tests/tests/mcp_selection_get_run.rs diff --git a/AGENTS.md b/AGENTS.md index 406a9bffd8..0e1762b32b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,7 +69,7 @@ Open-source platform for internal tools, workflows, API integrations, background - **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does. - **CLI commands**: when adding/modifying/removing a command, subcommand, option, or description in `cli/src/commands/`, run `python system_prompts/generate.py` to refresh `system_prompts/auto-generated/` and `cli/src/guidance/skills.gen.ts`. The CLI docs the agents use to operate `wmill` are derived from the source — stale generated files give agents the wrong flags. - **AI guidance** (chat prompts and CLI skills): what the AI knows about Windmill itself — how flows, scripts, apps, pipelines and resources work — is written once, in `system_prompts/base/` and `system_prompts/languages/`, and `system_prompts/generate.py` builds both the chat's `$system_prompts` exports and the CLI's skills from it. Add or change such guidance there, never inline in one consumer: a sentence only one side should see goes in a `` / `` block, and a new file reaches both through the `TOPICS` table. The chat prompt builders under `frontend/src/lib/components/copilot/chat/` add only tool plumbing and runtime values, and shared markdown names no chat tool, since it reaches every chat mode. Rerun `generate.py` after editing; `system_prompts/README.md` has the details. -- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`); the two copies of that rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. A per-runnable tool waits for its run as long as a session run tool does by default (`wait_budget`), then answers with the run id and leaves the run going, as it does when the client disconnects; beside them the runner offers the session's `get_run`, confined to runs of the runnables the token lists (`Runner::get_run`), since that tool reads with no route scope. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). With the `mcp_external_idp` instance setting, every MCP URL also accepts an access token of an external OIDC issuer (`mcp/external_idp.rs`), told apart from Windmill's own by its `iss`: the token's client is mapped to a workspace and to the same access a Windmill token takes (an access level, served the session toolset as `mcp:session`, or a selection of scripts and flows), and the request acts as the existing Windmill user with the token's email, under that access, as a workspace-bound token does. The protected-resource metadata then names that issuer. What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `ai_session_tools/gen/`: after changing a GLOBAL tool definition, the global system prompt or `system_prompts/`, run `npm run gen:mcp-session` from `frontend/` (`mcpSessionGen.test.ts` fails otherwise). The instructions are one template (`EXTERNAL_PROMPT` in `chat/global/core.ts`, with `{{#flag}}` blocks rendered by `promptTemplate.ts`), and the generator exports the flags and variables of each access profile: the token's scope and, for a full token, the caller's role and whether the deploy rules let them deploy. The server only renders it, with the profile the key `prompt_profile` (`ai_session_tools/instructions.rs`) builds, which must match the generator's; its renderer must match `promptTemplate.ts`, which a hash per profile pins. In a workspace with `DisableDirectDeployment` every full token, an admin's included, is held to read-and-run there (`workspace_access` in `mcp/core.rs`), as the chat's session is (`protects` in `chat/global/sessionAccess.ts`); the two copies of that rule change together. What a tool *does* is written once, in a Rust handler the chat also calls (`POST /w/{workspace}/ai_session_tools/{name}`, through `chat/global/backendSessionTools.ts`); the browser applies the effects it returns, saving drafts through its own draft store. A new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `ai_session_tools/mod.rs` fails otherwise). Still written twice, so a behaviour change must be mirrored: `deploy_workspace_item` and `diff` (the chat uses the UI's shared deploy and diff code), and the run tools' form side (argument coercion, secrets, plan mode, the outcome text), where the chat resolves and starts the run on the server but owns the form in between; both sides test their argument handling against `ai_session_tools/run_args_cases.json`, so a change there comes with a case. For MCP Apps clients the server adds tools of its own, defined in Rust (`ai_session_tools/views.rs`) rather than generated, and not offered to the chat, which draws its own cards: `show_run`, `show_runs`, `show_deploy_review` and `show_item` draw a card in the `ui://windmill/card-v` view (`mcp/card.html`; bump `CARD_URI` in `mcp/session.rs` when the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/backend/windmill-api-integration-tests/tests/mcp_selection_get_run.rs b/backend/windmill-api-integration-tests/tests/mcp_selection_get_run.rs new file mode 100644 index 0000000000..7bf04e8e1f --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/mcp_selection_get_run.rs @@ -0,0 +1,97 @@ +//! `get_run` as a token scoped to a selection of runnables is offered it: it reads a run of a +//! selected flow, and refuses one of a flow outside the selection, although the token's owner +//! can read both. The session tool it reuses reads through a JWT without route scopes, so this +//! check is the only thing holding a selection to its own runs. +//! +//! Requires: live database (migrations applied by sqlx::test). No worker: a queued run is +//! readable. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const SELECTED: &str = "u/test-user/selected_flow"; +const OTHER: &str = "u/test-user/other_flow"; + +async fn mcp_call(port: u16, name: &str, arguments: Value) -> anyhow::Result { + let text = reqwest::Client::new() + .post(format!( + "http://localhost:{port}/api/mcp/w/test-workspace/mcp" + )) + .header("Authorization", "Bearer SELECTION_TOKEN") + .header("Accept", "application/json, text/event-stream") + .json(&json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { "name": name, "arguments": arguments } + })) + .send() + .await? + .text() + .await?; + let payload = text + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(text.trim()); + serde_json::from_str(payload).map_err(|e| anyhow::anyhow!("unparseable MCP body {text:?}: {e}")) +} + +async fn create_and_queue(port: u16, path: &str) -> anyhow::Result { + let client = reqwest::Client::new(); + let api = format!("http://localhost:{port}/api/w/test-workspace"); + let resp = client + .post(format!("{api}/flows/create")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ + "path": path, + "summary": "", + "value": { "modules": [{ "id": "a", "value": { "type": "identity" } }] }, + "schema": { "type": "object", "properties": {}, "required": [] } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create flow: {}", resp.text().await?); + let resp = client + .post(format!("{api}/jobs/run/f/{path}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({})) + .send() + .await?; + assert_eq!(resp.status(), 201, "run flow: {}", resp.text().await?); + Ok(resp.text().await?) +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_get_run_reads_only_runs_of_the_selection(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes, workspace_id) + VALUES (encode(sha256('SELECTION_TOKEN'::bytea), 'hex'), 'SELECTION', 'SELECTION_TOKEN', + 'test@windmill.dev', 'selection', false, ARRAY['mcp:flows:u/test-user/selected_flow'], 'test-workspace')", + ) + .execute(&db) + .await?; + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + + let selected = create_and_queue(port, SELECTED).await?; + let other = create_and_queue(port, OTHER).await?; + + let read = mcp_call(port, "get_run", json!({ "id": selected })).await?; + let text = read["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default(); + assert!( + text.contains(SELECTED), + "a run of the selected flow is read: {read}" + ); + + let refused = mcp_call(port, "get_run", json!({ "id": other })).await?; + assert!( + refused["error"].is_object() && !refused.to_string().contains(OTHER), + "a run outside the selection is refused without reading it: {refused}" + ); + + Ok(()) +} diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index 22af9b641b..fc540fa095 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -512,8 +512,6 @@ pub async fn run_wait_result_internal( has_failure_module: bool, username: &str, ) -> error::Result<(Box, bool)> { - let mut result = None; - let mut success = false; let timeout = TIMEOUT_WAIT_RESULT.read().await.clone().unwrap_or(600); let timeout_ms = if timeout <= 0 { 2000 @@ -529,6 +527,36 @@ pub async fn run_wait_result_internal( username: username.to_string(), }; + let polled = poll_result( + db, + uuid, + w_id, + node_id_for_empty_return.as_deref(), + has_failure_module, + timeout_ms, + ) + .await?; + match polled { + Some(result) => { + g.done = true; + Ok(result) + } + None => Err(Error::ExecutionErr(format!("timeout after {}s", timeout))), + } +} + +/// Poll a job's result for up to `timeout_ms`: the flow's early-return node's when it has +/// one, otherwise the completed job's. `None` when it has none by then. Never cancels the job. +pub async fn poll_result( + db: &DB, + uuid: Uuid, + w_id: &str, + node_id_for_empty_return: Option<&str>, + has_failure_module: bool, + timeout_ms: u64, +) -> error::Result, bool)>> { + let mut result = None; + let mut success = false; let fast_poll_duration = *WAIT_RESULT_FAST_POLL_DURATION_SECS as u64 * 1000; let mut accumulated_delay = 0 as u64; // Once we observe the early_return node failed with a failure_module configured, @@ -536,9 +564,8 @@ pub async fn run_wait_result_internal( let mut early_return_failed_and_suppressed = false; loop { - if let Some(node_id_for_empty_return) = node_id_for_empty_return - .as_ref() - .filter(|_| !early_return_failed_and_suppressed) + if let Some(node_id_for_empty_return) = + node_id_for_empty_return.filter(|_| !early_return_failed_and_suppressed) { let result_and_success = get_result_and_success_by_id_from_flow( &db, @@ -607,12 +634,7 @@ pub async fn run_wait_result_internal( tokio::time::sleep(core::time::Duration::from_millis(delay)).await; } - if let Some(result) = result { - g.done = true; - Ok((result, success)) - } else { - Err(Error::ExecutionErr(format!("timeout after {}s", timeout))) - } + Ok(result.map(|result| (result, success))) } pub fn result_to_response(result: Box, success: bool) -> error::Result { diff --git a/backend/windmill-api/src/ai_session_tools/mod.rs b/backend/windmill-api/src/ai_session_tools/mod.rs index 045b87af39..15cdbd9db2 100644 --- a/backend/windmill-api/src/ai_session_tools/mod.rs +++ b/backend/windmill-api/src/ai_session_tools/mod.rs @@ -719,6 +719,9 @@ pub(crate) struct ToolOutcome { pub is_error: bool, } +#[cfg(feature = "mcp")] +pub(crate) use runs::wait_budget; + /// The card tools only MCP Apps clients draw; the chat draws its own cards. #[cfg(feature = "mcp")] pub(crate) use views::{allowed as view_allowed, definitions as view_definitions}; diff --git a/backend/windmill-api/src/ai_session_tools/runs.rs b/backend/windmill-api/src/ai_session_tools/runs.rs index c3df5f6008..998925b814 100644 --- a/backend/windmill-api/src/ai_session_tools/runs.rs +++ b/backend/windmill-api/src/ai_session_tools/runs.rs @@ -117,7 +117,7 @@ pub(super) async fn run_flow_preview( /// How many seconds a run tool waits before leaving the job in the background, from /// its `background` and `wait_seconds` arguments: 15 by default, 120 at most. -pub(super) fn wait_budget(tool_args: &Value) -> u64 { +pub(crate) fn wait_budget(tool_args: &Value) -> u64 { if tool_args.get("background").and_then(Value::as_bool) == Some(true) { return 0; } diff --git a/backend/windmill-api/src/jobs.rs b/backend/windmill-api/src/jobs.rs index 76f5440cdd..f8f527f1bc 100644 --- a/backend/windmill-api/src/jobs.rs +++ b/backend/windmill-api/src/jobs.rs @@ -8355,6 +8355,95 @@ pub async fn run_wait_result_script_by_path_internal( w_id: String, args: PushArgsOwned, ) -> error::Result { + let username = authed.username.clone(); + queue_script_by_path_for_result( + db.clone(), + run_query, + script, + authed, + user_db, + w_id.clone(), + args, + ) + .await? + .wait(&db, &w_id, &username) + .await +} + +/// A run queued by a caller that reads its result back. +pub struct QueuedRun { + pub uuid: Uuid, + early_return: Option, + has_failure_module: bool, + delete_after_use: Option, + delete_after_secs: Option, +} + +impl QueuedRun { + /// Until the run ends or `TIMEOUT_WAIT_RESULT` passes. The run is cancelled when the wait + /// times out or is dropped, as a disconnected HTTP caller is. + async fn wait(self, db: &DB, w_id: &str, username: &str) -> error::Result { + let result = run_wait_result( + db, + self.uuid, + w_id, + self.early_return, + self.has_failure_module, + username, + ) + .await; + handle_delete_after_completion( + db, + self.uuid, + w_id, + self.delete_after_use, + self.delete_after_secs, + ) + .await?; + result + } + + /// Up to `budget`: `None` when the run is still going by then. The run is never + /// cancelled, whether the budget runs out or the wait is dropped. + pub async fn wait_within( + &self, + db: &DB, + w_id: &str, + budget: std::time::Duration, + ) -> error::Result> { + let Some((result, success)) = windmill_api_jobs::poll_result( + db, + self.uuid, + w_id, + self.early_return.as_deref(), + self.has_failure_module, + budget.as_millis() as u64, + ) + .await? + else { + return Ok(None); + }; + handle_delete_after_completion( + db, + self.uuid, + w_id, + self.delete_after_use, + self.delete_after_secs, + ) + .await?; + result_to_response(result, success).map(Some) + } +} + +pub async fn queue_script_by_path_for_result( + db: sqlx::Pool, + run_query: RunJobQuery, + script: &RunnableRef, + authed: ApiAuthed, + user_db: UserDB, + w_id: String, + args: PushArgsOwned, +) -> error::Result { check_queue_too_long(&db, QUEUE_LIMIT_WAIT_RESULT.or(run_query.queue_limit)).await?; let db_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; @@ -8428,9 +8517,13 @@ pub async fn run_wait_result_script_by_path_internal( .await?; tx.commit().await?; - let wait_result = run_wait_result(&db, uuid, &w_id, None, false, &authed.username).await; - handle_delete_after_completion(&db, uuid, &w_id, delete_after_use, delete_after_secs).await?; - return wait_result; + Ok(QueuedRun { + uuid, + early_return: None, + has_failure_module: false, + delete_after_use, + delete_after_secs, + }) } pub async fn run_wait_result_script_by_hash( @@ -8836,28 +8929,51 @@ pub async fn run_wait_result_flow_by_path_internal( args: PushArgsOwned, w_id: String, ) -> error::Result { - check_queue_too_long(&db, run_query.queue_limit).await?; + queue_flow_by_path_for_result(&db, run_query, flow, &authed, user_db, args, &w_id) + .await? + .wait(&db, &w_id, &authed.username) + .await +} + +pub async fn queue_flow_by_path_for_result( + db: &DB, + run_query: RunJobQuery, + flow: &RunnableRef, + authed: &ApiAuthed, + user_db: UserDB, + args: PushArgsOwned, + w_id: &str, +) -> error::Result { + check_queue_too_long(db, run_query.queue_limit).await?; let flow_path = flow.path(); let userdb_authed = UserDbWithAuthed { db: user_db.clone(), authed: &authed.to_authed_ref() }; let flow_version_info = - get_latest_flow_version_info_for_path(Some(userdb_authed), &db, &w_id, &flow_path, true) + get_latest_flow_version_info_for_path(Some(userdb_authed), db, w_id, &flow_path, true) .await?; - run_flow_and_wait_result( - &authed, - &db, + let (uuid, early_return, has_failure_module, _) = run_flow( + authed, + db, + None, user_db, - &w_id, + w_id, flow_path, flow_version_info, run_query, args, None, ) - .await + .await?; + Ok(QueuedRun { + uuid, + early_return, + has_failure_module, + delete_after_use: None, + delete_after_secs: None, + }) } pub async fn run_wait_result_flow_by_version_get( diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index a691660b03..f93f77dca0 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -21,7 +21,7 @@ use windmill_mcp::server::{ use crate::auth::AuthCache; use crate::db::ApiAuthed; use crate::jobs::{ - run_wait_result_flow_by_path_internal, run_wait_result_script_by_path_internal, RunJobQuery, + queue_flow_by_path_for_result, queue_script_by_path_for_result, QueuedRun, RunJobQuery, }; use super::auto_generated_endpoints::all_tools; @@ -100,6 +100,45 @@ impl WindmillBackend { session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access)) } + /// A tool's answer for a run it queued: the result when the run ends within the session + /// tools' default wait, otherwise where to follow it. The run is never cancelled for + /// outliving the wait, nor when the client goes away before it ends. + async fn settle_run( + &self, + auth: &ApiAuthed, + workspace_id: &str, + path: &str, + queued: QueuedRun, + request: &McpRequest<'_>, + ) -> BackendResult { + let budget = Duration::from_secs(crate::ai_session_tools::wait_budget(&Value::Null)); + let done = queued + .wait_within(&self.db, workspace_id, budget) + .await + .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; + if let Some(response) = done { + return parse_response_body(response).await; + } + let id = queued.uuid; + let origin = request.origin(); + let mut ctx = session::Ctx::new( + auth, + workspace_id, + &self.base_internal_url, + session::access(SessionAccess::ReadOnly), + ); + ctx.origin = origin.as_deref(); + Ok(serde_json::json!({ + "id": id, + "status": "running", + "message": format!( + "Job {id} for {path} is taking a while and is now running in the background. \ + To inspect it, call get_run with id {id}." + ), + "run_page": ctx.page_url(&format!("/run/{id}")), + })) + } + pub fn new( db: DB, user_db: UserDB, @@ -295,7 +334,7 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - let result = run_wait_result_script_by_path_internal( + let queued = queue_script_by_path_for_result( self.db.clone(), RunJobQuery::default(), &script, @@ -307,7 +346,8 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - parse_response_body(result).await + self.settle_run(auth, workspace_id, path, queued, request) + .await } async fn run_flow( @@ -325,19 +365,49 @@ impl McpBackend for WindmillBackend { .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - let result = run_wait_result_flow_by_path_internal( - self.db.clone(), + let queued = queue_flow_by_path_for_result( + &self.db, RunJobQuery::default(), &flow, - auth.clone(), + auth, self.user_db.clone(), push_args, - workspace_id.to_string(), + workspace_id, ) .await .map_err(|e| ErrorData::internal_error(e.to_string(), None))?; - parse_response_body(result).await + self.settle_run(auth, workspace_id, path, queued, request) + .await + } + + async fn job_runnable( + &self, + auth: &ApiAuthed, + workspace_id: &str, + job_id: &str, + ) -> BackendResult> { + let ctx = session::Ctx::new( + auth, + workspace_id, + &self.base_internal_url, + session::access(SessionAccess::ReadOnly), + ); + let route = ctx.ws(&format!( + "jobs_u/get/{}?no_logs=true&no_code=true", + urlencoding::encode(job_id) + )); + let Ok(job) = ctx.get(&route).await else { + return Ok(None); + }; + let kind = match job["job_kind"].as_str() { + Some("script") => "script", + Some("flow") => "flow", + _ => return Ok(None), + }; + Ok(job["script_path"] + .as_str() + .map(|path| (kind, path.to_string()))) } async fn call_endpoint( diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 98831279d5..4f0af3e5a4 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -34,6 +34,13 @@ pub struct McpRequest<'a> { pub tool_name: &'a str, } +impl McpRequest<'_> { + /// The scheme and host the client reached, for links to Windmill pages. + pub fn origin(&self) -> Option { + crate::server::session::request_origin(self.headers) + } +} + /// How a script/flow listing is narrowed by path at the SQL layer, *before* the /// `ITEMS_FETCH_MAX_LIMIT` cap applies. /// @@ -194,7 +201,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { // Execution Operations // ───────────────────────────────────────────────────────────────── - /// Run a script and wait for result + /// Run a script, and wait a while for its result async fn run_script( &self, auth: &Self::Auth, @@ -204,7 +211,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { request: &McpRequest<'_>, ) -> BackendResult; - /// Run a flow and wait for result + /// Run a flow, and wait a while for its result async fn run_flow( &self, auth: &Self::Auth, @@ -214,6 +221,15 @@ pub trait McpBackend: Send + Sync + Clone + 'static { request: &McpRequest<'_>, ) -> BackendResult; + /// The type (`script` or `flow`) and path of what a job runs, read as the caller; + /// `None` when they cannot read the job or it runs neither. + async fn job_runnable( + &self, + auth: &Self::Auth, + workspace_id: &str, + job_id: &str, + ) -> BackendResult>; + /// Call an endpoint tool (generated API endpoint) async fn call_endpoint( &self, diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 6e18f36c7b..705d951c40 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -14,7 +14,7 @@ use crate::common::types::{ McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolableItem, WorkspaceId, }; -use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter}; +use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter, SessionAccess}; use crate::server::endpoints::{ endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, list_workspaces_tool, EndpointTool, }; @@ -68,6 +68,9 @@ const LIST_CHANGE_COALESCE: std::time::Duration = std::time::Duration::from_mill // Re-export from http crate for extracting request parts use http::request::Parts as HttpParts; +/// The session tool a selection is offered to follow the runs its tools start. +const GET_RUN: &str = "get_run"; + /// Maximum size in bytes for tool result text content. /// Anthropic enforces a 25,000 token limit per tool result. /// At ~3.5 bytes/token, 87,500 bytes is a safe upper bound. @@ -736,7 +739,11 @@ impl Runner { .filter(|(t, p)| !scope_config.granular || scope_config.is_allowed(t, p)) .collect(); let endpoint_tools = self.backend.all_endpoint_tools(); - let reserved: HashSet<&str> = endpoint_tools.iter().map(|t| t.name.as_ref()).collect(); + let reserved: HashSet<&str> = endpoint_tools + .iter() + .map(|t| t.name.as_ref()) + .chain([GET_RUN]) + .collect(); let pairs: Vec<(&str, &str)> = items.iter().map(|(t, p)| (*t, p.as_str())).collect(); let names = assign_tool_names(&pairs, &reserved); Ok(items @@ -876,6 +883,13 @@ impl Runner { &resource_types, )); } + + tools.extend( + self.backend + .session_tools(SessionAccess::ReadOnly) + .into_iter() + .find(|tool| tool.name == GET_RUN), + ); } // Add endpoint tools from the generated MCP tools, filtered by scope. @@ -950,6 +964,12 @@ impl Runner { )); } + if name == GET_RUN { + return self + .get_run(auth, workspace_id, scope_config, args, request) + .await; + } + // Resolve the tool name to (type, path, is_hub) let (tool_type, path, is_hub) = if !is_encoded_tool_name(name.as_ref()) { let segments = short_name_last_segments(name.as_ref()); @@ -1110,6 +1130,56 @@ impl Runner { } } + /// The session's `get_run`, for runs of the scripts and flows this token lists as tools. + async fn get_run( + &self, + auth: &B::Auth, + workspace_id: &str, + scope_config: &crate::common::scope::McpScopeConfig, + args: Value, + request: &McpRequest<'_>, + ) -> Result { + let id = args.get("id").and_then(Value::as_str).unwrap_or_default(); + let refused = || { + ErrorData::invalid_params( + format!("No run {id} of a script or flow this token runs"), + None, + ) + }; + let (item_type, path) = self + .backend + .job_runnable(auth, workspace_id, id) + .await? + .ok_or_else(refused)?; + let exact = [path.clone()]; + let listed = self + .backend + .list_runnable_paths( + auth, + workspace_id, + item_type, + scope_config.favorites, + Some(PathFilter::Patterns(&exact)), + ) + .await?; + if !listed.contains(&path) + || (scope_config.granular && !scope_config.is_allowed(item_type, &path)) + { + return Err(refused()); + } + let origin = request.origin(); + self.backend + .call_session_tool( + auth, + workspace_id, + GET_RUN, + args, + SessionAccess::ReadOnly, + origin.as_deref(), + ) + .await + } + /// List tools for a multi-workspace session: the synthetic `list_workspaces` /// tool plus every generic endpoint tool, each taking an explicit /// `workspace_id` argument. diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index 25d9da8dea..007af5f6a6 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -109,7 +109,7 @@ struct Caller { } /// `x-forwarded-*` first, since a proxy in front rewrites the host the request names. -fn request_origin(headers: &http::HeaderMap) -> Option { +pub(crate) fn request_origin(headers: &http::HeaderMap) -> Option { let header = |name: &str| { headers .get(name)