diff --git a/AGENTS.md b/AGENTS.md index b1db387c12..e2db88061a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -73,7 +73,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 and by the token forms' Build and run access, 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`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each 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 what 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 no model reads. Their `structuredContent` only names the call (`{tool, workspace_id, arguments}`): Codex's and ChatGPT's models read `structuredContent`, so card data there would cost context on every show call, and Claude hands the card no `_meta`, so the card then loads the data with `load_card`, an app-only tool (`visibility: ["app"]`) no host lists to the model. 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 (`load_card` to draw, refresh and re-read a draft, `cancel_job`, `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`). The show tools are hidden from a client that declares capabilities without the MCP Apps extension on each request (`2026-07-28`); every other client gets them, with a text fallback (status, a short result, the link), because the sessionless server cannot see an older client's `initialize` capabilities. +- **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 and by the token forms' Build and run access, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. A workspace role's MCP setting (EE, `docs/workspace-roles.md`) caps every token there, so it can change which of the two servers answers a connection to one workspace. 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`), and a member whose role cannot run is held to read-only, with no run tools (`session_ctx_with`, and `capabilitiesForRole` in the chat); the two copies of each 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 what 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 no model reads. Their `structuredContent` only names the call (`{tool, workspace_id, arguments}`): Codex's and ChatGPT's models read `structuredContent`, so card data there would cost context on every show call, and Claude hands the card no `_meta`, so the card then loads the data with `load_card`, an app-only tool (`visibility: ["app"]`) no host lists to the model. 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 (`load_card` to draw, refresh and re-read a draft, `cancel_job`, `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`). The show tools are hidden from a client that declares capabilities without the MCP Apps extension on each request (`2026-07-28`); every other client gets them, with a text fallback (status, a short result, the link), because the sessionless server cannot see an older client's `initialize` capabilities. - **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/.sqlx/query-2b95dc313f255a63c19cf48a0e8806bbf2e9c126bbe65384e72a47260e4eb7d4.json b/backend/.sqlx/query-2b95dc313f255a63c19cf48a0e8806bbf2e9c126bbe65384e72a47260e4eb7d4.json new file mode 100644 index 0000000000..7694e2f46e --- /dev/null +++ b/backend/.sqlx/query-2b95dc313f255a63c19cf48a0e8806bbf2e9c126bbe65384e72a47260e4eb7d4.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, role_overrides FROM workspace_settings\n WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "role_overrides", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "TextArray" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "2b95dc313f255a63c19cf48a0e8806bbf2e9c126bbe65384e72a47260e4eb7d4" +} diff --git a/backend/.sqlx/query-9ad042a9c1a1dc7f2ddeeccbffb560e27093ac7fc54b14070debe9155cb9f04f.json b/backend/.sqlx/query-9ad042a9c1a1dc7f2ddeeccbffb560e27093ac7fc54b14070debe9155cb9f04f.json new file mode 100644 index 0000000000..083aef5062 --- /dev/null +++ b/backend/.sqlx/query-9ad042a9c1a1dc7f2ddeeccbffb560e27093ac7fc54b14070debe9155cb9f04f.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT DISTINCT workspace_id FROM workspace_protection_rule\n WHERE workspace_id = ANY($1) AND rules & $2 <> 0", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "TextArray", + "Int4" + ] + }, + "nullable": [ + false + ] + }, + "hash": "9ad042a9c1a1dc7f2ddeeccbffb560e27093ac7fc54b14070debe9155cb9f04f" +} diff --git a/backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json b/backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json new file mode 100644 index 0000000000..8881f24f4d --- /dev/null +++ b/backend/.sqlx/query-cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT workspace_id, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "operator", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "workspace_role", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "TextArray" + ] + }, + "nullable": [ + false, + false, + false, + true + ] + }, + "hash": "cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b" +} diff --git a/backend/tests/mcp_role_access.rs b/backend/tests/mcp_role_access.rs new file mode 100644 index 0000000000..687c30a1d9 --- /dev/null +++ b/backend/tests/mcp_role_access.rs @@ -0,0 +1,261 @@ +//! A role's MCP setting is a maximum for every connection of its members, whatever their token +//! grants and whichever MCP URL they use, and an MCP token reaches nothing but MCP. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn mcp(port: u16, path: &str, token: &str, method: &str, params: Value) -> Value { + let body = reqwest::Client::new() + .post(format!("http://localhost:{port}{path}")) + .bearer_auth(token) + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", "2025-06-18") + .json(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + let data = body + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(&body); + serde_json::from_str(data).unwrap_or(Value::Null) +} + +#[cfg(feature = "enterprise")] +async fn tools(port: u16, path: &str, token: &str) -> Vec { + let list = mcp(port, path, token, "tools/list", json!({})).await; + list["result"]["tools"] + .as_array() + .unwrap_or_else(|| panic!("no tools in {list}")) + .iter() + .filter_map(|t| t["name"].as_str().map(str::to_string)) + .collect() +} + +#[cfg(feature = "enterprise")] +async fn set_access(db: &Pool, mcp: Value) { + sqlx::query( + "UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = 'test-workspace'", + ) + .bind(json!({"developer": {"mcp": mcp}})) + .execute(db) + .await + .unwrap(); + windmill_common::roles::invalidate_workspace_roles_cache("test-workspace"); +} + +#[cfg(feature = "enterprise")] +const WORKSPACE: &str = "/api/mcp/w/test-workspace/mcp"; +const DEFAULT: &str = "/api/mcp"; +#[cfg(feature = "enterprise")] +const GATEWAY: &str = "/api/mcp/gateway"; + +async fn token(db: &Pool, name: &str, email: &str, scopes: &[&str], bound: bool) { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, email, label, super_admin, scopes, workspace_id) + VALUES (encode(sha256($1::text::bytea), 'hex'), left($1::text, 10), $2, 'mcp', false, $3, $4)", + ) + .bind(name) + .bind(email) + .bind(scopes.iter().map(|s| s.to_string()).collect::>()) + .bind(bound.then_some("test-workspace")) + .execute(db) + .await + .unwrap(); +} + +#[cfg(feature = "enterprise")] +#[sqlx::test(fixtures("base"))] +async fn role_setting_caps_every_token(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES + ('test-workspace', 'test-user', 'export function main() { return 1 }', '{}', '', '', 'u/test-user/in_set', 7788401, 'bun', ''), + ('test-workspace', 'test-user', 'export function main() { return 1 }', '{}', '', '', 'u/test-user/outside', 7788402, 'bun', '');", + ) + .execute(&db) + .await?; + // test-user is a workspace admin: the setting of the role they hold applies to them too. + let admin = "test@windmill.dev"; + token(&db, "ROLEPLAIN_TOKEN", admin, &["mcp:all"], true).await; + token( + &db, + "ROLESESS_TOKEN", + admin, + &["mcp:all", "mcp:session"], + true, + ) + .await; + token(&db, "ROLEUNBOUND_TOKEN", admin, &["mcp:all"], false).await; + token( + &db, + "ROLEREAD_TOKEN", + admin, + &["mcp:all", "mcp:read_only"], + true, + ) + .await; + token( + &db, + "ROLESEL_TOKEN", + admin, + &["mcp:scripts:u/test-user/outside"], + true, + ) + .await; + + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + let has = |tools: &[String], name: &str| tools.iter().any(|t| t == name); + + let before = tools(port, WORKSPACE, "ROLEPLAIN_TOKEN").await; + assert!(has(&before, "listJobs"), "unconfigured: {before:?}"); + assert!(has( + &tools(port, WORKSPACE, "ROLESEL_TOKEN").await, + "outside" + )); + + set_access( + &db, + json!({"access": "runnables", "scripts": ["u/test-user/in_set"]}), + ) + .await; + for t in ["ROLEPLAIN_TOKEN", "ROLESESS_TOKEN"] { + for url in [WORKSPACE, DEFAULT, GATEWAY] { + assert_eq!(tools(port, url, t).await, ["in_set"], "{t} {url}"); + } + } + assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty()); + assert!(tools(port, WORKSPACE, "ROLEREAD_TOKEN").await.is_empty()); + let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move { + mcp( + port, + url, + token, + "tools/call", + json!({"name": name, "arguments": args}), + ) + .await + }; + for (name, refused) in [ + ("outside", "outside this token's selection"), + ("listJobs", ""), + ] { + let out = call(WORKSPACE, "ROLESESS_TOKEN", name, json!({})).await; + let msg = out["error"]["message"].as_str().unwrap_or_default(); + assert!(!msg.is_empty() && msg.contains(refused), "{name}: {out}"); + } + let ws = json!({"workspace_id": "test-workspace"}); + for (url, name) in [(DEFAULT, "list_workspace_items"), (GATEWAY, "listJobs")] { + let out = call(url, "ROLEUNBOUND_TOKEN", name, ws.clone()).await; + let msg = out["error"]["message"].as_str().unwrap_or_default(); + assert!( + msg.contains("/api/mcp/w/test-workspace/mcp"), + "{name}: {out}" + ); + } + + set_access(&db, json!({"access": "read_only"})).await; + for url in [WORKSPACE, DEFAULT, GATEWAY] { + let t = tools(port, url, "ROLEPLAIN_TOKEN").await; + assert!(has(&t, "list_workspace_items"), "{url}: {t:?}"); + assert!( + !has(&t, "listJobs") && !has(&t, "run_script"), + "{url}: {t:?}" + ); + } + assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty()); + let out = call( + DEFAULT, + "ROLEUNBOUND_TOKEN", + "run_script", + json!({"workspace_id": "test-workspace", "path": "u/test-user/in_set", "args": {}}), + ) + .await; + assert!( + out["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("read-only")), + "{out}" + ); + let out = call(DEFAULT, "ROLEUNBOUND_TOKEN", "list_workspaces", json!({})).await; + assert!(out["result"].to_string().contains("read only"), "{out}"); + + set_access(&db, json!({"access": "off"})).await; + assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty()); + assert_eq!( + tools(port, DEFAULT, "ROLESESS_TOKEN").await, + ["list_workspaces"] + ); + let out = call(DEFAULT, "ROLESESS_TOKEN", "list_workspace_items", ws).await; + assert!( + out["error"]["message"] + .as_str() + .is_some_and(|m| m.contains("no MCP access")), + "{out}" + ); + + // A role nothing defines any more fails closed where a setting exists. + set_access(&db, json!({"access": "read_run"})).await; + sqlx::query("UPDATE usr SET workspace_role = 'gone' WHERE workspace_id = 'test-workspace' AND username = 'test-user'") + .execute(&db) + .await?; + windmill_common::roles::invalidate_member_role_cache("test-workspace", "test-user"); + assert_eq!( + tools(port, DEFAULT, "ROLESESS_TOKEN").await, + ["list_workspaces"] + ); + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn mcp_tokens_reach_mcp_alone(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + token( + &db, + "MCPONLY_TOKEN", + "test@windmill.dev", + &["mcp:all", "mcp:session"], + true, + ) + .await; + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + let list = mcp(port, DEFAULT, "MCPONLY_TOKEN", "tools/list", json!({})).await; + assert!(list["result"]["tools"].is_array(), "{list}"); + + let client = reqwest::Client::new(); + for route in [ + "w/test-workspace/scripts/list", + "w/test-workspace/jobs/list", + "w/test-workspace/variables/list", + ] { + let status = client + .get(format!("http://localhost:{port}/api/{route}")) + .bearer_auth("MCPONLY_TOKEN") + .send() + .await? + .status(); + assert_eq!(status, 403, "{route}"); + } + + for (scopes, ok) in [ + (vec!["mcp:all", "scripts:read"], false), + (vec!["mcp:all", "if_jobs:filter_tags:deno"], true), + ] { + let status = client + .post(format!("http://localhost:{port}/api/users/tokens/create")) + .bearer_auth("SECRET_TOKEN") + .json(&json!({"label": "mixed", "scopes": scopes})) + .send() + .await? + .status(); + assert_eq!(status.is_success(), ok, "{scopes:?}: {status}"); + } + Ok(()) +} diff --git a/backend/windmill-api-auth/src/lib.rs b/backend/windmill-api-auth/src/lib.rs index d541a57e3f..a9388f7256 100644 --- a/backend/windmill-api-auth/src/lib.rs +++ b/backend/windmill-api-auth/src/lib.rs @@ -638,6 +638,27 @@ pub fn ensure_scopes_within_caller( ensure_scopes_within(authed.scopes.as_deref(), requested_scopes) } +/// Whether scopes mix MCP access with access to the regular API. The job tag fence narrows both. +pub fn mixes_mcp_scopes(scopes: Option<&[String]>) -> bool { + let mut scopes = scopes + .unwrap_or_default() + .iter() + .filter(|s| !s.starts_with("if_jobs:filter_tags:")) + .map(|s| s.starts_with("mcp:")); + scopes.next().is_some_and(|first| scopes.any(|s| s != first)) +} + +/// Refuses giving a token MCP scopes next to regular ones: an MCP token calls tools only, and a +/// regular scope on it opens routes its MCP access level does not limit. +pub fn ensure_mcp_scopes_unmixed(scopes: Option<&[String]>) -> error::Result<()> { + if mixes_mcp_scopes(scopes) { + return Err(Error::BadRequest( + "a token cannot mix MCP scopes with other scopes: create a token for each".to_string(), + )); + } + Ok(()) +} + /// Whether a credential holding `holder_scopes` covers `requested_scopes`, by the rules of /// [`ensure_scopes_within_caller`]. pub fn ensure_scopes_within( diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index 72b19748aa..15e53fb33c 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -3613,6 +3613,7 @@ async fn create_token( token_config.admin = Some(token_config.admin.unwrap_or(false)); windmill_api_auth::ensure_scopes_within_caller(&authed, token_config.scopes.as_deref())?; + windmill_api_auth::ensure_mcp_scopes_unmixed(token_config.scopes.as_deref())?; // Mirrors the MCP OAuth approve: a scoped token cannot mint superadmin access it may lack. if token_config.super_admin == Some(true) && authed @@ -4593,6 +4594,10 @@ async fn update_token_scopes( "token {token_prefix} not found, not owned by user, or not rescopable" ))); } + // A token that mixes them already stays editable. + if !windmill_api_auth::mixes_mcp_scopes(token.scopes.as_deref()) { + windmill_api_auth::ensure_mcp_scopes_unmixed(req.scopes.as_deref())?; + } let widens = windmill_api_auth::ensure_scopes_within(token.scopes.as_deref(), req.scopes.as_deref()) .is_err(); diff --git a/backend/windmill-api-workspaces/src/workspace_roles.rs b/backend/windmill-api-workspaces/src/workspace_roles.rs index b78c9c0deb..7f01262e5a 100644 --- a/backend/windmill-api-workspaces/src/workspace_roles.rs +++ b/backend/windmill-api-workspaces/src/workspace_roles.rs @@ -91,11 +91,8 @@ pub(crate) async fn write_role_overrides( ) -> Result<()> { let instance = instance_roles(db).await?; roles::validate_overrides(&instance, &overrides)?; - roles::check_frozen_overrides( - &instance, - &roles::load_role_overrides(db, w_id).await?, - &overrides, - )?; + let previous_overrides = load_role_overrides(db, w_id).await?; + roles::check_frozen_overrides(&instance, &previous_overrides, &overrides)?; let previous = roles::workspace_roles(db, w_id).await?; let removed: Vec = previous @@ -161,6 +158,21 @@ pub(crate) async fn write_role_overrides( .await?; tx.commit().await?; roles::invalidate_workspace_roles_cache(w_id); + roles::log_mcp_role_changes( + previous_overrides + .keys() + .chain( + overrides + .keys() + .filter(|n| !previous_overrides.contains_key(*n)), + ) + .map(|n| { + ( + previous_overrides.get(n).and_then(|o| o.mcp.as_ref()), + overrides.get(n).and_then(|o| o.mcp.as_ref()), + ) + }), + ); handle_deployment_metadata( &authed.email, @@ -280,7 +292,7 @@ pub(crate) async fn update_operator_settings( let entry = overrides.entry(OPERATOR_ROLE.to_string()).or_default(); entry.capabilities = roles::diff_capabilities(&base, &target); - if entry.label.is_none() && entry.capabilities == Default::default() { + if *entry == Default::default() { overrides.remove(OPERATOR_ROLE); } diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 242e3a6bb1..f1663da974 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -42187,6 +42187,26 @@ components: additionalProperties: type: boolean + McpRoleSetting: + type: object + description: The most a role's members may do through MCP, whatever their token grants (EE). Unset falls through to the layer below. + properties: + access: + type: string + enum: [follow_role, read_run, read_only, runnables, "off"] + description: "`follow_role` sets no limit, and lifts the instance's when a workspace states it. `runnables` offers the listed scripts and flows as tools and nothing else." + scripts: + type: array + description: With `runnables`, script paths, `*` or an exact path or a `/*` subtree. + items: + type: string + flows: + type: array + description: With `runnables`, flow paths, as for scripts. + items: + type: string + required: [access] + RoleDefinition: type: object description: One entry of the `workspace_roles` instance setting. @@ -42197,6 +42217,8 @@ components: type: string capabilities: $ref: "#/components/schemas/RoleCapabilitiesPatch" + mcp: + $ref: "#/components/schemas/McpRoleSetting" required: [name] RoleOverride: @@ -42206,6 +42228,8 @@ components: type: string capabilities: $ref: "#/components/schemas/RoleCapabilitiesPatch" + mcp: + $ref: "#/components/schemas/McpRoleSetting" RoleOverrides: type: object @@ -42222,6 +42246,8 @@ components: type: string capabilities: $ref: "#/components/schemas/RoleCapabilities" + mcp: + $ref: "#/components/schemas/McpRoleSetting" source: type: string enum: [instance, workspace] diff --git a/backend/windmill-api/src/ai_session_tools/gen/instructions.json b/backend/windmill-api/src/ai_session_tools/gen/instructions.json index e0dd1ee8b8..f40df8271a 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -317,7 +317,7 @@ "datatable.python3": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "datatable.go": "# Data tables: schema changes, migrations and permissions\n\nA data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL.\n\n## Changing the schema\n\nA data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table:\n\n- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it.\n- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else.\n\nWriting a migration:\n\n- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied.\n- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back.\n- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension.\n- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration.\n- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not.\n\n## A migration is not a draft\n\nA migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use:\n\n- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default;\n- or work in a workspace fork whose data table was cloned when the fork was created (\"Clone schema only\" or \"Clone schema and data\"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once.\n\nAltering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it.\n\n## Roles and permissions\n\nData table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise.\n\nA data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted:\n\n- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants;\n- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role;\n- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it;\n- a migration runs as the role its SQL declares on its first line, `-- role `, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do.\n\nRead the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles.\n\n\n# Datatable SQL SDK reference\n\nDatatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime.\n\n- A runnable accesses a datatable via `wmill.datatable()` (the default \"main\") or `wmill.datatable('')`, referencing tables as `schema.table`.\n- Use parameterized queries (the tagged template in TypeScript, `$1`/`$2` placeholders in Python) — never interpolate untrusted values into SQL strings.\n\n## TypeScript Datatable API (windmill-client)\n\nImport: `import * as wmill from 'windmill-client'`\n\nSQL statement object with query content, arguments, and execution methods\n```typescript\ntype SqlStatement = {\n /** Raw SQL content with formatted arguments */\n content: string;\n\n /** Argument values keyed by parameter name */\n args: Record;\n\n /**\n * Execute the SQL query and return results\n * @param params - Optional parameters including result collection mode\n * @returns Query results based on the result collection mode\n */\n fetch(\n params?: FetchParams // The union is for auto-completion\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOne(\n params?: Omit, \"resultCollection\">\n ): Promise>;\n\n /**\n * Execute the SQL query and return only the first row as a scalar value\n * @param params - Optional parameters\n * @returns First row of the query result\n */\n fetchOneScalar(\n params?: Omit<\n FetchParams<\"last_statement_first_row_scalar\">,\n \"resultCollection\"\n >\n ): Promise>;\n\n /**\n * Execute the SQL query without fetching rows\n * @param params - Optional parameters\n */\n execute(\n params?: Omit, \"resultCollection\">\n ): Promise;\n};\n```\n\n```typescript\n// Template tag function: sql`SELECT * FROM table WHERE id = ${id}`.fetch()\ninterface DatatableSqlTemplateFunction {\n // Tagged template usage:\n (strings: TemplateStringsArray, ...values: any[]): SqlStatement;\n query(sql: string, ...params: any[]): SqlStatement;\n};\n```\n\nCreate a SQL template function for PostgreSQL/datatable queries\n@param name - Database/datatable name (default: \"main\")\n@param opts.role - Connect as this data table role instead of the data table's default one.\n Only meaningful on a data table under roles, and only for a role you are a tenant of.\n@returns SQL template function for building parameterized queries\n@example\nlet sql = wmill.datatable()\nlet name = 'Robin'\nlet age = 21\nawait sql`\n SELECT * FROM friends\n WHERE name = ${name} AND age = ${age}::int\n`.fetch()\n@example\n// Read through a restricted role\nlet sql = wmill.datatable(\"main\", { role: \"analytics\" })\n```typescript\nfunction datatable(name: string = \"main\",\n opts?: DatatableOptions): DatatableSqlTemplateFunction\n```\n\n\n## Python Datatable API (wmill)\n\nImport: `import wmill`\n\n# Get a DataTable client for SQL queries.\n# \n# Args:\n# name: Database name (default: \"main\")\n# role: Connect as this data table role instead of the data table's default one.\n# \n# Returns:\n# DataTableClient instance\ndef datatable(name: str = 'main', *, role: Optional[str] = None) -> DataTableClient\n\n# Client for executing SQL queries against Windmill DataTables.\nclass DataTableClient:\n # Initialize DataTableClient.\n # \n # Args:\n # client: Windmill client instance\n # name: DataTable name\n # role: Data table role to connect as, or None for the data table's default\n def __init__(client: Windmill, name: str, role: Optional[str] = None)\n\n # Execute a SQL query against the DataTable.\n # \n # Args:\n # sql: SQL query string with $1, $2, etc. placeholders\n # *args: Positional arguments to bind to query placeholders\n # \n # Returns:\n # SqlQuery instance for fetching results\n def query(sql: str, *args) -> SqlQuery\n\n\n# Query result handler for DataTable and DuckLake queries.\nclass SqlQuery:\n # Initialize SqlQuery.\n # \n # Args:\n # sql: SQL query string\n # fetch_fn: Function to execute the query\n def __init__(sql: str, fetch_fn)\n\n # Execute query and fetch results.\n # \n # Args:\n # result_collection: Optional result collection mode\n # \n # Returns:\n # Query results\n def fetch(result_collection: str | None = None)\n\n # Execute query and fetch first row of results.\n # \n # Returns:\n # First row of query results\n def fetch_one()\n\n # Execute query and fetch first row of results. Return result as a scalar value.\n # \n # Returns:\n # First row of query result as a scalar value\n def fetch_one_scalar()\n\n # Execute query and don't return any results.\n # \n def execute()\n\n\n", "pipeline": "# Data pipeline authoring\n\nA **data pipeline** is NOT a flow. A flow is one runnable that orchestrates steps internally. A data pipeline is a set of **independent scripts**, each deployed on its own, that form a DAG by reading and writing shared **storage assets** (DuckLake tables, data tables, S3 objects, volumes, resources) and by declaring execution **triggers**. The pipeline is visualized and edited at `/pipeline/`; every node is a normal workspace script that happens to carry pipeline annotations. When the user asks for a \"data pipeline\" (or to \"ingest / transform / materialize\" data across steps), build pipeline-annotated scripts — do NOT build a flow.\n\n## Default to DuckDB + DuckLake\n\nA pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake:///` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else:\n\n- `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live).\n- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see \"Ingesting from Python / TypeScript\" below — rather than inventing a parallel store.\n\nDo not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal.\n\n## Ingesting from Python / TypeScript\n\nA node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second \"load the raw file\" node. One ingestion node, one table.\n\nPass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema:\n\n```python\n# pipeline\n# on schedule\nimport wmill\n\ndef main():\n rows = fetch_charges() # list[dict]\n lake = wmill.ducklake()\n lake.query(\"\"\"\n CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json($rows, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)\n \"\"\", rows=rows).fetch()\n```\n\n```ts\n// pipeline\n// on schedule\nimport * as wmill from \"windmill-client\"\n\nexport async function main() {\n const rows = await fetchCharges()\n const lake = wmill.ducklake()\n await lake`CREATE OR REPLACE TABLE stripe_charges AS\n SELECT unnest(from_json(${rows}, '[{\"id\":\"VARCHAR\",\"amount\":\"BIGINT\",\"created\":\"BIGINT\"}]'), recursive := true)`.fetch()\n}\n```\n\n- Use `INSERT INTO
SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first.\n- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/
`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms.\n- `wmill.ducklake(\"\")` targets a non-default catalog; `wmill.datatable(\"\")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above).\n- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`.\n\n## Storage prerequisites\n\nA DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build.\nDrafting the annotated scripts does not require storage, but the pipeline can't ingest, materialize, or read its assets until it exists. So if there is none (or the user hits \"storage not configured\" errors), say so and give the right next step **by role**:\n\n- a workspace **admin** sets it up in Workspace settings → Object Storage (add an S3/Azure/GCS storage), then adds a DuckLake catalog on top of it;\n- anyone **without admin rights** should ask a workspace admin to configure object storage + a DuckLake catalog.\n\nNever hand back a DuckLake pipeline that cannot run without flagging the missing storage and pointing to who sets it up.\n\n## What makes a script a pipeline node\n\nA script joins the pipeline when its source begins with the `pipeline` annotation as a top-of-file comment, **written in the script's own comment syntax** — `//` for TS/JS (bun), `--` for SQL (DuckDB/Postgres), `#` for Python/Bash. So it's `-- pipeline` in a DuckDB node, `# pipeline` in a Python node, `// pipeline` in a bun node. Every annotation below uses that same prefix (the `//` shown is the TS form). All other wiring is expressed as annotation comments near the top of the file:\n\n- `// on ` — declares an execution-DAG **input** (what triggers/feeds this node). `` is either:\n - an **asset URI** (the node runs when that asset is produced upstream): `ducklake://main/orders`, `datatable://main/users`, `$res:f/folder/my_resource`, `volume://name/path`, or an S3 object (see the S3 storage-form rule below).\n - a **native trigger kind**: `schedule`, `webhook`, `email`, `kafka`, `mqtt`, `amqp`, `nats`, `postgres`, `sqs`, `gcp`, or `data_upload` (a user-uploaded S3 file). For these the actual trigger row (cron, topic, …) is created separately; the annotation only declares the binding. **`data_upload` is special**: there is no trigger row — the node instead declares an **`S3Object` input parameter** fed by the auto-generated upload picker; it never hard-codes a key. Any language can be the `data_upload` node:\n - Python (has `import wmill`): `def main(file: wmill.S3Object):` then `wmill.load_s3_file(file)`; TS (has `import * as wmill from \"windmill-client\"`): `export async function main(file: wmill.S3Object)`. Qualify the type as `wmill.S3Object` (or add `from wmill import S3Object` / `import { S3Object } from \"windmill-client\"`) — a bare `S3Object` is undefined.\n - **DuckDB** takes the s3object arg via a `-- $ (s3object)` declaration and reads it directly, so a single DuckDB node can ingest **and** materialize:\n ```\n -- pipeline\n -- on data_upload\n -- materialize ducklake://main/raw_uploads\n -- $file (s3object)\n SELECT * FROM read_csv($file)\n ```\n- **Outputs** are inferred from what the body writes — a `CREATE TABLE`, a `wmill.writeS3File(...)`, a DuckLake/datatable write. To declare a managed output explicitly, use `// materialize `.\n- Optional badges: `// partitioned `, `// freshness ` (e.g. `1h`), `// tag `, `// retry [delay]`, `// data_test ...` (managed DuckLake targets only — deploy rejects it beside a `dbt://` one), `// measure = [where ]` and `// dimension = ` (see \"Declared metrics\" below).\n\n## S3 object wiring (storage form matters)\n\nAn `s3://` URI's first slashes select the **storage**, not part of the key — get this wrong and the producer/consumer edge silently won't connect:\n\n- `s3:///` (**triple** slash, empty first segment) = the **default** workspace storage. A downstream node reading or triggering on that object uses `s3:///` — e.g. DuckDB `-- on s3:///orders/2024.parquet` and `read_parquet('s3:///orders/2024.parquet')`.\n- `s3:///` (**double** slash, non-empty first segment) = a **named secondary** storage called `` — so `s3://ingest/x` means storage `ingest`, key `x`, NOT key `ingest/x`. Only use this when the object genuinely lives in a configured secondary storage; never invent a bucket/storage name for a default-storage object (it breaks the edge).\n\nTo make the producer side visible to lineage, a Python/TS node MUST pass the **`S3Object` form**, not a bare key string: Python `wmill.write_s3_file(wmill.S3Object(s3=\"\"), data)` (or the import-free dict `{\"s3\": \"\"}`), TS `wmill.writeS3File({ s3: \"\" }, data)`. That records the default-storage asset `/`, which a downstream `s3:///` reader connects to (same key both sides). A bare `write_s3_file(\"\", ...)` records **no** asset and produces **no** edge. Add `storage=\"\"` only for a named secondary storage.\n\nThe key must be a **string literal** — the graph parser is static and cannot follow a variable, f-string, or computed path, so `write_s3_file(wmill.S3Object(s3=key_var), ...)` records no edge. Inline the literal (`s3=\"events/user_events.parquet\"`) on both the writing and reading node. The same rule applies to every asset URI in an annotation or SDK call (`ducklake://`, `datatable://`, `s3://`): write them literally, not via a variable.\n\n## Materialize (the managed output)\n\n> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake:///
`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see \"Ingesting from Python / TypeScript\") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table.\n>\n> The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt:////`, where `` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt:////` fires when the ingestion node completes.\n\nA managed `// materialize ducklake:///
` tells the runtime to write the node's output table **for you**: write the body as a single `SELECT` and the runtime wraps it in the create/replace — do **not** also write your own `CREATE TABLE` / `INSERT`. (The opposite holds for the `dbt://` target above: there the node writes its own DDL and the strategies below do not apply.)\n\nA target that names no table — `// materialize`, `// materialize ducklake://`, or options alone such as `// materialize key=id` — writes the table named after the script: node `f/shop/orders_daily` materializes `ducklake://main/orders_daily` (characters other than letters, digits and `_` become `_`, and a name starting with a digit gets a leading `_`). Name the node after the table it produces and the bare form is enough; write the full target when the table's name differs from the node's, and use that same name in every downstream `// on` and read.\n\nWrite strategy:\n\n- no option → **replace** the whole table each run (full refresh; the only mode whose output columns may change);\n- `// materialize append` → INSERT-append rows (incremental);\n- `// materialize key=` → merge/upsert on ``.\n\n`// materialize manual ` opts **out** of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage.\n\n`materialize` pairs with partitioning for incremental pipelines: a `// partitioned ` node runs **once per partition** (append/merge into a fixed-schema table). The `{partition}` token, usable in any asset URI **and** in the body SQL, is replaced at run time by the current partition's **identity string**:\n\n- To filter the source to the active slice on a time grain, use the runtime-injected macro: `WHERE wm_partition() = {partition}`. `wm_partition(ts)` buckets a timestamp in exactly the identity format the runtime uses for daily/hourly/weekly/monthly, so it always matches; never hand-write a `strftime` format.\n- Do NOT write `= TIMESTAMP {partition}`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at run time.\n- For `dynamic` partitioning the identity is the caller-supplied key (not a timestamp, no macro), so filter on it directly: `WHERE = {partition}`.\n\n`materialize` is an output **declaration** on a node — not a command. There is no \"materialize run\".\n\n## Declared metrics (`measure` / `dimension`)\n\nOn a node that materializes a DuckLake table, `// measure = [where ]` names the canonical way to aggregate that table (e.g. `// measure revenue = sum(amount) where not is_refund`), and `// dimension = ` names a way to slice it (e.g. `// dimension region = region`, `// dimension month = date_trunc('month', ordered_at)`). They execute nothing: they are catalogued at deploy so the editor and other agents reuse the definition instead of re-deriving it and silently disagreeing.\n\n- Keep the predicate in the `where` clause rather than folding it into the aggregate: it is rendered as ` FILTER (WHERE )`, which is what lets two measures with different predicates share one GROUP BY.\n- DuckLake-only, and only meaningful next to `// materialize`.\n- Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures — an obvious `count(*)` earns nothing.\n- To use a metric another node declares, read that node and reuse its exact expression rather than guessing it.\n\n## How to build one\n\n1. Put every node in the **same folder**: `f//`. The folder is the pipeline.\n2. Write each node as its own script. Default to `duckdb` materializing into DuckLake (see \"Default to DuckDB + DuckLake\" above); pick `postgresql`, `bun`, or `python3` only when that section says the work calls for it.\n3. Start each body with `// pipeline`, then the `// on` input declarations, then the transform that writes the output.\n4. **Chain nodes by asset URI**: read an upstream node's output asset, then `// on ` in the downstream node so the edge forms. Reuse exact asset paths from existing nodes rather than inventing parallel ones.\n5. Never guess the columns of a file or table you have not seen: read them first with a query that writes nothing, such as `DESCRIBE SELECT * FROM read_csv('s3:///raw/orders/*.csv')` or `ATTACH 'ducklake://main' AS lake; DESCRIBE lake.orders`, and use those exact column names. A test run of a node that materializes a table writes that table into the workspace's lake: test-run such a node only while its table does not exist yet, and ask before running one that would replace a table already there.\n6. Don't deploy nodes unless the user asks to. A pipeline only \"runs\" once its scripts are deployed and their triggers exist.\n\n## Example (DuckDB → DuckLake, scheduled ingest + downstream transform)\n\nNode `f/sales/orders_ingest` (runs on a schedule, materializes a DuckLake table):\n\n```sql\n-- pipeline\n-- on schedule\n-- materialize ducklake://main/orders\nSELECT * FROM read_csv('s3:///raw/orders/*.csv')\n```\n\nNode `f/sales/orders_daily` (runs when `orders` is produced, writes a rollup):\n\n```sql\n-- pipeline\n-- on ducklake://main/orders\n-- materialize ducklake://main/orders_daily\nATTACH 'ducklake://main' AS lake;\nSELECT date_trunc('day', ts) AS day, count(*) AS n\nFROM lake.orders GROUP BY 1\n```\n\nA node reads a DuckLake table only through a lake it attaches itself (`ATTACH 'ducklake://' AS lake;`, then `lake.
`); the materialize target is attached by the runtime under a name of its own, so `ducklake.main.
` does not resolve.\n", - "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/` or `flow/`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ : { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", + "workspace_settings": "# Workspace settings\n\nEverything an admin sets on the Workspace settings page is one document: a mapping of top-level\nkeys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can\nread or change it.\n\n## Applying a document\n\n- A partial document changes only the keys it states; every key it omits is left as it is.\n- Each key is replaced whole, so read its current value and send it back edited: a nested object\n given with one field replaces the stored object with that one field.\n- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`.\n- Each setting is written through the same path the settings page uses, with the same validation\n and audit log. The writes are not one transaction: when one fails the apply stops, and the\n error says what was already written.\n- A dry run reports the changes, as `before` / `after` per key, without writing anything.\n- `name` is never applied: rename a workspace on the settings page. `color` is applied only when\n set to a value, so `null` does not clear it.\n- A key the server does not know is ignored and named in the warnings: check them, since a typo\n otherwise reads as \"nothing to change\".\n- A setting this edition does not offer (Enterprise only) is refused, by the dry run too.\n\n## Secrets\n\n`webhook` (its URL usually carries the receiver's token) and `slack_oauth_client_secret` are the\nsecrets. A read shows `__SENSITIVE_AND_UNCHANGED__` in place\nof a set secret; sending that placeholder back keeps the stored value. A value starting with\n`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key\nis left unchanged with a warning; any other value is taken as plaintext. Never\nwrite a secret you were not given: keep the placeholder.\n\n## Keys\n\n| Key | Value |\n|---|---|\n| `auto_invite` | `{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. |\n| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path?, muted_on_ui_runs? }`, `path` being `script/` or `flow/`. `muted_on_ui_runs` (error handler only) skips jobs started from the UI. |\n| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. |\n| `webhook` | URL POSTed a JSON event on every change to the workspace's items. |\n| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. |\n| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. |\n| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. |\n| `datatable` | `{ datatables: { : { database: { resource_type, resource_path } } } }`, both required: `resource_type: postgresql` with `resource_path` a Postgres resource's path, or `instance`, or `external_instance` (Enterprise only), with `resource_path` the name of a database a superadmin set up. A fork's entry can instead be `{ reference: { workspace_id, datatable } }`, pointing at its parent's data table; keep it as is. `main` is the one scripts use by default. Role permissions are `datatable_permissions`. |\n| `datatable_permissions` | `{ : { default_role, roles: { : [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/`, `g/`, `f/` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. |\n| `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`, `RequireSso` (an account signing in with a password, other than a bypasser, cannot join, and no member can be switched to a password login; members already signing in with a password are not removed). A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |\n| `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. |\n| `dbt_warehouses` | dbt warehouse connections. |\n| `default_app` | Path of the app shown as the workspace home. |\n| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |\n| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |\n| `role_overrides` | `{ : { label?, capabilities, mcp?, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. `mcp` (Enterprise) caps what the role's members may do through MCP: `{ access: follow_role \\| read_run \\| read_only \\| runnables \\| off, scripts?, flows? }`, the paths only with `runnables`. |\n| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |\n| `mute_critical_alerts` | Mute the workspace's critical alerts. |\n| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |\n| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. |\n| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. |\n| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. |\n| `guest_jwt_public_key`, `guest_jwt_jwks_url` | The key that signs guest JWTs for apps set to Guests. |\n| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. |\n| `color` | Workspace color, `#rrggbb`. |\n", "display": "# Rich results\n\nWindmill renders a script's or flow's return value according to its shape: on run pages, in the\nscript and flow editors, in app result displays and in AI chat run cards. Anything that matches none\nof the shapes below is shown as JSON.\n\n## Shapes\n\n- `{ \"table-row-object\": [{...}, ...] }`, or a bare array of objects: a table whose columns are the\n union of the objects' keys.\n- `{ \"table-col\": { \"col\": [...], ... } }`, or a bare object of equal-length arrays: a table built\n column by column.\n- `{ \"table-row\": [[\"col\", ...], [v, ...], ...] }`: a table whose first row holds the column names.\n- `{ \"chart\": {...} }`: a bar, line, pie or scatter chart drawn from rows (schema below). A `chart`\n value the schema rejects is shown as JSON, not as a broken chart.\n- `{ \"markdown\": \"...\" }` (or `md`): rendered markdown.\n- `{ \"html\": \"...\" }`: sanitized HTML.\n- `{ \"png\": \"\" }`, likewise `jpeg`, `gif`, `svg`: an image. `{ \"pdf\": \"\" }`: a PDF.\n- `{ \"file\": \"\", \"filename\": \"report.csv\" }`: a download.\n- `{ \"map\": { \"lat\": 0, \"lon\": 0, \"zoom\": 3, \"markers\": [{ \"lat\": 0, \"lon\": 0, \"title\": \"...\" }] } }`:\n a map.\n- `{ \"s3\": \"path/to/key\" }`: an object in the workspace storage, previewed by type.\n- `{ \"render_all\": [ ... ] }`: each item rendered in turn with the rules above.\n\nEach shape is an object with that one key (plus `filename` for a file, and an optional `storage` for\n`s3`). A result carrying any other key beside it is shown as JSON.\n\n## Large results\n\nA result stored above about 90 KB is not sent with the run: the run page and the editors offer it\nas a JSON download, with a Load button that draws it on request. A `render_all` lists up to 100 of\nits elements with their type and size, counts the rest, and loads them ten at a time. To have a large result previewed without a\nclick, write the content to the workspace storage and return `{ \"s3\": \"path/to/key\" }`, which is\npreviewed by type; for a generated image, also keep it small (a JPEG, or fewer pixels) when it only\nneeds to be looked at.\n\n## Choosing one\n\nA chart answers a question at a glance: a trend over time (line), a comparison across categories\n(bar), parts of a whole with few parts (pie), or a relation between two numbers (scatter). A table\nanswers lookups and holds the exact values. When both help, return both in a `render_all`: the chart\nfirst, then the table of the same rows.\n\nKeep a chart to what it shows well: at most 8 series. A pie with more than 8 slices keeps the 7\nlargest and folds the rest into \"Other\", so prefer a bar chart for many categories. Aggregate before\ncharting: a chart of thousands of raw points says less than one of the totals per day.\n\n\n### Chart and table schema\n\nA chart or table value, as JSON Schema. Beyond it: `x` and every `y` must be columns of `data`, `y` columns hold numbers, a scatter chart's `x` column holds numbers, and a pie chart takes exactly one `y`.\n\n```json\n{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"anyOf\":[{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]},{\"type\":\"object\",\"properties\":{\"render_all\":{\"description\":\"Several items shown one after another\",\"minItems\":1,\"maxItems\":10,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"object\",\"properties\":{\"chart\":{\"type\":\"object\",\"properties\":{\"type\":{\"description\":\"bar or line for categories or time, pie for parts of a whole, scatter for two numeric columns\",\"type\":\"string\",\"enum\":[\"bar\",\"line\",\"pie\",\"scatter\"]},\"title\":{\"type\":\"string\"},\"data\":{\"description\":\"The rows to plot, the same shape as a table-row-object result\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}},\"x\":{\"description\":\"Column holding the category, label or date of each row (bar, line, pie), or the numeric x value (scatter)\",\"type\":\"string\"},\"y\":{\"description\":\"Numeric column, or columns, to plot: one series each. A pie takes exactly one\",\"anyOf\":[{\"type\":\"string\"},{\"minItems\":1,\"maxItems\":8,\"type\":\"array\",\"items\":{\"type\":\"string\"}}]},\"stacked\":{\"description\":\"bar and line: stack the series\",\"type\":\"boolean\"},\"horizontal\":{\"description\":\"bar: draw the bars horizontally\",\"type\":\"boolean\"},\"x_label\":{\"type\":\"string\"},\"y_label\":{\"type\":\"string\"}},\"required\":[\"type\",\"data\",\"x\",\"y\"],\"additionalProperties\":false}},\"required\":[\"chart\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row-object\":{\"description\":\"Rows as objects; the columns are the union of their keys\",\"minItems\":1,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"description\":\"One row: column name to value (string, number, boolean or null)\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row-object\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-col\":{\"description\":\"Columns: column name to its values, all the same length\",\"type\":\"object\",\"propertyNames\":{\"type\":\"string\"},\"additionalProperties\":{\"maxItems\":5000,\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-col\"],\"additionalProperties\":false},{\"type\":\"object\",\"properties\":{\"table-row\":{\"description\":\"Rows as arrays; the first row holds the column names\",\"minItems\":2,\"maxItems\":5000,\"type\":\"array\",\"items\":{\"type\":\"array\",\"items\":{\"anyOf\":[{\"type\":\"string\"},{\"type\":\"number\"},{\"type\":\"boolean\"},{\"type\":\"null\"}]}}}},\"required\":[\"table-row\"],\"additionalProperties\":false}]}}},\"required\":[\"render_all\"],\"additionalProperties\":false}]}\n```\n\nBar chart, one series per y column:\n\n```json\n{\n \"chart\": {\n \"type\": \"bar\",\n \"title\": \"Runs per day\",\n \"data\": [\n {\n \"day\": \"2026-11-10\",\n \"success\": 42,\n \"failure\": 3\n },\n {\n \"day\": \"2026-11-11\",\n \"success\": 51,\n \"failure\": 1\n }\n ],\n \"x\": \"day\",\n \"y\": [\n \"success\",\n \"failure\"\n ],\n \"stacked\": true\n }\n}\n```\n\nPie chart (exactly one y column):\n\n```json\n{\n \"chart\": {\n \"type\": \"pie\",\n \"data\": [\n {\n \"language\": \"python3\",\n \"scripts\": 18\n },\n {\n \"language\": \"bun\",\n \"scripts\": 25\n }\n ],\n \"x\": \"language\",\n \"y\": \"scripts\"\n }\n}\n```\n\nA chart and a table together:\n\n```json\n{\n \"render_all\": [\n {\n \"chart\": {\n \"type\": \"line\",\n \"data\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180\n }\n ],\n \"x\": \"hour\",\n \"y\": \"p95_ms\",\n \"y_label\": \"ms\"\n }\n },\n {\n \"table-row-object\": [\n {\n \"hour\": \"10:00\",\n \"p95_ms\": 120,\n \"jobs\": 310\n },\n {\n \"hour\": \"11:00\",\n \"p95_ms\": 180,\n \"jobs\": 402\n }\n ]\n }\n ]\n}\n```\n", "code_mode": "# Solving a task with code\n\nWhen the user asks for something done against the systems their workspace connects to (look\nsomething up in an API, move data, check a status), answer it with a Windmill script run as a\npreview: it executes on the workspace's workers, with its resources. A script that worked can be\nsaved and run as is the next time.\n\n1. **Look for a saved script first**, by the user's words and by the system the task touches. If\n one fits, run it rather than writing new code; if one nearly fits, offer to change it rather\n than writing a near-duplicate.\n2. **Otherwise write one script and run it as a preview.** Do the fetching, filtering and\n combining in the code, and return only what answers the task, not raw API payloads. Take\n credentials as a resource-typed `main` parameter, passed as `$res:` when running, never\n as a token in the code. Give `main` typed parameters for whatever would change between runs,\n so the script is reusable.\n3. **Offer to save it** when the task is likely to come back, without saving it unasked. Saving\n makes a draft, deployed only when the user asks; from then on it is an ordinary script.\n\nFor a third-party API, look up its hub integration for its resource type and how to call it.\n\n" } diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index 76af37f900..00709b5fbe 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -14,8 +14,8 @@ use windmill_mcp::common::types::{ FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo, }; use windmill_mcp::server::{ - BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, McpRequest, PathFilter, - RunOutcome, SessionAccess, Tool, + admits, session_limit, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, + McpLimit, McpRequest, PathFilter, RunOutcome, SessionAccess, Tool, }; use crate::auth::{AuthCache, Tokened}; @@ -92,7 +92,11 @@ impl WindmillBackend { auth: &'a ApiAuthed, w_id: &'a str, access: SessionAccess, - ) -> session::Ctx<'a> { + ) -> BackendResult> { + let access = match self.mcp_limit(auth, w_id).await? { + Some(limit) => access.min(session_limit(w_id, &limit)?), + None => access, + }; let access = match access { SessionAccess::Full => { let rules = get_protection_rules(w_id, &self.db).await.ok(); @@ -109,7 +113,12 @@ impl WindmillBackend { } else { access }; - session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access)) + Ok(session::Ctx::new( + auth, + w_id, + &self.base_internal_url, + session::access(access), + )) } pub fn new( @@ -550,13 +559,30 @@ impl McpBackend for WindmillBackend { all_tools() } + async fn mcp_limit( + &self, + auth: &ApiAuthed, + workspace_id: &str, + ) -> BackendResult> { + super::role_access::mcp_limit(&self.db, auth, workspace_id).await + } + + async fn workspace_accesses( + &self, + auth: &ApiAuthed, + workspaces: &[WorkspaceInfo], + access: SessionAccess, + ) -> BackendResult> { + super::role_access::workspace_accesses(&self.db, &auth.email, workspaces, access).await + } + async fn session_instructions( &self, auth: &ApiAuthed, workspace_id: &str, access: SessionAccess, ) -> BackendResult { - let ctx = self.session_ctx_with(auth, workspace_id, access).await; + let ctx = self.session_ctx_with(auth, workspace_id, access).await?; let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await; Ok(session::session_instructions(&ctx, &profile).await) } @@ -570,10 +596,10 @@ impl McpBackend for WindmillBackend { auth: &ApiAuthed, workspace_id: &str, access: SessionAccess, - ) -> String { - let ctx = self.session_ctx_with(auth, workspace_id, access).await; + ) -> BackendResult { + let ctx = self.session_ctx_with(auth, workspace_id, access).await?; let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await; - session::workspace_context(&ctx, &profile, session::access(access)).await + Ok(session::workspace_context(&ctx, &profile, session::access(access)).await) } fn session_tools(&self, access: SessionAccess) -> Vec { @@ -593,7 +619,7 @@ impl McpBackend for WindmillBackend { access: SessionAccess, origin: Option<&str>, ) -> BackendResult { - let mut ctx = self.session_ctx_with(auth, workspace_id, access).await; + let mut ctx = self.session_ctx_with(auth, workspace_id, access).await?; ctx.origin = origin; session::call_session_tool(&ctx, name, args).await } @@ -621,6 +647,40 @@ fn serves_session_toolset(scopes: &[String]) -> bool { .any(|scope| [SESSION_SCOPE, "mcp:read_only", "mcp:read_run"].contains(&scope.as_str())) } +/// Whether the session server answers a request to one workspace, given what its URL and token +/// say (`session`) and its member's role: a role limited to chosen scripts and flows is served +/// them by the tools server whatever the token, and an `mcp:all` token under any other limit the +/// session toolset, as endpoint tools are never served under one. +async fn served_under_limit( + db: &DB, + extensions: &http::Extensions, + session: bool, +) -> Result { + let (Some(WorkspaceId(w_id)), Some(authed)) = ( + extensions.get::(), + extensions.get::(), + ) else { + return Ok(session); + }; + let limit = super::role_access::mcp_limit(db, authed, w_id) + .await + .map_err(|e| { + ( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + e.message.into_owned(), + ) + .into_response() + })?; + Ok(match limit { + None => session, + Some(McpLimit::Runnables { .. }) => false, + Some(_) => { + let scopes = authed.scopes.as_deref().unwrap_or_default(); + session || admits(scopes, scopes.iter().any(|s| s == "mcp:all")) + } + }) +} + /// The path of a workspace-less MCP URL, when it is not the tools server's /// `/api/mcp/gateway`: each URL is its own OAuth protected resource. #[derive(Clone, Copy)] @@ -856,7 +916,7 @@ pub async fn setup_mcp_server( let cancellation_token = CancellationToken::new(); let session_manager = Arc::new(LocalSessionManager::default()); - let backend = WindmillBackend::new(db, user_db, base_internal_url, auth_cache); + let backend = WindmillBackend::new(db.clone(), user_db, base_internal_url, auth_cache); let session_runner = SessionRunner::new(backend.clone()); let runner = Runner::new(backend); @@ -891,13 +951,20 @@ pub async fn setup_mcp_server( "/", axum::routing::any({ let (service, session_service) = (service.clone(), session_service.clone()); + let db = db.clone(); move |request: Request| { let (service, session_service) = (service.clone(), session_service.clone()); + let db = db.clone(); async move { use tower::ServiceExt; let session = request.extensions().get::().is_some_and(|a| { serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) }); + let session = match served_under_limit(&db, request.extensions(), session).await + { + Ok(session) => session, + Err(refused) => return refused, + }; let response = if session { session_service.oneshot(request).await } else { @@ -918,9 +985,15 @@ pub async fn setup_mcp_server( "/mcp", axum::routing::any(move |mut request: Request| { let (service, session_service) = (service.clone(), session_service.clone()); + let db = db.clone(); async move { use tower::ServiceExt; - let response = if request.extensions().get::().is_some() { + let session = request.extensions().get::().is_none(); + let session = match served_under_limit(&db, request.extensions(), session).await { + Ok(session) => session, + Err(refused) => return refused, + }; + let response = if !session { request.extensions_mut().insert(NoEndpointTools); service.oneshot(request).await } else { diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index 9d715612e4..fe5caf9931 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -6,6 +6,7 @@ mod auto_generated_endpoints; mod core; pub mod external_idp; +mod role_access; mod session; mod utils; diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index 2f84c4201c..97b3d1e518 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -981,6 +981,7 @@ async fn oauth_approve_inner( if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { scopes.push(SESSION_SCOPE.to_string()); } + windmill_api_auth::ensure_mcp_scopes_unmixed(Some(&scopes))?; // The approver's own token bounds what it may grant: a scope-restricted MCP // token must not approve a broader one (e.g. mcp:scripts:f/x -> mcp:all). An diff --git a/backend/windmill-api/src/mcp/role_access.rs b/backend/windmill-api/src/mcp/role_access.rs new file mode 100644 index 0000000000..736bcad42a --- /dev/null +++ b/backend/windmill-api/src/mcp/role_access.rs @@ -0,0 +1,153 @@ +//! What a member's workspace role lets an MCP connection do. See `roles::McpRoleSetting`. + +use std::collections::HashMap; + +use windmill_api_auth::ApiAuthed; +use windmill_common::{ + roles::{self, McpRoleAccess, McpRoleSetting, RoleCapabilities}, + workspaces::ProtectionRules, + DB, +}; +use windmill_mcp::server::{BackendResult, ErrorData, McpLimit, SessionAccess, WorkspaceInfo}; + +fn limit_of(setting: &McpRoleSetting) -> Option { + match setting.access { + McpRoleAccess::FollowRole => None, + McpRoleAccess::ReadRun => Some(McpLimit::ReadAndRun), + McpRoleAccess::ReadOnly => Some(McpLimit::ReadOnly), + McpRoleAccess::Runnables => Some(McpLimit::Runnables { + scripts: setting.scripts.clone(), + flows: setting.flows.clone(), + }), + McpRoleAccess::Off => Some(McpLimit::Off), + } +} + +/// Refuses on an error, unlike `can_run`: an unread limit is one the admin still relies on. +pub(super) async fn mcp_limit( + db: &DB, + authed: &ApiAuthed, + workspace_id: &str, +) -> BackendResult> { + roles::caller_mcp_limit(db, workspace_id, authed) + .await + .map(|s| s.as_ref().and_then(limit_of)) + .map_err(|e| { + tracing::error!("reading the MCP access of a role in {workspace_id}: {e:#}"); + ErrorData::internal_error( + format!( + "The MCP access of your role in '{workspace_id}' could not be read. Try again." + ), + None, + ) + }) +} + +/// What a connection with `access` gets in each workspace, in three queries however many there +/// are. Community, where no role limits anything, queries nothing and lists none. +pub(super) async fn workspace_accesses( + db: &DB, + email: &str, + workspaces: &[WorkspaceInfo], + access: SessionAccess, +) -> BackendResult> { + if !cfg!(feature = "enterprise") { + return Ok(HashMap::new()); + } + accesses(db, email, workspaces, access) + .await + .map_err(|e| ErrorData::internal_error(e.to_string(), None)) +} + +async fn accesses( + db: &DB, + email: &str, + workspaces: &[WorkspaceInfo], + access: SessionAccess, +) -> windmill_common::error::Result> { + let ids: Vec = workspaces.iter().map(|w| w.id.clone()).collect(); + let members = sqlx::query!( + "SELECT workspace_id, is_admin, operator, workspace_role FROM usr + WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false", + email, + &ids + ) + .fetch_all(db) + .await?; + let mut overrides: HashMap = sqlx::query!( + "SELECT workspace_id, role_overrides FROM workspace_settings + WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL", + &ids + ) + .fetch_all(db) + .await? + .into_iter() + .filter_map(|r| { + Some(( + r.workspace_id, + serde_json::from_value(r.role_overrides?).ok()?, + )) + }) + .collect(); + let locked: Vec = sqlx::query_scalar!( + "SELECT DISTINCT workspace_id FROM workspace_protection_rule + WHERE workspace_id = ANY($1) AND rules & $2 <> 0", + &ids, + ProtectionRules::DISABLE_DIRECT_DEPLOYMENT.bits() + ) + .fetch_all(db) + .await?; + let instance = roles::instance_roles(db).await?; + + let mut out = HashMap::with_capacity(ids.len()); + for id in ids { + let mut access = access; + let mut builds = true; + if let Some(m) = members.iter().find(|m| m.workspace_id == id) { + let roles = + roles::effective_roles(&instance, &overrides.remove(&id).unwrap_or_default())?; + let name = roles::resolve_role_name(m.workspace_role.clone(), m.operator); + let role = roles.iter().find(|r| r.name == name); + let limited = roles.iter().any(|r| r.mcp_limit().is_some()); + let limit = match role { + Some(role) => role.mcp_limit().and_then(limit_of), + None => limited.then_some(McpLimit::Off), + }; + match limit { + None => {} + Some(McpLimit::ReadAndRun) => access = access.min(SessionAccess::ReadAndRun), + Some(McpLimit::ReadOnly) => access = SessionAccess::ReadOnly, + Some(McpLimit::Runnables { .. }) => { + out.insert( + id, + "scripts and flows as tools, on this workspace's own MCP URL", + ); + continue; + } + Some(McpLimit::Off) => { + out.insert(id, "off"); + continue; + } + } + if !m.is_admin { + let caps = role.map_or(RoleCapabilities::NONE, |r| r.capabilities); + if !caps.run { + access = SessionAccess::ReadOnly; + } + builds = caps.is_author(); + } + } + if access == SessionAccess::Full && (!builds || locked.contains(&id)) { + access = SessionAccess::ReadAndRun; + } + out.insert( + id, + match access { + SessionAccess::ReadOnly => "read only", + SessionAccess::ReadAndRun => "read and run", + SessionAccess::Full => "build and run", + }, + ); + } + Ok(out) +} diff --git a/backend/windmill-common/src/roles.rs b/backend/windmill-common/src/roles.rs index f1db372cf3..4bee0f68d9 100644 --- a/backend/windmill-common/src/roles.rs +++ b/backend/windmill-common/src/roles.rs @@ -342,6 +342,67 @@ pub fn legacy_operator_settings(c: &RoleCapabilities) -> serde_json::Value { }) } +/// What a role's members may do through MCP. +#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum McpRoleAccess { + /// Whatever the role can do in Windmill. Stored explicitly by a workspace lifting the + /// instance's limit: an unset setting falls through instead. + #[default] + FollowRole, + ReadRun, + ReadOnly, + /// The scripts and flows of the setting, one tool each, and nothing else. + Runnables, + Off, +} + +/// A role's MCP setting: a maximum for every connection of its members, workspace admins holding +/// the role included. Apart from [`RoleCapabilities`], which it must not affect: seats and every +/// authoring gate read those. EE only, see [`custom_roles_built`]. +#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)] +pub struct McpRoleSetting { + pub access: McpRoleAccess, + /// Paths as an `mcp:scripts:` scope names them: `*`, an exact path or a `/*` subtree. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub scripts: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub flows: Vec, +} + +impl McpRoleSetting { + fn off() -> Self { + Self { access: McpRoleAccess::Off, ..Default::default() } + } + + pub fn validate(&self, role: &str) -> Result<()> { + let runnables = self.access == McpRoleAccess::Runnables; + if runnables == (self.scripts.is_empty() && self.flows.is_empty()) { + return Err(Error::BadRequest(if runnables { + format!("role `{role}`: choose at least one script or flow to offer over MCP") + } else { + format!( + "role `{role}`: MCP scripts and flows are only set with the `runnables` access" + ) + })); + } + for path in self.scripts.iter().chain(&self.flows) { + let base = path.strip_suffix("/*").unwrap_or(path); + let usable = path == "*" + || (!base.contains(['*', ',', ' ']) + && ["u/", "f/", "g/"] + .iter() + .any(|p| base.len() > p.len() && base.starts_with(p))); + if !usable { + return Err(Error::BadRequest(format!( + "role `{role}`: `{path}` is not a script or flow path: use `*`, a path, or `/*`" + ))); + } + } + Ok(()) + } +} + /// One entry of the instance's [`WORKSPACE_ROLES_SETTING`]. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] pub struct RoleDefinition { @@ -350,6 +411,9 @@ pub struct RoleDefinition { pub label: Option, #[serde(default)] pub capabilities: RoleCapabilitiesPatch, + /// Unset falls through to the layer below. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp: Option, } /// One entry of `workspace_settings.role_overrides`, keyed by role name. Naming a role the @@ -360,6 +424,9 @@ pub struct RoleOverride { pub label: Option, #[serde(default)] pub capabilities: RoleCapabilitiesPatch, + /// Unset falls through to the layer below. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp: Option, } pub type RoleOverrides = HashMap; @@ -377,11 +444,22 @@ pub struct EffectiveRole { pub name: String, pub label: String, pub capabilities: RoleCapabilities, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp: Option, pub source: RoleSource, /// Whether the workspace overrides this role. pub overridden: bool, } +impl EffectiveRole { + /// The role's MCP setting when it limits anything. + pub fn mcp_limit(&self) -> Option<&McpRoleSetting> { + self.mcp + .as_ref() + .filter(|m| m.access != McpRoleAccess::FollowRole) + } +} + /// Whether stored instance roles and workspace-only roles apply: on any EE build. A CE build has /// `developer` and `operator`, which a workspace may still override. fn custom_roles_built() -> bool { @@ -409,11 +487,13 @@ pub fn default_instance_roles() -> Vec { name: DEVELOPER_ROLE.to_string(), label: Some("Developer".to_string()), capabilities: RoleCapabilitiesPatch::default(), + mcp: None, }, RoleDefinition { name: OPERATOR_ROLE.to_string(), label: Some("Operator".to_string()), capabilities: RoleCapabilitiesPatch::default(), + mcp: None, }, ] } @@ -453,6 +533,9 @@ pub fn parse_instance_roles(value: &serde_json::Value) -> Result( } } +/// The MCP setting limiting the caller in `workspace_id`, `None` when nothing does. An error means +/// the limit is unknown: refuse, since an unread limit is one the admin still relies on. +/// +/// Reads the member's role only where some role carries a limit, so an unconfigured workspace +/// costs the cached [`workspace_roles`] and Community nothing. Workspace admins are held to the +/// role they carry; a superadmin who is no member carries none. +pub async fn caller_mcp_limit( + db: &DB, + workspace_id: &str, + authed: &A, +) -> Result> { + if !custom_roles_built() { + return Ok(None); + } + let roles = workspace_roles(db, workspace_id).await?; + if !roles.iter().any(|r| r.mcp_limit().is_some()) { + return Ok(None); + } + Ok( + match member_role(db, workspace_id, authed.username()).await? { + Some(name) => match roles.iter().find(|r| r.name == name) { + Some(role) => role.mcp_limit().cloned(), + // A role no longer defined fails closed, as its capabilities do. + None => Some(McpRoleSetting::off()), + }, + None if authed.is_admin() => None, + None => Some(McpRoleSetting::off()), + }, + ) +} + /// Whether the caller's role in `workspace_id` holds [`RoleCapabilities::fork`]. Read from the role /// even for an unrestricted caller, since withdrawing `fork` alone leaves a role unrestricted. A /// caller with no membership is left to the fork routes' other gates. @@ -918,6 +1049,14 @@ pub async fn ensure_role_unused(db: &DB, w_id: Option<&str>, name: &str) -> Resu Ok(()) } +/// Whether `next` is `current` itself, or with some roles' MCP settings removed. +fn only_removes_mcp(current: &[RoleDefinition], next: &[RoleDefinition]) -> bool { + current.len() == next.len() + && current.iter().zip(next).all(|(c, n)| { + c == n || (n.mcp.is_none() && RoleDefinition { mcp: None, ..c.clone() } == *n) + }) +} + /// Checks a write of the `workspace_roles` setting (`None` or null resets to the defaults) before /// it is stored. Every writer of the setting must call it, the declarative config sync included. pub async fn validate_instance_roles_write( @@ -929,8 +1068,12 @@ pub async fn validate_instance_roles_write( None | Some(serde_json::Value::Null) => default_instance_roles(), Some(v) => parse_instance_roles(v)?, }; - // Resetting stays open so a downgraded instance can always drop the setting. - if !custom_roles_enabled() && *current != next && next != default_instance_roles() { + // Resetting stays open so a downgraded instance can always drop the setting, and so does + // removing an MCP setting. + if !custom_roles_enabled() + && !only_removes_mcp(¤t, &next) + && next != default_instance_roles() + { return Err(Error::BadRequest( "changing workspace roles requires a valid Windmill Enterprise Edition license" .to_string(), @@ -958,9 +1101,34 @@ pub async fn validate_instance_roles_write( )) })?; } + log_mcp_role_changes(next.iter().map(|r| { + let before = current.iter().find(|c| c.name == r.name); + (before.and_then(|c| c.mcp.as_ref()), r.mcp.as_ref()) + })); Ok(()) } +/// Counts the MCP settings a role write changes, as `(before, after)` per role. +pub fn log_mcp_role_changes<'a>( + changes: impl Iterator, Option<&'a McpRoleSetting>)>, +) { + for (before, after) in changes { + let access = after.map(|m| m.access); + if access == before.map(|m| m.access) { + continue; + } + let key = match access { + None => "unset", + Some(McpRoleAccess::FollowRole) => "follow_role", + Some(McpRoleAccess::ReadRun) => "read_run", + Some(McpRoleAccess::ReadOnly) => "read_only", + Some(McpRoleAccess::Runnables) => "runnables", + Some(McpRoleAccess::Off) => "off", + }; + crate::feature_usage::log_feature_usage("mcp", "role_access", key); + } +} + /// Side effects of a stored `workspace_roles` write, owed by every writer. The seat table is read /// by billing on every replica, so it is rebuilt here rather than on the notify that drops the /// role caches. diff --git a/backend/windmill-common/tests/workspace_roles_license.rs b/backend/windmill-common/tests/workspace_roles_license.rs index 88aa3593cb..952991037a 100644 --- a/backend/windmill-common/tests/workspace_roles_license.rs +++ b/backend/windmill-common/tests/workspace_roles_license.rs @@ -7,7 +7,7 @@ use sqlx::{Pool, Postgres}; use windmill_common::ee_oss::LICENSE_KEY_VALID; use windmill_common::roles::{ self, check_frozen_overrides, instance_roles, load_role_overrides, - validate_instance_roles_write, RoleOverrides, + validate_instance_roles_write, McpRoleAccess, McpRoleSetting, RoleOverride, RoleOverrides, }; /// A lapsed license freezes the configured roles: falling back to the defaults would give a @@ -51,6 +51,15 @@ async fn lapsed_license_freezes_roles(db: Pool) { validate_instance_roles_write(&db, Some(&restricted)) .await .expect("resaving the stored roles is a no-op"); + validate_instance_roles_write( + &db, + Some(&serde_json::json!([ + {"name": "developer", "capabilities": {"code": false, "flows": "none", "apps": "none"}, + "mcp": {"access": "follow_role"}} + ])), + ) + .await + .expect_err("adding an instance MCP setting needs a license"); validate_instance_roles_write(&db, None) .await .expect("resetting to the defaults stays open"); @@ -65,6 +74,31 @@ async fn lapsed_license_freezes_roles(db: Pool) { check_frozen_overrides(&instance, &previous, &RoleOverrides::new()) .expect("removing a workspace-only role stays open"); + let mcp = |access: McpRoleAccess| { + RoleOverrides::from([( + "developer".to_string(), + RoleOverride { + mcp: Some(McpRoleSetting { access, ..Default::default() }), + ..Default::default() + }, + )]) + }; + let capped = mcp(McpRoleAccess::ReadOnly); + check_frozen_overrides(&instance, &capped, &mcp(McpRoleAccess::FollowRole)) + .expect_err("changing an MCP setting needs a license"); + check_frozen_overrides(&instance, &RoleOverrides::new(), &capped) + .expect_err("adding an MCP setting needs a license"); + check_frozen_overrides(&instance, &capped, &capped).expect("an unchanged MCP setting passes"); + check_frozen_overrides(&instance, &capped, &RoleOverrides::new()) + .expect("removing an MCP setting stays open"); + assert!( + roles::effective_roles(&instance, &capped) + .unwrap() + .iter() + .any(|r| r.name == "developer" && r.mcp_limit().is_some()), + "a configured MCP limit keeps applying" + ); + LICENSE_KEY_VALID.store(true, Ordering::Relaxed); check_frozen_overrides(&instance, &previous, &relabelled).expect("licensed again"); } diff --git a/backend/windmill-mcp/src/common/scope.rs b/backend/windmill-mcp/src/common/scope.rs index b330d6f9e5..cb6c7e5d65 100644 --- a/backend/windmill-mcp/src/common/scope.rs +++ b/backend/windmill-mcp/src/common/scope.rs @@ -33,6 +33,19 @@ pub struct McpScopeConfig { pub no_endpoints: bool, } +/// The most a member's workspace role lets an MCP connection do, whatever its token grants. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum McpLimit { + ReadAndRun, + ReadOnly, + /// These scripts and flows, one tool each, and nothing else. + Runnables { + scripts: Vec, + flows: Vec, + }, + Off, +} + impl McpScopeConfig { /// How the token came to have endpoint tools, as a closed set of telemetry keys. pub fn endpoint_shape(&self) -> &'static str { @@ -49,6 +62,31 @@ impl McpScopeConfig { } } + /// This token's grant held to a role's limit. A limited role gets no endpoint tools; a + /// selection intersects with the token's own, so each runnable left is one both allow. + pub fn limited_by(mut self, limit: &McpLimit) -> Self { + self.no_endpoints = true; + self.endpoints.clear(); + match limit { + McpLimit::ReadAndRun => {} + McpLimit::ReadOnly | McpLimit::Off => self.read_only = true, + McpLimit::Runnables { scripts, flows } => { + // Favorites name no path: the listing's favorites join keeps narrowing them. + if self.favorites && !self.all { + self.scripts = scripts.clone(); + self.flows = flows.clone(); + } else { + self.scripts = intersect_patterns(&self.scripts, scripts); + self.flows = intersect_patterns(&self.flows, flows); + } + self.all = false; + self.granular = true; + self.hub_apps = None; + } + } + self + } + pub fn allows_workspace(&self, workspace_id: &str) -> bool { self.workspaces .as_ref() @@ -153,6 +191,27 @@ fn resource_list_covers(caller: &[String], requested: &[String]) -> bool { .all(|req| caller.iter().any(|c| pattern_covers(c, req))) } +/// The patterns matching exactly the paths both lists match: two patterns are nested or disjoint, +/// so the narrower of each nested pair. +fn intersect_patterns(a: &[String], b: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + for x in a { + for y in b { + let narrower = if pattern_covers(x, y) { + y + } else if pattern_covers(y, x) { + x + } else { + continue; + }; + if !out.contains(narrower) { + out.push(narrower.clone()); + } + } + } + out +} + /// Directional: does the single caller pattern cover `requested`? `caller` may /// be `*`, an exact path/name, or a `/*` subtree; `requested` may itself /// be a subtree wildcard, in which case the whole requested subtree must fall @@ -346,6 +405,33 @@ fn resource_matches_pattern(resource_path: &str, pattern: &str) -> bool { mod tests { use super::*; + #[test] + fn a_role_limit_narrows_and_never_widens() { + let parse = |scopes: &[&str]| { + parse_mcp_scopes(&scopes.iter().map(|s| s.to_string()).collect::>()).unwrap() + }; + let limit = McpLimit::Runnables { + scripts: vec!["f/ops/*".to_string(), "f/a/x".to_string()], + flows: vec![], + }; + let all = parse(&["mcp:all"]).limited_by(&limit); + assert!(all.is_allowed("script", "f/ops/check") && all.is_allowed("script", "f/a/x")); + assert!(!all.is_allowed("script", "f/b/x") && !all.is_allowed("flow", "f/ops/check")); + assert!(!all.is_allowed("endpoint", "listJobs") && all.no_endpoints && !all.all); + + let selection = parse(&["mcp:scripts:f/ops/sub/*,f/b/x,f/a/*", "mcp:flows:*"]); + let both = selection.limited_by(&limit); + assert_eq!(both.scripts, ["f/ops/sub/*", "f/a/x"]); + assert!(both.flows.is_empty()); + + let favorites = parse(&["mcp:favorites"]).limited_by(&limit); + assert!(favorites.favorites && favorites.granular); + assert!(!favorites.is_allowed("script", "f/b/x")); + assert!(parse(&["mcp:endpoints:*"]).limited_by(&limit).scripts.is_empty()); + assert!(parse(&["mcp:all", "mcp:hub:slack"]).limited_by(&limit).hub_apps.is_none()); + } + + #[test] fn test_parse_legacy_scopes() { let scopes = vec!["mcp:all".to_string()]; diff --git a/backend/windmill-mcp/src/server/backend.rs b/backend/windmill-mcp/src/server/backend.rs index 5938b4c9c5..92054e9a96 100644 --- a/backend/windmill-mcp/src/server/backend.rs +++ b/backend/windmill-mcp/src/server/backend.rs @@ -9,6 +9,7 @@ use rmcp::ErrorData; use serde_json::Value; use std::collections::HashMap; +use crate::common::scope::McpLimit; use crate::common::types::{ FlowInfo, HubScriptInfo, McpToken, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo, @@ -31,7 +32,8 @@ pub enum RunOutcome { /// What a v2 token may do: read, read and run deployed scripts, flows and agents /// (`mcp:read_run`), or everything its owner can. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Ordered, narrowest first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum SessionAccess { ReadOnly, ReadAndRun, @@ -276,6 +278,23 @@ pub trait McpBackend: Send + Sync + Clone + 'static { // Workspace server (`SessionRunner`): the AI-session toolset // ───────────────────────────────────────────────────────────────── + /// The limit the caller's role sets on MCP in `workspace_id`, `None` when it sets none. `auth` + /// is the caller's in that workspace. An error must refuse: the limit is unknown. + async fn mcp_limit( + &self, + auth: &Self::Auth, + workspace_id: &str, + ) -> BackendResult>; + + /// What a connection with this access gets in each workspace, by id, for `list_workspaces`. + /// A workspace left out says nothing. + async fn workspace_accesses( + &self, + auth: &Self::Auth, + workspaces: &[WorkspaceInfo], + access: SessionAccess, + ) -> BackendResult>; + /// The instructions a client reaching one workspace receives on connecting, built for /// this user and what the token lets them do. async fn session_instructions( @@ -294,7 +313,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static { auth: &Self::Auth, workspace_id: &str, access: SessionAccess, - ) -> String; + ) -> BackendResult; /// The tools a token with this access is offered. fn session_tools(&self, access: SessionAccess) -> Vec; diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index 69ce01be4f..58fa0ceeeb 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -13,6 +13,7 @@ mod session; pub mod tools; // Re-export main types +pub use crate::common::scope::McpLimit; pub use crate::common::types::{McpToken, MultiWorkspaceMcp, NoEndpointTools, WorkspaceInfo}; pub use backend::{ BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess, @@ -22,7 +23,7 @@ pub use endpoints::{ list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool, }; pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES}; -pub use session::SessionRunner; +pub use session::{admits, session_limit, SessionRunner}; pub use tools::create_tool_from_item; // Re-export rmcp types for convenience diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 85425ecffd..0fe812a7f0 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -4,7 +4,7 @@ //! and delegates to a McpBackend for actual functionality. use crate::common::schema::extract_resource_types_from_schema; -use crate::common::scope::parse_mcp_scopes; +use crate::common::scope::{parse_mcp_scopes, McpLimit}; use crate::common::transform::{ assign_tool_names, extract_hub_version_id_from_hashed, extract_path_prefix_from_hashed, is_encoded_tool_name, parse_tool_prefix, reverse_transform, reverse_transform_key, @@ -19,6 +19,7 @@ use crate::server::endpoints::{ endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, list_workspaces_tool, EndpointTool, }; use crate::server::list_changes::ListChanges; +use crate::server::session::limit_refusal; use crate::server::tools::create_tool_from_item; use rmcp::handler::server::ServerHandler; use rmcp::model::{ @@ -647,6 +648,13 @@ impl ServerHandler for Runner { scope_config.no_endpoints |= no_endpoints; // v1 has no read-and-run access: such a token reads only. + // Multi-workspace mode lists before any workspace is named: a role's limit refuses there + // at call time. + if let McpMode::Single(workspace_id) = &mode { + if let Some(limit) = self.backend.mcp_limit(&auth, workspace_id).await? { + scope_config = scope_config.limited_by(&limit); + } + } let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only; match mode { @@ -675,6 +683,14 @@ impl ServerHandler for Runner { let mut scope_config = parse_mcp_scopes(scopes).map_err(|e| ErrorData::internal_error(e, None))?; scope_config.no_endpoints |= no_endpoints; + if let McpMode::Single(workspace_id) = &mode { + if let Some(limit) = self.backend.mcp_limit(&auth, workspace_id).await? { + if matches!(limit, McpLimit::Off | McpLimit::ReadOnly) { + return Err(limit_refusal(workspace_id, &limit)); + } + scope_config = scope_config.limited_by(&limit); + } + } let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only; let args = request.arguments.map(Value::Object).unwrap_or(Value::Null); @@ -1294,6 +1310,10 @@ impl Runner { .resolve_workspace_auth(token, &workspace_id) .await .map_err(|e| ErrorData::internal_error(e.message, None))?; + // Endpoint tools, the only ones here, are never served under a role's limit. + if let Some(limit) = self.backend.mcp_limit(&resolved, &workspace_id).await? { + return Err(limit_refusal(&workspace_id, &limit)); + } (workspace_id, resolved) } else { (String::new(), base_auth.clone()) diff --git a/backend/windmill-mcp/src/server/session.rs b/backend/windmill-mcp/src/server/session.rs index 7c4a7d68e7..f8624e1ebf 100644 --- a/backend/windmill-mcp/src/server/session.rs +++ b/backend/windmill-mcp/src/server/session.rs @@ -5,7 +5,7 @@ //! Every tool takes the workspace it acts in, whether the token reaches one workspace or //! several, so a client's tool schemas do not change with the token it signed in with. -use crate::common::scope::{parse_mcp_scopes, McpScopeConfig}; +use crate::common::scope::{parse_mcp_scopes, McpLimit, McpScopeConfig}; use crate::common::types::WorkspaceInfo; use crate::server::backend::{McpAuth, McpBackend, SessionAccess}; use crate::server::endpoints::{list_workspaces_tool, with_workspace_id_arg}; @@ -30,7 +30,7 @@ use std::sync::Arc; /// `mcp:all`, and no scope from outside `mcp:` that confines the token to some routes /// or paths (`variables:read:f/x/*`): the tools call the API without a route scope, so /// that confinement would be lost here. The job tag fence is carried through instead. -fn admits(scopes: &[String], all: bool) -> bool { +pub fn admits(scopes: &[String], all: bool) -> bool { all && scopes .iter() .all(|s| s.starts_with("mcp:") || s.starts_with("if_jobs:filter_tags:")) @@ -46,6 +46,34 @@ fn access(auth: &A, scope: &McpScopeConfig) -> SessionAccess { } } +/// The access a role's limit leaves the session toolset, or why it leaves none. +pub fn session_limit(workspace_id: &str, limit: &McpLimit) -> Result { + match limit { + McpLimit::ReadAndRun => Ok(SessionAccess::ReadAndRun), + McpLimit::ReadOnly => Ok(SessionAccess::ReadOnly), + McpLimit::Runnables { .. } | McpLimit::Off => Err(limit_refusal(workspace_id, limit)), + } +} + +/// Says what is allowed there instead, so the model does not retry. +pub(super) fn limit_refusal(workspace_id: &str, limit: &McpLimit) -> ErrorData { + let allowed = match limit { + McpLimit::Off => "your role has no MCP access there".to_string(), + McpLimit::Runnables { .. } => format!( + "your role is limited there to chosen scripts and flows as tools, which a connection \ + to that workspace's own MCP URL (/api/mcp/w/{workspace_id}/mcp) serves" + ), + McpLimit::ReadOnly => "your role is limited there to reading, through /api/mcp".to_string(), + McpLimit::ReadAndRun => { + "your role is limited there to reading and running, through /api/mcp".to_string() + } + }; + ErrorData::invalid_params( + format!("Not available in workspace '{workspace_id}': {allowed}"), + None, + ) +} + const GET_WORKSPACE_CONTEXT: &str = "get_workspace_context"; /// The MIME type of an MCP Apps view (the `io.modelcontextprotocol/ui` extension). @@ -196,9 +224,19 @@ impl SessionRunner { "Every tool takes a `workspace_id`: pass `{}`, the workspace this connection \ works in.\n\n{}", only.id, - self.backend - .session_instructions(&auth, &only.id, access(&auth, &caller.scope)) - .await? + match self.backend.mcp_limit(&auth, &only.id).await? { + // Connecting succeeds so the client shows why no tool works there. + Some(limit @ (McpLimit::Off | McpLimit::Runnables { .. })) => + limit_refusal(&only.id, &limit).message.into_owned(), + _ => + self.backend + .session_instructions( + &auth, + &only.id, + access(&auth, &caller.scope), + ) + .await?, + } ) } _ => { @@ -288,6 +326,17 @@ impl ServerHandler for SessionRunner { // A bound token's one workspace decides its toolset as it decides its instructions: // a role there that cannot run gets the read-only tools. if let McpMode::Single(bound) = &caller.mode { + match self.backend.mcp_limit(&caller.auth, bound).await? { + Some(limit) => match session_limit(bound, &limit) { + Ok(most) => access = access.min(most), + Err(_) => { + return Ok(ListToolsResult::with_all_items(tools) + .with_ttl_ms(LIST_TTL_MS) + .with_cache_scope(LIST_CACHE_SCOPE)) + } + }, + None => {} + } if access != SessionAccess::ReadOnly && !self .backend @@ -371,8 +420,26 @@ impl ServerHandler for SessionRunner { let caller = Self::caller(&context)?; if request.name == "list_workspaces" { let workspaces = self.workspaces(&caller).await?; + let accesses = self + .backend + .workspace_accesses( + &caller.auth, + &workspaces, + access(&caller.auth, &caller.scope), + ) + .await?; + let listed: Vec = workspaces + .iter() + .map(|w| { + let mut entry = serde_json::json!({ "id": w.id, "name": w.name }); + if let Some(access) = accesses.get(&w.id) { + entry["access"] = (*access).into(); + } + entry + }) + .collect(); return Ok(CallToolResult::success(vec![ContentBlock::text( - serde_json::to_string_pretty(&workspaces).unwrap_or_default(), + serde_json::to_string_pretty(&listed).unwrap_or_default(), )]) .into()); } @@ -391,7 +458,7 @@ impl ServerHandler for SessionRunner { let text = self .backend .workspace_context(&auth, &workspace_id, access(&auth, &caller.scope)) - .await; + .await?; return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()); } let result = self diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index ca220a6abe..a947ea1d63 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8666,7 +8666,7 @@ write a secret you were not given: keep the placeholder. | \`default_app\` | Path of the app shown as the workspace home. | | \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. | | \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. | -| \`role_overrides\` | \`{ : { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. | +| \`role_overrides\` | \`{ : { label?, capabilities, mcp?, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. \`mcp\` (Enterprise) caps what the role's members may do through MCP: \`{ access: follow_role \\| read_run \\| read_only \\| runnables \\| off, scripts?, flows? }\`, the paths only with \`runnables\`. | | \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. | | \`mute_critical_alerts\` | Mute the workspace's critical alerts. | | \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | diff --git a/docs/workspace-roles.md b/docs/workspace-roles.md index 02db77c3f8..05723ad69e 100644 --- a/docs/workspace-roles.md +++ b/docs/workspace-roles.md @@ -57,6 +57,27 @@ Unlike `fork`, withdrawing `run` makes a role restricted: it is an enforced gate and the fast path is what spares every unrestricted caller a role lookup on each run. It does not change seats: a role is a full seat by what it authors, not by whether it runs. +## MCP access + +A role may carry an MCP setting beside its capabilities (`McpRoleSetting`, EE): `follow_role`, +`read_run`, `read_only`, `runnables` (listed scripts and flows as tools, nothing else) or `off`. It +is a maximum for every MCP connection of the role's members, whatever the token and whenever it was +made, and never widens one; the in-app chat does not read it. Layers fall through as capabilities +do, so `follow_role` is stored by a workspace lifting the instance's limit. It is not a capability: +it must not restrict a role, cost a seat or reach an authoring gate. + +- Workspace admins are held to the setting of the role they carry, as `DisableDirectDeployment` + holds them. A superadmin who is no member carries no role. +- `caller_mcp_limit` reads the member's role only where some role carries a limit. An error or a + role no longer defined refuses, unlike `can_run`, which fails open. +- A connection to one workspace is served by the role, not the URL (`served_under_limit`): + `runnables` gets the tools server whatever the token, and an `mcp:all` token under another limit + the session toolset, since endpoint tools are never served under one. Where a connection covers + several workspaces the list is one for all, so the limit refuses at call time. +- A selection intersects with the token's own (`McpScopeConfig::limited_by`). +- A lapsed license freezes it as it does roles: it keeps applying and can be removed, not changed. + On Community it is ignored and refused at write. + ## Forks A member's role carries into a fork: the forker, and every member `copy_members` or diff --git a/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte b/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte index 0bdc23e175..67df5db73c 100644 --- a/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte +++ b/frontend/src/lib/components/instanceSettings/WorkspaceRolesSetting.svelte @@ -4,7 +4,13 @@ import { Alert, Badge, Button } from '../common' import TextInput from '../text_input/TextInput.svelte' import RoleCapabilitiesEditor from '../settings/RoleCapabilitiesEditor.svelte' - import type { RoleCapabilities, RoleCapabilitiesPatch, RoleDefinition } from '$lib/gen' + import RoleMcpAccessEditor from '../settings/RoleMcpAccessEditor.svelte' + import type { + McpRoleSetting, + RoleCapabilities, + RoleCapabilitiesPatch, + RoleDefinition + } from '$lib/gen' import { resolveCapabilities, authorLevelLabel, @@ -36,6 +42,7 @@ name: string label: string capabilities: RoleCapabilitiesPatch + mcp: McpRoleSetting | undefined open: boolean } @@ -52,6 +59,7 @@ name: r.name ?? '', label: r.label ?? '', capabilities: structuredClone(r.capabilities ?? {}), + mcp: structuredClone(r.mcp ?? undefined), open: false })) } @@ -60,7 +68,8 @@ const list: RoleDefinition[] = rs.map((r) => ({ name: r.name.trim(), ...(r.label.trim() ? { label: r.label.trim() } : {}), - ...(isEmptyPatch(r.capabilities) ? {} : { capabilities: r.capabilities }) + ...(isEmptyPatch(r.capabilities) ? {} : { capabilities: r.capabilities }), + ...(r.mcp ? { mcp: r.mcp } : {}) })) return isDefaultInstanceRoles(list) ? undefined : list } @@ -78,7 +87,8 @@ $effect(() => { const next = serialize($state.snapshot(rows) as Row[]) - if (lastSynced === undefined || disabled) return + // Not `disabled`: without a license, removing an MCP setting is still saved. + if (lastSynced === undefined || loading) return const nextStr = JSON.stringify(next ?? null) // Compared with the stored value in serialized form, so one spelled differently (the // defaults written out, an empty `capabilities`, another key order) is not rewritten @@ -94,7 +104,7 @@ const flipDurationMs = 200 function addRole() { - rows = [...rows, { id: nextId++, name: '', label: '', capabilities: {}, open: true }] + rows = [...rows, { id: nextId++, name: '', label: '', capabilities: {}, mcp: undefined, open: true }] } function summary(caps: RoleCapabilities): string { @@ -115,7 +125,7 @@ title="Changing workspace roles requires a valid Windmill Enterprise Edition license" > The roles below keep applying as they are. A workspace admin can still override what they - allow in that workspace's settings. + allow in that workspace's settings, and an MCP access set here can still be removed. {#if serialize(rows) !== undefined}
{:else if errors[`${i}.capabilities`]} diff --git a/frontend/src/lib/components/mcp/McpScopeSelector.svelte b/frontend/src/lib/components/mcp/McpScopeSelector.svelte index 3e87476f74..84cb3533e2 100644 --- a/frontend/src/lib/components/mcp/McpScopeSelector.svelte +++ b/frontend/src/lib/components/mcp/McpScopeSelector.svelte @@ -17,9 +17,12 @@ workspaceId: string scope: string initialScope?: string + /** Paths every member of a role shares: no favorites, which are each member's own, and no + * hub scripts, which are no path. */ + pathsOnly?: boolean } - let { workspaceId, scope = $bindable(), initialScope }: Props = $props() + let { workspaceId, scope = $bindable(), initialScope, pathsOnly = false }: Props = $props() // Mirrors ITEMS_FETCH_MAX_LIMIT in backend/windmill-api/src/mcp/utils.rs: the // server exposes at most this many scripts and this many flows (per type) as @@ -29,7 +32,9 @@ const parsedInitial = parseInitialScope(initialScope) - let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>(parsedInitial.mode) + let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>( + pathsOnly && parsedInitial.mode === 'favorites' ? 'folder' : parsedInitial.mode + ) let selectedFolders = $state(parsedInitial.folders) let allFolders = $state([]) let loadingFolders = $state(false) @@ -474,12 +479,14 @@ Scope {#snippet children({ item })} - + {#if !pathsOnly} + + {/if} {/if} -
+
Hub scripts (optional) {#if loadingApps}
Loading...
diff --git a/frontend/src/lib/components/settings/RoleMcpAccessEditor.svelte b/frontend/src/lib/components/settings/RoleMcpAccessEditor.svelte new file mode 100644 index 0000000000..617efa9794 --- /dev/null +++ b/frontend/src/lib/components/settings/RoleMcpAccessEditor.svelte @@ -0,0 +1,139 @@ + + +
+
+
+ MCP access + + The most an AI client may do for members of this role, admins holding it included, whatever + they grant it. Does not affect the chat in Windmill. + +
+
+