diff --git a/AGENTS.md b/AGENTS.md index b5efed5f77..356115753f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -72,7 +72,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 the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/ai_session_tools/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. A workspace's named tool sets (`workspace_settings.mcp_tool_sets`) are served at `/api/mcp/w/{workspace}/s/{set}/mcp`: signing in there grants `mcp:set:` alone, which `expand_tool_set` (`mcp/core.rs`) replaces on every request with the set's current selection, so a set narrows like any selection and an admin's edit reaches open connections. 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 the `_meta` it reads changes shape, since hosts cache a view by URI) from their result's `_meta` (`windmill/run`, `windmill/runs`, `windmill/review`, `windmill/item`), which the model never reads. A host draws a card for every call of a tool that declares one, so only these show tools do: the tools the model reads and runs with draw nothing, and `get_run` builds no card data. The card acts only by calling the session's tools (`show_run` to refresh, `cancel_job`, `show_deploy_review` to re-read a draft, `deploy_workspace_item` from the review card's Deploy button, which the user presses), so it sees nothing the model could not. Every `DESTRUCTIVE` tool but those in `CARD_ACTIONS` is hidden from it. Every session tool carries a `title` and explicit read-only, destructive and open-world hints, which the Claude and ChatGPT directories require (`DESTRUCTIVE`, `OPEN_WORLD`). A client that declares capabilities without the MCP Apps extension is not offered the show tools. - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/backend/.sqlx/query-0734fedf96224932c067fa9be615b8301addc2d10abb2a3e35d43b56201baf83.json b/backend/.sqlx/query-0734fedf96224932c067fa9be615b8301addc2d10abb2a3e35d43b56201baf83.json new file mode 100644 index 0000000000..6717f45b46 --- /dev/null +++ b/backend/.sqlx/query-0734fedf96224932c067fa9be615b8301addc2d10abb2a3e35d43b56201baf83.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE workspace_settings\n SET\n ai_config = source_ws.ai_config,\n large_file_storage = source_ws.large_file_storage,\n ducklake = source_ws.ducklake,\n dbt_warehouses = source_ws.dbt_warehouses,\n mcp_tool_sets = source_ws.mcp_tool_sets,\n datatable = source_ws.datatable,\n git_app_installations = source_ws.git_app_installations,\n add_admins_and_developers_to_forks = source_ws.add_admins_and_developers_to_forks\n FROM workspace_settings source_ws\n WHERE source_ws.workspace_id = $1\n AND workspace_settings.workspace_id = $2\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "0734fedf96224932c067fa9be615b8301addc2d10abb2a3e35d43b56201baf83" +} diff --git a/backend/.sqlx/query-0eb27f0609977fa1d30a5e72fd7b1134a8e184872ece98705c30eb3a77117d51.json b/backend/.sqlx/query-0eb27f0609977fa1d30a5e72fd7b1134a8e184872ece98705c30eb3a77117d51.json new file mode 100644 index 0000000000..ddbe65b296 --- /dev/null +++ b/backend/.sqlx/query-0eb27f0609977fa1d30a5e72fd7b1134a8e184872ece98705c30eb3a77117d51.json @@ -0,0 +1,244 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT\n workspace_id,\n slack_team_id,\n teams_team_id,\n teams_team_name,\n teams_team_guid,\n slack_name,\n slack_command_script,\n teams_command_script,\n slack_email,\n slack_oauth_client_id,\n slack_oauth_client_secret,\n customer_id,\n plan,\n webhook,\n webhook_events,\n ai_config,\n dbt_warehouses,\n mcp_tool_sets,\n large_file_storage,\n datatable,\n ducklake,\n git_sync,\n deploy_ui,\n default_app,\n default_scripts,\n mute_critical_alerts,\n color,\n operator_settings,\n git_app_installations,\n auto_invite,\n error_handler,\n success_handler,\n variable_expiration_handler,\n public_app_execution_limit_per_minute,\n error_handler_fallback_to_instance_alerts,\n guest_jwt_public_key,\n guest_jwt_jwks_url,\n add_admins_and_developers_to_forks\n FROM\n workspace_settings\n WHERE\n workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "slack_team_id", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "teams_team_id", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "teams_team_name", + "type_info": "Text" + }, + { + "ordinal": 4, + "name": "teams_team_guid", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "slack_name", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "slack_command_script", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "teams_command_script", + "type_info": "Text" + }, + { + "ordinal": 8, + "name": "slack_email", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "slack_oauth_client_id", + "type_info": "Varchar" + }, + { + "ordinal": 10, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + }, + { + "ordinal": 11, + "name": "customer_id", + "type_info": "Varchar" + }, + { + "ordinal": 12, + "name": "plan", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "webhook", + "type_info": "Text" + }, + { + "ordinal": 14, + "name": "webhook_events", + "type_info": "TextArray" + }, + { + "ordinal": 15, + "name": "ai_config", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "dbt_warehouses", + "type_info": "Jsonb" + }, + { + "ordinal": 17, + "name": "mcp_tool_sets", + "type_info": "Jsonb" + }, + { + "ordinal": 18, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 19, + "name": "datatable", + "type_info": "Jsonb" + }, + { + "ordinal": 20, + "name": "ducklake", + "type_info": "Jsonb" + }, + { + "ordinal": 21, + "name": "git_sync", + "type_info": "Jsonb" + }, + { + "ordinal": 22, + "name": "deploy_ui", + "type_info": "Jsonb" + }, + { + "ordinal": 23, + "name": "default_app", + "type_info": "Varchar" + }, + { + "ordinal": 24, + "name": "default_scripts", + "type_info": "Jsonb" + }, + { + "ordinal": 25, + "name": "mute_critical_alerts", + "type_info": "Bool" + }, + { + "ordinal": 26, + "name": "color", + "type_info": "Varchar" + }, + { + "ordinal": 27, + "name": "operator_settings", + "type_info": "Jsonb" + }, + { + "ordinal": 28, + "name": "git_app_installations", + "type_info": "Jsonb" + }, + { + "ordinal": 29, + "name": "auto_invite", + "type_info": "Jsonb" + }, + { + "ordinal": 30, + "name": "error_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 31, + "name": "success_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 32, + "name": "variable_expiration_handler", + "type_info": "Jsonb" + }, + { + "ordinal": 33, + "name": "public_app_execution_limit_per_minute", + "type_info": "Int4" + }, + { + "ordinal": 34, + "name": "error_handler_fallback_to_instance_alerts", + "type_info": "Bool" + }, + { + "ordinal": 35, + "name": "guest_jwt_public_key", + "type_info": "Text" + }, + { + "ordinal": 36, + "name": "guest_jwt_jwks_url", + "type_info": "Text" + }, + { + "ordinal": 37, + "name": "add_admins_and_developers_to_forks", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + false + ] + }, + "hash": "0eb27f0609977fa1d30a5e72fd7b1134a8e184872ece98705c30eb3a77117d51" +} diff --git a/backend/.sqlx/query-1ecc9cacf02398a7cee0719788e76e28c34052b083bcb51e7e5c104690128d5b.json b/backend/.sqlx/query-1ecc9cacf02398a7cee0719788e76e28c34052b083bcb51e7e5c104690128d5b.json new file mode 100644 index 0000000000..b9e2fb9ca0 --- /dev/null +++ b/backend/.sqlx/query-1ecc9cacf02398a7cee0719788e76e28c34052b083bcb51e7e5c104690128d5b.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, mcp_tool_sets, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, mcp_tool_sets, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "1ecc9cacf02398a7cee0719788e76e28c34052b083bcb51e7e5c104690128d5b" +} diff --git a/backend/.sqlx/query-4357736f4c8a74d384eff726369d364210c006055a72f52b1d00dc0efd6e5990.json b/backend/.sqlx/query-4357736f4c8a74d384eff726369d364210c006055a72f52b1d00dc0efd6e5990.json new file mode 100644 index 0000000000..051ec68cd5 --- /dev/null +++ b/backend/.sqlx/query-4357736f4c8a74d384eff726369d364210c006055a72f52b1d00dc0efd6e5990.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE workspace_settings SET mcp_tool_sets = $1 WHERE workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Jsonb", + "Text" + ] + }, + "nullable": [] + }, + "hash": "4357736f4c8a74d384eff726369d364210c006055a72f52b1d00dc0efd6e5990" +} diff --git a/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json b/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json deleted file mode 100644 index 96a0927e30..0000000000 --- a/backend/.sqlx/query-4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Text" - ] - }, - "nullable": [] - }, - "hash": "4693a6932e0f09f8d0a929bde83cc0aa58df96928eed3c05c515476771538c3a" -} diff --git a/backend/.sqlx/query-8a901804bfd11e21be439930b4f41778719238d72a032ec4a72b24c8a53250bd.json b/backend/.sqlx/query-8a901804bfd11e21be439930b4f41778719238d72a032ec4a72b24c8a53250bd.json new file mode 100644 index 0000000000..e5c6c47933 --- /dev/null +++ b/backend/.sqlx/query-8a901804bfd11e21be439930b4f41778719238d72a032ec4a72b24c8a53250bd.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT mcp_tool_sets -> $2 FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "8a901804bfd11e21be439930b4f41778719238d72a032ec4a72b24c8a53250bd" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 12de185c46..8f3b2c3376 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -458eeca8c31ba093a72eeb1ed9d82a83e18477db +b355c69d700cd66491af67259910b2b57a41f443 diff --git a/backend/migrations/20261113155231_mcp_tool_sets.down.sql b/backend/migrations/20261113155231_mcp_tool_sets.down.sql new file mode 100644 index 0000000000..76840377b0 --- /dev/null +++ b/backend/migrations/20261113155231_mcp_tool_sets.down.sql @@ -0,0 +1 @@ +ALTER TABLE workspace_settings DROP COLUMN IF EXISTS mcp_tool_sets; diff --git a/backend/migrations/20261113155231_mcp_tool_sets.up.sql b/backend/migrations/20261113155231_mcp_tool_sets.up.sql new file mode 100644 index 0000000000..0f3218a20d --- /dev/null +++ b/backend/migrations/20261113155231_mcp_tool_sets.up.sql @@ -0,0 +1 @@ +ALTER TABLE workspace_settings ADD COLUMN IF NOT EXISTS mcp_tool_sets JSONB; diff --git a/backend/tests/mcp_tool_sets.rs b/backend/tests/mcp_tool_sets.rs new file mode 100644 index 0000000000..4d50489b0f --- /dev/null +++ b/backend/tests/mcp_tool_sets.rs @@ -0,0 +1,82 @@ +//! A named tool set narrows and never grants: a member signed in to it gets the set's +//! runnables they can see, the set is read on every request, and its URL refuses any other +//! token so the client signs in to the set. +#![cfg(feature = "mcp")] + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +async fn list_tools(port: u16, path: &str, token: &str) -> anyhow::Result<(u16, Value)> { + let response = 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": "tools/list", "params": {}})) + .send() + .await?; + let status = response.status().as_u16(); + let body = response.text().await?; + let data = body + .lines() + .find_map(|l| l.strip_prefix("data: ")) + .unwrap_or(&body); + Ok((status, serde_json::from_str(data).unwrap_or(Value::Null))) +} + +fn names(list: &Value) -> Vec { + list["result"]["tools"] + .as_array() + .unwrap_or_else(|| panic!("no tools in {list}")) + .iter() + .map(|t| t["name"].as_str().unwrap_or_default().to_string()) + .collect() +} + +#[sqlx::test(fixtures("base"))] +async fn tool_set_narrows_to_what_the_member_can_see(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + r#" + INSERT INTO folder (workspace_id, name, display_name, owners, extra_perms) VALUES + ('test-workspace', 'ops', 'ops', ARRAY['u/test-user'], '{"u/test-user-3": false}'), + ('test-workspace', 'internal', 'internal', ARRAY['u/test-user'], '{}'); + 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 }', '{}', '', '', 'f/ops/check_order', 7788301, 'bun', ''), + ('test-workspace', 'test-user', 'export function main() { return 1 }', '{}', '', '', 'f/internal/secret', 7788302, 'bun', ''); + UPDATE workspace_settings + SET mcp_tool_sets = '{"support": {"scripts": ["f/ops/*", "f/internal/secret"]}}' + WHERE workspace_id = 'test-workspace'; + INSERT INTO token (token_hash, token_prefix, email, label, super_admin, scopes, workspace_id) VALUES + (encode(sha256('SET_TOKEN'::bytea), 'hex'), 'SET_TOKEN_', 'test3@windmill.dev', 'mcp', false, + ARRAY['mcp:set:support', 'mcp:runnables_as_tools'], 'test-workspace'), + (encode(sha256('FULL_TOKEN'::bytea), 'hex'), 'FULL_TOKEN', 'test3@windmill.dev', 'mcp', false, + ARRAY['mcp:all', 'mcp:session'], 'test-workspace'); + "#, + ) + .execute(&db) + .await?; + + let server = ApiServer::start_mcp(db.clone()).await?; + let port = server.addr.port(); + const SET_URL: &str = "/api/mcp/w/test-workspace/s/support/mcp"; + + let (_, list) = list_tools(port, SET_URL, "SET_TOKEN").await?; + assert_eq!(names(&list), ["check_order"], "{list}"); + + let (status, _) = list_tools(port, SET_URL, "FULL_TOKEN").await?; + assert_eq!(status, 401, "a token not signed in to the set"); + + sqlx::query( + "UPDATE workspace_settings SET mcp_tool_sets = NULL WHERE workspace_id = 'test-workspace'", + ) + .execute(&db) + .await?; + let (_, list) = list_tools(port, SET_URL, "SET_TOKEN").await?; + assert!( + names(&list).is_empty(), + "a deleted set leaves no tool: {list}" + ); + Ok(()) +} diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index 89d907c3d1..6c91a94eb8 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -138,6 +138,7 @@ pub fn workspaced_service() -> Router { post(edit_large_file_storage_config), ) .route("/edit_dbt_warehouses", post(edit_dbt_warehouses)) + .route("/edit_mcp_tool_sets", post(edit_mcp_tool_sets)) .route("/edit_ducklake_config", post(edit_ducklake_config)) .route("/list_ducklakes", get(list_ducklakes)) .route("/list_datatables", get(list_datatables)) @@ -320,6 +321,8 @@ pub struct WorkspaceSettings { #[serde(skip_serializing_if = "Option::is_none")] pub dbt_warehouses: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub mcp_tool_sets: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub large_file_storage: Option, #[serde(skip_serializing_if = "Option::is_none")] pub ducklake: Option, @@ -1201,6 +1204,7 @@ async fn get_settings( webhook_events, ai_config, dbt_warehouses, + mcp_tool_sets, large_file_storage, datatable, ducklake, @@ -2274,6 +2278,49 @@ async fn edit_dbt_warehouses( Ok("Updated the workspace's dbt warehouses".to_string()) } +#[derive(serde::Deserialize)] +struct EditMcpToolSets { + mcp_tool_sets: Option, +} + +/// The workspace's named MCP tool sets, each served at `/api/mcp/w/{workspace}/s/{name}/mcp`. +async fn edit_mcp_tool_sets( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(new_config): Json, +) -> Result { + require_admin(authed.is_admin, &authed.username)?; + let sets = new_config.mcp_tool_sets.filter(|s| !s.is_empty()); + if let Some(sets) = sets.as_ref() { + windmill_common::mcp_tool_sets::validate_tool_sets(sets)?; + } + let value = sets + .map(serde_json::to_value) + .transpose() + .map_err(|e| Error::internal_err(format!("serializing the MCP tool sets: {e}")))?; + let mut tx = db.begin().await?; + audit_log( + &mut *tx, + &authed, + "workspaces.edit_mcp_tool_sets", + ActionKind::Update, + &w_id, + Some(&authed.email), + Some([("mcp_tool_sets", format!("{value:?}").as_str())].into()), + ) + .await?; + sqlx::query!( + "UPDATE workspace_settings SET mcp_tool_sets = $1 WHERE workspace_id = $2", + value, + &w_id + ) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok("Updated the workspace's MCP tool sets".to_string()) +} + /// A fork's isolated storage is purged at deletion from the storage recorded at creation: under /// another location, its objects would outlive the fork untracked, and a same-id fork would /// read them. @@ -7973,6 +8020,7 @@ async fn update_workspace_settings( large_file_storage = source_ws.large_file_storage, ducklake = source_ws.ducklake, dbt_warehouses = source_ws.dbt_warehouses, + mcp_tool_sets = source_ws.mcp_tool_sets, datatable = source_ws.datatable, git_app_installations = source_ws.git_app_installations, add_admins_and_developers_to_forks = source_ws.add_admins_and_developers_to_forks @@ -15885,6 +15933,7 @@ pub enum SettingsEdit { DeleteSlackOAuth, Ducklake, DbtWarehouses, + McpToolSets, DeployUi, GuestJwtKey, PublicAppRateLimit, @@ -15957,6 +16006,7 @@ pub async fn apply_settings_edit( DeleteSlackOAuth => delete_slack_oauth_config(a, d, p).await?, Ducklake => edit_ducklake_config(a, d, p, settings_edit_body(edit, body)?).await?, DbtWarehouses => edit_dbt_warehouses(a, d, p, settings_edit_body(edit, body)?).await?, + McpToolSets => edit_mcp_tool_sets(a, d, p, settings_edit_body(edit, body)?).await?, #[cfg(feature = "enterprise")] DeployUi => edit_deploy_ui_config(a, d, p, settings_edit_body(edit, body)?).await?, #[cfg(not(feature = "enterprise"))] diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 19087df2bf..2f96aad9d6 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -152,7 +152,7 @@ pub(crate) async fn change_workspace_id( // Duplicate workspace settings (keep copy in old workspace for reference) info!("Duplicating workspace_settings table"); sqlx::query!( - "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", + "INSERT INTO workspace_settings (workspace_id, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, mcp_tool_sets, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler) SELECT $1, slack_team_id, slack_name, slack_command_script, slack_email, customer_id, plan, webhook, webhook_events, ai_config, large_file_storage, git_sync, default_app, default_scripts, deploy_ui, mute_critical_alerts, color, operator_settings, role_overrides, teams_command_script, teams_team_id, teams_team_name, git_app_installations, git_credentials, ducklake, dbt_warehouses, mcp_tool_sets, slack_oauth_client_id, slack_oauth_client_secret, slack_signing_secret, datatable, teams_team_guid, auto_invite, error_handler, success_handler, public_app_execution_limit_per_minute, error_handler_fallback_to_instance_alerts, guest_jwt_public_key, guest_jwt_jwks_url, add_admins_and_developers_to_forks, remote_deploy_target, remote_deploy_target_changed_at, variable_expiration_handler FROM workspace_settings WHERE workspace_id = $2", &rw.new_id, &old_id ) diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 3481cba6a5..4e37286232 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -4447,6 +4447,8 @@ paths: $ref: "#/components/schemas/DucklakeSettings" dbt_warehouses: $ref: "#/components/schemas/DbtWarehouses" + mcp_tool_sets: + $ref: "#/components/schemas/McpToolSets" datatable: $ref: "#/components/schemas/DataTableSettings" git_sync: @@ -5609,6 +5611,31 @@ paths: application/json: schema: {} + /w/{workspace}/workspaces/edit_mcp_tool_sets: + post: + summary: edit the workspace's MCP tool sets + operationId: editMcpToolSets + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + description: MCP tool sets, by name + required: true + content: + application/json: + schema: + type: object + properties: + mcp_tool_sets: + $ref: "#/components/schemas/McpToolSets" + responses: + "200": + description: status + content: + application/json: + schema: {} + /w/{workspace}/dbt/run_progress: post: summary: record the running job's settled dbt nodes @@ -39065,6 +39092,26 @@ components: required: - resource_path + McpToolSets: + type: object + description: >- + Named selections of scripts and flows, each served at + /api/mcp/w/{workspace}/s/{name}/mcp. A member signed in to a set gets the + scripts and flows of the set they can run, as tools. + additionalProperties: + type: object + properties: + scripts: + type: array + items: + type: string + flows: + type: array + items: + type: string + instructions: + type: string + DbtWarehouseConnection: type: object properties: 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 018490080f..6c1487afa4 100644 --- a/backend/windmill-api/src/ai_session_tools/gen/instructions.json +++ b/backend/windmill-api/src/ai_session_tools/gen/instructions.json @@ -289,7 +289,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? }`, `path` being `script/` or `flow/`. |\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`. 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? }`, `path` being `script/` or `flow/`. |\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`. 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| `mcp_tool_sets` | `{ : { scripts?: [paths], flows?: [paths], instructions? } }`: selections of scripts and flows, each served at `/api/mcp/w//s//mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run. |\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", "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## 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" } } diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 0a59323412..df722b856c 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -575,12 +575,18 @@ pub async fn run_server( // Setup MCP server #[allow(unused_variables)] - let (mcp_router, gateway_mcp_router, gateway_session_router, mcp_cancellation_token) = { + let ( + mcp_router, + gateway_mcp_router, + gateway_session_router, + tool_set_mcp_router, + mcp_cancellation_token, + ) = { #[cfg(feature = "mcp")] if server_mode || mcp_mode { use mcp::{ add_www_authenticate_header, add_www_authenticate_header_gateway, - extract_workspace_from_token, reject_token_query_param, + extract_tool_set_endpoint, extract_workspace_from_token, reject_token_query_param, }; let (mcp_router, session_router, mcp_cancellation_token) = setup_mcp_server( db.clone(), @@ -599,6 +605,14 @@ pub async fn run_server( .layer(axum::middleware::from_fn(reject_token_query_param)) .layer(axum::middleware::from_fn(add_www_authenticate_header)) .layer(axum::middleware::from_fn(extract_and_store_workspace_id)); + // A named tool set's URL: signed in to through Windmill's own consent page only, so + // without the external issuer's layer. + let tool_set_mcp_router = mcp_router + .clone() + .route_layer(from_extractor::()) + .layer(axum::middleware::from_fn(reject_token_query_param)) + .layer(axum::middleware::from_fn(add_www_authenticate_header)) + .layer(axum::middleware::from_fn(extract_tool_set_endpoint)); // Gateway MCP router — resolves workspace from token let gateway_mcp_router = mcp_router .route_layer(from_extractor::()) @@ -622,10 +636,17 @@ pub async fn run_server( workspaced_mcp_router, gateway_mcp_router, gateway_session_router, + tool_set_mcp_router, Some(mcp_cancellation_token), ) } else { - (Router::new(), Router::new(), Router::new(), None) + ( + Router::new(), + Router::new(), + Router::new(), + Router::new(), + None, + ) } #[cfg(not(feature = "mcp"))] @@ -633,6 +654,7 @@ pub async fn run_server( Router::new(), Router::new(), Router::new(), + Router::new(), Option::<()>::None, ) }; @@ -977,6 +999,10 @@ pub async fn run_server( "/mcp/w/{workspace_id}/mcp", mcp_router.clone().layer(mcp_cors.clone()), ) + .nest( + "/mcp/w/{workspace_id}/s/{tool_set}/mcp", + tool_set_mcp_router.layer(mcp_cors.clone()), + ) .nest("/mcp/gateway", gateway_mcp_router.layer(mcp_cors.clone())) .merge(gateway_session_router.layer(mcp_cors.clone())) .nest("/agent_workers", { @@ -1192,6 +1218,19 @@ pub async fn run_server( } }, ) + .route( + "/.well-known/oauth-protected-resource/api/mcp/w/{workspace_id}/s/{tool_set}/mcp", + { + #[cfg(feature = "mcp")] + { + get(mcp::oauth_server::tool_set_protected_resource_metadata) + } + #[cfg(not(feature = "mcp"))] + { + get(|| async { axum::http::StatusCode::NOT_FOUND }) + } + }, + ) // Gateway OAuth well-known endpoints .route( "/.well-known/oauth-authorization-server/api/mcp/gateway/oauth/server", diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index c817d314f3..a5607c781e 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -37,10 +37,13 @@ use std::sync::Arc; use std::time::Duration; use tokio_util::sync::CancellationToken; +use windmill_common::mcp_tool_sets::{ + get_tool_set, tool_set_of, tool_set_scopes, SET_SCOPE_PREFIX, +}; use windmill_mcp::common::SESSION_SCOPE; use windmill_mcp::server::{ LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner, - StreamableHttpServerConfig, StreamableHttpService, + StreamableHttpServerConfig, StreamableHttpService, ToolSetInstructions, }; use windmill_mcp::WorkspaceId; @@ -606,6 +609,74 @@ fn serves_session_toolset(scopes: &[String]) -> bool { #[derive(Clone, Copy)] pub struct McpEndpoint(pub &'static str); +/// The tool set a set URL serves: `/api/mcp/w/{workspace}/s/{tool_set}/mcp`. +#[derive(Clone)] +pub struct ToolSetEndpoint(pub String); + +/// Store a tool set URL's workspace and set in request extensions. +pub async fn extract_tool_set_endpoint( + Path((workspace_id, tool_set)): Path<(String, String)>, + mut request: Request, + next: Next, +) -> Response { + request.extensions_mut().insert(WorkspaceId(workspace_id)); + request.extensions_mut().insert(ToolSetEndpoint(tool_set)); + next.run(request).await +} + +/// Puts the current paths of the tool set a token is signed in to in place of its scopes, so an +/// admin's edit reaches open connections and a deleted set leaves no tool. On a set's URL, a +/// token signed in to anything else is refused, which sends the client back to sign in. +async fn expand_tool_set(db: &DB, request: &mut Request) -> Result<(), Response> { + let served = request + .extensions() + .get::() + .map(|e| e.0.clone()); + let held = request + .extensions() + .get::() + .and_then(|a| a.scopes.as_deref()) + .and_then(tool_set_of) + .map(str::to_string); + if let Some(served) = served { + if held.as_deref() != Some(served.as_str()) { + return Err(( + axum::http::StatusCode::UNAUTHORIZED, + format!("This URL serves the MCP tool set `{served}`: sign in to it"), + ) + .into_response()); + } + } + let Some(name) = held else { + return Ok(()); + }; + request.extensions_mut().insert(NoEndpointTools); + // Without a bound workspace the token keeps its unexpanded scopes, which reach no runnable. + let Some(w_id) = request + .extensions() + .get::() + .map(|w| w.0.clone()) + else { + return Ok(()); + }; + let set = get_tool_set(db, &w_id, &name) + .await + .map_err(|e| e.into_response())?; + let scopes = match &set { + Some(set) => tool_set_scopes(&name, set), + None => vec![format!("{SET_SCOPE_PREFIX}{name}")], + }; + if let Some(authed) = request.extensions_mut().get_mut::() { + authed.scopes = Some(scopes); + } + if let Some(instructions) = set.and_then(|s| s.instructions) { + request + .extensions_mut() + .insert(ToolSetInstructions(instructions)); + } + Ok(()) +} + /// Extract workspace ID from path and store it in request extensions pub async fn extract_and_store_workspace_id( Path(params): Path, @@ -626,6 +697,10 @@ fn www_authenticate_value(base_url: &str, endpoint: &str) -> String { } else { "mcp:all" }; + www_authenticate_with_scope(base_url, endpoint, scope) +} + +fn www_authenticate_with_scope(base_url: &str, endpoint: &str, scope: &str) -> String { format!( "Bearer resource_metadata=\"{base_url}/.well-known/oauth-protected-resource{endpoint}\", \ scope=\"{scope}\"" @@ -652,14 +727,24 @@ pub async fn add_www_authenticate_header( .body(axum::body::Body::from("Missing workspace_id in request")) .unwrap(); }; + let tool_set = request + .extensions() + .get::() + .map(|e| e.0.clone()); let response = next.run(request).await; // Only add header to 401 Unauthorized responses if response.status() == StatusCode::UNAUTHORIZED { let base_url = BASE_URL.load(); - let www_authenticate = - www_authenticate_value(&base_url, &format!("/api/mcp/w/{}/mcp", workspace_id)); + let www_authenticate = match tool_set { + Some(set) => www_authenticate_with_scope( + &base_url, + &format!("/api/mcp/w/{workspace_id}/s/{set}/mcp"), + &format!("{SET_SCOPE_PREFIX}{set}"), + ), + None => www_authenticate_value(&base_url, &format!("/api/mcp/w/{}/mcp", workspace_id)), + }; // Reconstruct response with the new header let (mut parts, body) = response.into_parts(); @@ -812,6 +897,7 @@ pub async fn setup_mcp_server( let cancellation_token = CancellationToken::new(); let session_manager = Arc::new(LocalSessionManager::default()); + let tool_set_db = db.clone(); let backend = WindmillBackend::new(db, user_db, base_internal_url, auth_cache); let session_runner = SessionRunner::new(backend.clone()); let runner = Runner::new(backend); @@ -847,10 +933,15 @@ pub async fn setup_mcp_server( "/", axum::routing::any({ let (service, session_service) = (service.clone(), session_service.clone()); - move |request: Request| { + let db = tool_set_db.clone(); + move |mut request: Request| { let (service, session_service) = (service.clone(), session_service.clone()); + let db = db.clone(); async move { use tower::ServiceExt; + if let Err(response) = expand_tool_set(&db, &mut request).await { + return response; + } let session = request.extensions().get::().is_some_and(|a| { serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) }); @@ -874,8 +965,12 @@ 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 = tool_set_db.clone(); async move { use tower::ServiceExt; + if let Err(response) = expand_tool_set(&db, &mut request).await { + return response; + } let response = if request.extensions().get::().is_some() { request.extensions_mut().insert(NoEndpointTools); service.oneshot(request).await diff --git a/backend/windmill-api/src/mcp/mod.rs b/backend/windmill-api/src/mcp/mod.rs index 6052e4d60f..665b013edc 100644 --- a/backend/windmill-api/src/mcp/mod.rs +++ b/backend/windmill-api/src/mcp/mod.rs @@ -13,6 +13,6 @@ mod utils; pub mod oauth_server; pub use core::{ add_www_authenticate_header, add_www_authenticate_header_gateway, - extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service, - reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint, + extract_and_store_workspace_id, extract_tool_set_endpoint, extract_workspace_from_token, + list_tools_service, reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint, }; diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index f07f563b32..5f2bf0ff45 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -20,7 +20,11 @@ use windmill_common::{ use crate::db::ApiAuthed; use windmill_api_auth::forbid_elevated_job_token; -use windmill_mcp::{common::SESSION_SCOPE, parse_mcp_scopes}; +use windmill_common::mcp_tool_sets::{get_tool_set, tool_set_of, SET_SCOPE_PREFIX}; +use windmill_mcp::{ + common::{scope::RUNNABLES_AS_TOOLS_SCOPE, SESSION_SCOPE}, + parse_mcp_scopes, +}; /// Token expiration for MCP OAuth tokens (1 week in seconds) const MCP_OAUTH_TOKEN_EXPIRATION_SECS: u64 = 7 * 24 * 60 * 60; @@ -248,7 +252,15 @@ fn granting_scopes() -> Vec { fn supported_scopes() -> Vec { let mut scopes = granting_scopes(); - scopes.extend(["mcp:read_only", "mcp:read_run", "mcp:runnables_as_tools"].map(String::from)); + scopes.extend( + [ + "mcp:read_only", + "mcp:read_run", + "mcp:runnables_as_tools", + "mcp:set:*", + ] + .map(String::from), + ); scopes } @@ -323,6 +335,22 @@ pub async fn protected_resource_metadata_by_path( )) } +/// GET /.well-known/oauth-protected-resource/api/mcp/w/:workspace_id/s/:tool_set/mcp +/// +/// Always names Windmill's own authorization server, external issuer or not: a tool set is +/// signed in to through Windmill's consent page. +pub async fn tool_set_protected_resource_metadata( + Path((workspace_id, tool_set)): Path<(String, String)>, +) -> Json { + let base_url = BASE_URL.load(); + Json(ProtectedResourceMetadata { + resource: format!("{base_url}/api/mcp/w/{workspace_id}/s/{tool_set}/mcp"), + authorization_servers: vec![format!("{base_url}/api/w/{workspace_id}/mcp/oauth/server")], + scopes_supported: Some(vec![format!("{SET_SCOPE_PREFIX}{tool_set}")]), + bearer_methods_supported: Some(vec!["header".to_string()]), + }) +} + /// Schemes that a browser executes as script or uses to read local content. The /// consent page navigates the user's browser to the registered redirect_uri /// (`window.location` / anchor `href`), so accepting any of these turns dynamic @@ -949,6 +977,35 @@ async fn oauth_approve_inner( scopes.push(SESSION_SCOPE.to_string()); } + // A tool set is resolved in the token's own workspace on every request, so its grant is + // that set alone, bound to the workspace it exists in. + if let Some(name) = tool_set_of(&scopes).map(str::to_string) { + let Some(workspace_id) = workspace_id else { + return Err(Error::BadRequest( + "A tool set belongs to one workspace: sign in from its URL".to_string(), + )); + }; + if scopes + .iter() + .filter(|s| s.starts_with(SET_SCOPE_PREFIX)) + .count() + > 1 + { + return Err(Error::BadRequest( + "A connection signs in to one tool set".to_string(), + )); + } + if get_tool_set(db, workspace_id, &name).await?.is_none() { + return Err(Error::NotFound(format!( + "Workspace {workspace_id} has no MCP tool set `{name}`" + ))); + } + scopes = vec![ + format!("{SET_SCOPE_PREFIX}{name}"), + RUNNABLES_AS_TOOLS_SCOPE.to_string(), + ]; + } + // 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 // unrestricted approver (interactive session, scopes None) grants freely, diff --git a/backend/windmill-api/src/workspace_settings_document.rs b/backend/windmill-api/src/workspace_settings_document.rs index a670340706..b59b2f3a2f 100644 --- a/backend/windmill-api/src/workspace_settings_document.rs +++ b/backend/windmill-api/src/workspace_settings_document.rs @@ -81,6 +81,7 @@ struct SettingsRow { slack_oauth_client_secret: Option, ducklake: Option, dbt_warehouses: Option, + mcp_tool_sets: Option, deploy_ui: Option, teams_command_script: Option, public_app_execution_limit_per_minute: Option, @@ -355,7 +356,7 @@ pub async fn load_settings_document( ai_config, large_file_storage, git_sync, default_app, default_scripts, workspace.name AS name, mute_critical_alerts, color, operator_settings, datatable, slack_team_id, slack_name, slack_command_script, - slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, deploy_ui, + slack_oauth_client_id, slack_oauth_client_secret, ducklake, dbt_warehouses, mcp_tool_sets, deploy_ui, teams_command_script, public_app_execution_limit_per_minute, guest_jwt_public_key, guest_jwt_jwks_url, error_handler_fallback_to_instance_alerts, add_admins_and_developers_to_forks @@ -416,7 +417,7 @@ pub async fn load_settings_document( // In the order `wmill sync pull` has always written settings.yaml. A key that predates the // document and is not marked `always` is written only when set, as it always was; a key // added since is always written, so a pulled file states it and from then on manages it. - let entries: [(&str, Option, bool); 33] = [ + let entries: [(&str, Option, bool); 34] = [ ("auto_invite", row.auto_invite, false), ("webhook", webhook.map(Value::String), false), ("webhook_events", row.webhook_events.map(|e| json!(e)), true), @@ -465,6 +466,7 @@ pub async fn load_settings_document( ), ("ducklake", row.ducklake, true), ("dbt_warehouses", row.dbt_warehouses, true), + ("mcp_tool_sets", row.mcp_tool_sets, true), ("deploy_ui", row.deploy_ui, true), ( "teams_command_script", @@ -771,6 +773,7 @@ const KNOWN_KEYS: &[&str] = &[ "slack_oauth_client_secret", "ducklake", "dbt_warehouses", + "mcp_tool_sets", "deploy_ui", "teams_command_script", "public_app_execution_limit_per_minute", @@ -1628,6 +1631,14 @@ fn plan_document( |v| json!({ "dbt_warehouses": v }), ); + let mcp_tool_sets = p.managed("mcp_tool_sets"); + p.simple( + "mcp_tool_sets", + mcp_tool_sets, + Target::Edit(SettingsEdit::McpToolSets), + |v| json!({ "mcp_tool_sets": v }), + ); + let deploy_ui = p.managed("deploy_ui"); p.simple( "deploy_ui", diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 90710d0933..49555295a2 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -98,6 +98,7 @@ pub mod job_provenance; pub mod jobs; pub mod jwt; pub mod login_rate_limit; +pub mod mcp_tool_sets; pub mod more_serde; pub mod oauth2; #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] diff --git a/backend/windmill-common/src/mcp_tool_sets.rs b/backend/windmill-common/src/mcp_tool_sets.rs new file mode 100644 index 0000000000..65473b6285 --- /dev/null +++ b/backend/windmill-common/src/mcp_tool_sets.rs @@ -0,0 +1,146 @@ +//! Named MCP tool sets: a workspace admin's selection of scripts and flows, served at its own +//! MCP URL. A set narrows and never grants: a member signed in to it gets the runnables of the +//! set they can see and run themselves. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use crate::{ + db::DB, + error::{Error, Result}, +}; + +/// Marks a token signed in to a tool set: `mcp:set:`. +pub const SET_SCOPE_PREFIX: &str = "mcp:set:"; + +const MAX_NAME_LEN: usize = 50; +const MAX_INSTRUCTIONS_LEN: usize = 4000; + +#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] +pub struct McpToolSet { + /// Script paths: `*`, an exact path, or a `/*` subtree. + #[serde(default)] + pub scripts: Vec, + /// Flow paths, as for scripts. + #[serde(default)] + pub flows: Vec, + /// Added to the server's instructions for clients connected to this set. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub instructions: Option, +} + +/// By name, as stored in `workspace_settings.mcp_tool_sets`. +pub type McpToolSets = BTreeMap; + +pub fn validate_tool_set_name(name: &str) -> Result<()> { + let usable = !name.is_empty() + && name.len() <= MAX_NAME_LEN + && name + .chars() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-'); + if usable { + Ok(()) + } else { + Err(Error::BadRequest(format!( + "`{name}` is not a usable tool set name: use up to {MAX_NAME_LEN} lowercase letters, digits, `_` and `-`" + ))) + } +} + +pub fn validate_tool_sets(sets: &McpToolSets) -> Result<()> { + for (name, set) in sets { + validate_tool_set_name(name)?; + if set.scripts.is_empty() && set.flows.is_empty() { + return Err(Error::BadRequest(format!( + "tool set `{name}` selects no scripts or flows" + ))); + } + for path in set.scripts.iter().chain(&set.flows) { + // Paths are joined with commas into selection scopes, and only `*`, an exact path + // and a trailing `/*` are matched. + let base = path.strip_suffix("/*").unwrap_or(path); + let usable = path == "*" + || (!base.is_empty() + && !base.contains(['*', ',', ' ']) + && ["u/", "f/", "g/"].iter().any(|p| base.starts_with(p))); + if !usable { + return Err(Error::BadRequest(format!( + "`{path}` in tool set `{name}` is not a script or flow path: use `*`, a path, or `/*`" + ))); + } + } + if set + .instructions + .as_ref() + .is_some_and(|i| i.len() > MAX_INSTRUCTIONS_LEN) + { + return Err(Error::BadRequest(format!( + "the instructions of tool set `{name}` are longer than {MAX_INSTRUCTIONS_LEN} characters" + ))); + } + } + Ok(()) +} + +pub async fn get_tool_set(db: &DB, w_id: &str, name: &str) -> Result> { + let value = sqlx::query_scalar!( + "SELECT mcp_tool_sets -> $2 FROM workspace_settings WHERE workspace_id = $1", + w_id, + name + ) + .fetch_optional(db) + .await? + .flatten(); + value + .map(serde_json::from_value) + .transpose() + .map_err(|e| Error::internal_err(format!("reading tool set `{name}`: {e}"))) +} + +/// The set a token is signed in to, if any. +pub fn tool_set_of(scopes: &[String]) -> Option<&str> { + scopes.iter().find_map(|s| s.strip_prefix(SET_SCOPE_PREFIX)) +} + +/// What a token signed in to `name` acts with: the set as a selection of scripts and flows, with +/// no endpoint tools. +pub fn tool_set_scopes(name: &str, set: &McpToolSet) -> Vec { + let mut scopes = vec![ + format!("{SET_SCOPE_PREFIX}{name}"), + "mcp:runnables_as_tools".to_string(), + ]; + if !set.scripts.is_empty() { + scopes.push(format!("mcp:scripts:{}", set.scripts.join(","))); + } + if !set.flows.is_empty() { + scopes.push(format!("mcp:flows:{}", set.flows.join(","))); + } + scopes +} + +#[cfg(test)] +mod tests { + use super::*; + + fn set(paths: &[&str]) -> McpToolSets { + BTreeMap::from([( + "support".to_string(), + McpToolSet { + scripts: paths.iter().map(|p| p.to_string()).collect(), + flows: vec![], + instructions: None, + }, + )]) + } + + #[test] + fn paths_are_patterns_the_matchers_read() { + assert!(validate_tool_sets(&set(&["*", "f/ops/*", "u/alice/report"])).is_ok()); + for bad in ["f/ops/*/x", "f/a,f/b", "ops/x", "f/*x", ""] { + assert!(validate_tool_sets(&set(&[bad])).is_err(), "{bad}"); + } + assert!(validate_tool_sets(&set(&[])).is_err()); + assert!(validate_tool_set_name("Support").is_err()); + } +} diff --git a/backend/windmill-mcp/src/common/scope.rs b/backend/windmill-mcp/src/common/scope.rs index 1d782c4c54..18d0b4ef75 100644 --- a/backend/windmill-mcp/src/common/scope.rs +++ b/backend/windmill-mcp/src/common/scope.rs @@ -3,6 +3,8 @@ //! Contains utilities for parsing and matching MCP token scopes to determine //! which scripts, flows, and endpoints a token has access to. +use windmill_common::mcp_tool_sets::SET_SCOPE_PREFIX; + /// Configuration for MCP scopes parsed from token scopes #[derive(Debug, Clone, Default)] pub struct McpScopeConfig { @@ -31,6 +33,10 @@ pub struct McpScopeConfig { /// No endpoint tools on any URL: set by `mcp:read_only`, `mcp:read_run` and /// `mcp:runnables_as_tools`, and by the server on `/api/mcp` for a selection. pub no_endpoints: bool, + /// Named tool sets (`mcp:set:`). The scope selects nothing itself: the server adds the + /// set's paths as `mcp:scripts:`/`mcp:flows:` on each request, so an unexpanded set token + /// reaches no runnable. + pub sets: Vec, } impl McpScopeConfig { @@ -106,6 +112,9 @@ impl McpScopeConfig { if requested.all { return false; } + if !requested.sets.iter().all(|s| self.sets.contains(s)) { + return false; + } if requested.favorites && !self.favorites { return false; } @@ -243,6 +252,12 @@ pub fn parse_mcp_scopes(scopes: &[String]) -> Result { continue; } + if let Some(name) = scope.strip_prefix(SET_SCOPE_PREFIX) { + config.sets.push(name.to_string()); + config.no_endpoints = true; + continue; + } + if let Some(ids) = scope.strip_prefix("mcp:workspaces:") { config .workspaces @@ -331,6 +346,19 @@ fn resource_matches_pattern(resource_path: &str, pattern: &str) -> bool { mod tests { use super::*; + #[test] + fn a_tool_set_is_approved_only_by_a_holder_of_it() { + let parse = |s: &[&str]| { + parse_mcp_scopes(&s.iter().map(|s| s.to_string()).collect::>()).unwrap() + }; + let set = parse(&["mcp:set:support"]); + assert!(set.no_endpoints && set.scripts.is_empty() && set.flows.is_empty()); + assert!(!parse(&["mcp:scripts:f/x/*"]).contains(&set)); + assert!(!parse(&["mcp:set:other"]).contains(&set)); + assert!(parse(&["mcp:set:support"]).contains(&set)); + assert!(parse(&["mcp:all"]).contains(&set)); + } + #[test] fn test_parse_legacy_scopes() { let scopes = vec!["mcp:all".to_string()]; diff --git a/backend/windmill-mcp/src/common/types.rs b/backend/windmill-mcp/src/common/types.rs index 7d91e94255..0d980b85dc 100644 --- a/backend/windmill-mcp/src/common/types.rs +++ b/backend/windmill-mcp/src/common/types.rs @@ -27,6 +27,11 @@ pub struct MultiWorkspaceMcp; #[derive(Clone, Debug)] pub struct NoEndpointTools; +/// What the admin wrote for the tool set a connection is signed in to, added to the tools +/// server's instructions. +#[derive(Clone, Debug)] +pub struct ToolSetInstructions(pub String); + /// Raw bearer token wrapper for Axum extensions. In multi-workspace mode the /// runner needs the raw token to re-resolve auth for each requested workspace. #[derive(Clone, Debug)] diff --git a/backend/windmill-mcp/src/server/mod.rs b/backend/windmill-mcp/src/server/mod.rs index 69ce01be4f..0708521109 100644 --- a/backend/windmill-mcp/src/server/mod.rs +++ b/backend/windmill-mcp/src/server/mod.rs @@ -13,7 +13,9 @@ mod session; pub mod tools; // Re-export main types -pub use crate::common::types::{McpToken, MultiWorkspaceMcp, NoEndpointTools, WorkspaceInfo}; +pub use crate::common::types::{ + McpToken, MultiWorkspaceMcp, NoEndpointTools, ToolSetInstructions, WorkspaceInfo, +}; pub use backend::{ BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess, }; diff --git a/backend/windmill-mcp/src/server/runner.rs b/backend/windmill-mcp/src/server/runner.rs index 6af8eebc1b..1b6b9a1b56 100644 --- a/backend/windmill-mcp/src/server/runner.rs +++ b/backend/windmill-mcp/src/server/runner.rs @@ -11,8 +11,8 @@ use crate::common::transform::{ short_name_last_segments, }; use crate::common::types::{ - McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolableItem, - WorkspaceId, + McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolSetInstructions, + ToolableItem, WorkspaceId, }; use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome}; use crate::server::endpoints::{ @@ -23,7 +23,7 @@ use crate::server::tools::create_tool_from_item; use rmcp::handler::server::ServerHandler; use rmcp::model::{ CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, - Implementation, InitializeRequestParams, InitializeResult, ListPromptsResult, + DiscoverResult, Implementation, InitializeRequestParams, InitializeResult, ListPromptsResult, ListResourceTemplatesResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams, ProtocolVersion, ServerCapabilities, ServerInfo, SubscriptionFilter, }; @@ -178,6 +178,19 @@ impl Runner { Self { backend: Arc::new(backend), list_changes: Arc::default() } } + /// The server's instructions, followed by those of the tool set the caller signed in to. + fn info_for(&self, context: &RequestContext) -> ServerInfo { + let info = self.get_info(); + let set = context + .extensions + .get::() + .and_then(|parts| parts.extensions.get::()); + match (set, info.instructions.clone()) { + (Some(set), Some(own)) => info.with_instructions(format!("{own}\n\n{}", set.0)), + _ => info, + } + } + /// Extract authentication, the workspace mode and the HTTP request itself /// from the request context pub(super) fn extract_context( @@ -568,7 +581,7 @@ impl ServerHandler for Runner { context: RequestContext, ) -> Result { context.peer.set_peer_info(request.clone()); - let mut info = self.get_info(); + let mut info = self.info_for(&context); if let Some(tools) = info.capabilities.tools.as_mut() { tools.list_changed = None; } @@ -578,6 +591,16 @@ impl ServerHandler for Runner { Ok(info) } + async fn discover( + &self, + context: RequestContext, + ) -> Result { + Ok(DiscoverResult::from_server_info( + SUPPORTED_PROTOCOL_VERSIONS.to_vec(), + self.info_for(&context), + )) + } + /// `None` for a request that asks for nothing this server sends, so the client is /// told the subscription is unsupported rather than acked with an empty filter. fn accepted_subscription_filter( diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index ec0035de79..feaf0fe789 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -70,6 +70,7 @@ export interface SimplifiedSettings { slack_oauth_client_secret?: string; ducklake?: any; dbt_warehouses?: any; + mcp_tool_sets?: any; deploy_ui?: any; teams_command_script?: string | null; public_app_execution_limit_per_minute?: number | null; @@ -86,6 +87,7 @@ export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ "datatable_permissions", "ducklake", "dbt_warehouses", + "mcp_tool_sets", "deploy_ui", "teams_command_script", "public_app_execution_limit_per_minute", diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index bf2230cfd0..618caa16e0 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -8527,6 +8527,7 @@ write a secret you were not given: keep the placeholder. | \`protection_rules\` | \`{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { : { catalog, storage, ... } } }\`. | | \`dbt_warehouses\` | dbt warehouse connections. | +| \`mcp_tool_sets\` | \`{ : { scripts?: [paths], flows?: [paths], instructions? } }\`: selections of scripts and flows, each served at \`/api/mcp/w//s//mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run. | | \`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. | @@ -8554,7 +8555,7 @@ With \`includeSettings: true\` in \`wmill.yaml\`, \`wmill sync pull\` writes the \`settings.yaml\`, secrets encrypted with the workspace key (plaintext only with \`plainSecrets\`), and \`wmill sync push\` applies it. Unlike a partial apply, a push treats the file as the whole document: a setting the file omits is cleared, except \`operator_settings\`, \`role_overrides\`, \`color\`, the auto-invite -instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`deploy_ui\`, \`teams_command_script\`, +instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`mcp_tool_sets\`, \`deploy_ui\`, \`teams_command_script\`, \`public_app_execution_limit_per_minute\`, \`guest_jwt_public_key\`, \`guest_jwt_jwks_url\`, \`error_handler_fallback_to_instance_alerts\` and \`add_admins_and_developers_to_forks\`, which are managed only when the file states them. diff --git a/frontend/src/lib/components/mcp/McpScopeSelector.svelte b/frontend/src/lib/components/mcp/McpScopeSelector.svelte index 35b815fcff..ce8dee10e8 100644 --- a/frontend/src/lib/components/mcp/McpScopeSelector.svelte +++ b/frontend/src/lib/components/mcp/McpScopeSelector.svelte @@ -29,6 +29,9 @@ * endpoints are left out, and since `mcp:all` is the full toolset, "All scripts/flows" * is written as `mcp:scripts:* mcp:flows:*`. */ runnablesOnly?: boolean + /** A workspace tool set: no favorites, which are each member's own, and no hub scripts, as + * a set holds scripts and flows alone. Implies `runnablesOnly`. */ + toolSet?: boolean } let { @@ -36,8 +39,10 @@ scope = $bindable(), initialScope, readOnly = false, - runnablesOnly = false + runnablesOnly: _runnablesOnly = false, + toolSet = false }: Props = $props() + const runnablesOnly = $derived(_runnablesOnly || toolSet) // 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 @@ -68,7 +73,9 @@ const parsedInitial = parseInitialScope(initialScope) - let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>(parsedInitial.mode) + let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>( + toolSet && parsedInitial.mode === 'favorites' ? 'folder' : parsedInitial.mode + ) let selectedFolders = $state(parsedInitial.folders) let allFolders = $state([]) let loadingFolders = $state(false) @@ -568,12 +575,14 @@ Scope {#snippet children({ item })} - + {#if !toolSet} + + {/if} {/if} -
+
Hub scripts (optional) {#if loadingApps}
Loading...
diff --git a/frontend/src/lib/components/workspaceSettings/McpToolSetsSettings.svelte b/frontend/src/lib/components/workspaceSettings/McpToolSetsSettings.svelte new file mode 100644 index 0000000000..b558a7f7b8 --- /dev/null +++ b/frontend/src/lib/components/workspaceSettings/McpToolSetsSettings.svelte @@ -0,0 +1,188 @@ + + + + + + +
+ {#each mcpToolSets.sets as set, i (set.id)} +
+
+
+ Name + +
+ { + mcpToolSets.sets = mcpToolSets.sets.filter((_, j) => j !== i) + }} + /> +
+
+ Scripts and flows + +
+
+ Instructions + + Sent to the AI client along with the tools, for example which flow answers which question. + + +
+
+ URL + +
+
+ {/each} +
+ +
+
+ + onDiscard?.()} + saveLabel="Save tool sets" +/> diff --git a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte index 7097a30d31..839efcb97d 100644 --- a/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/oauth/mcp_authorize/+page@(root).svelte @@ -13,6 +13,7 @@ import { UserService, WorkspaceService } from '$lib/gen' import { listEveryWorkspace } from '$lib/mcpAuth' import { sendUserToast } from '$lib/toast' + import { logFeatureUsage } from '$lib/utils/featureUsage' import Check from 'lucide-svelte/icons/check' // Get OAuth params from URL @@ -32,7 +33,9 @@ askedScopes.includes('mcp:read_run') ? askedScopes.filter((s) => s !== 'mcp:read_only' && s !== 'mcp:read_run') : askedScopes - let scopes = $state([]) + // A tool set's URL asks for that set, which its workspace's admins chose: nothing to pick. + const toolSet = askedScopes.find((s) => s.startsWith('mcp:set:'))?.slice('mcp:set:'.length) + let scopes = $state(toolSet ? [`mcp:set:${toolSet}`, 'mcp:runnables_as_tools'] : []) let access = $state() let oauthState = page.url.searchParams.get('state') || '' let codeChallenge = page.url.searchParams.get('code_challenge') || '' @@ -176,6 +179,7 @@ params.set('state', data.state) } const url = `${redirectUri}?${params.toString()}` + if (toolSet) logFeatureUsage('mcp_tool_set', 'connected') success = true successRedirectUrl = url loading = false @@ -278,33 +282,40 @@
{/if} -
- w.value) - : pickedWorkspaces - : [workspaceId]} - initialScopes={requestedScopes} - bind:scopes - bind:access={() => access, setAccess} - > - {#snippet afterAccess()} - {#if isSuperAdmin} - superAdmin, setSuperAdmin} - options={{ - right: 'Superadmin rights', - rightTooltip: - 'The token carries your superadmin rights: admin in every workspace of the instance, including ones you are not a member of.' - }} - size="xs" - /> - {/if} - {/snippet} - -
+ {#if toolSet} +

+ It gets the {toolSet} tool set: the scripts + and flows its admins put in it that you can run, each as a tool. +

+ {:else} +
+ w.value) + : pickedWorkspaces + : [workspaceId]} + initialScopes={requestedScopes} + bind:scopes + bind:access={() => access, setAccess} + > + {#snippet afterAccess()} + {#if isSuperAdmin} + superAdmin, setSuperAdmin} + options={{ + right: 'Superadmin rights', + rightTooltip: + 'The token carries your superadmin rights: admin in every workspace of the instance, including ones you are not a member of.' + }} + size="xs" + /> + {/if} + {/snippet} + +
+ {/if}
diff --git a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte index 777802ca2e..7b3b659413 100644 --- a/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/workspace_settings/+page.svelte @@ -91,6 +91,10 @@ convertDbtSettingsFromBackend, type DbtSettingsType } from '$lib/components/workspaceSettings/DbtSettings.svelte' + import McpToolSetsSettings, { + convertMcpToolSetsFromBackend, + type McpToolSetsType + } from '$lib/components/workspaceSettings/McpToolSetsSettings.svelte' import DucklakeSettings, { convertDucklakeSettingsFromBackend, type DucklakeSettingsType @@ -362,6 +366,8 @@ let dbtSettings: DbtSettingsType = $state({ warehouses: [] }) let dbtSavedSettings: DbtSettingsType = $state(untrack(() => dbtSettings)) + let mcpToolSets: McpToolSetsType = $state({ sets: [] }) + let mcpToolSetsSaved: McpToolSetsType = $state(untrack(() => mcpToolSets)) let ducklakeSettings: DucklakeSettingsType = $state({ ducklakes: [] }) let ducklakeSavedSettings: DucklakeSettingsType = $state(untrack(() => ducklakeSettings)) @@ -587,6 +593,7 @@ | 'volume_storage' | 'ducklake' | 'dbt' + | 'mcp_tool_sets' | 'git_sync' | 'default_app' | 'native_triggers' @@ -913,6 +920,8 @@ dataTableSettings = convertDataTableSettingsFromBackend(settings.datatable) dbtSettings = convertDbtSettingsFromBackend(settings.dbt_warehouses) dbtSavedSettings = clone(dbtSettings) + mcpToolSets = convertMcpToolSetsFromBackend(settings.mcp_tool_sets) + mcpToolSetsSaved = clone(mcpToolSets) ducklakeSettings = convertDucklakeSettingsFromBackend(settings.ducklake) ducklakeSavedSettings = clone(ducklakeSettings) @@ -1451,6 +1460,11 @@ return getDucklakeSettingsInitialAndModifiedValues() case 'dbt': return getDbtSettingsInitialAndModifiedValues() + case 'mcp_tool_sets': + return { + savedValue: { mcpToolSets: mcpToolSetsSaved }, + modifiedValue: { mcpToolSets } + } case 'dev_workspace': return getDeploySettingsInitialAndModifiedValues() case 'webhook': @@ -1541,6 +1555,9 @@ case 'dbt': dbtSettings = clone(dbtSavedSettings) break + case 'mcp_tool_sets': + mcpToolSets = clone(mcpToolSetsSaved) + break case 'default_app': discardDefaultAppSettingsChanges() break @@ -1569,6 +1586,12 @@ aiId: 'workspace-settings-ai', aiDescription: 'Windmill AI workspace settings' }, + { + id: 'mcp_tool_sets', + label: 'MCP tool sets', + aiId: 'workspace-settings-mcp-tool-sets', + aiDescription: 'Named selections of scripts and flows served at their own MCP URL' + }, { id: 'premium', label: 'Premium plans', @@ -2717,6 +2740,14 @@ export async function main( s3ResourceSettings = clone(s3ResourceSavedSettings) }} /> + {:else if tab == 'mcp_tool_sets'} + { + mcpToolSets = clone(mcpToolSetsSaved) + }} + /> {:else if tab == 'dbt'} : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | \`ducklake\` | \`{ ducklakes: { : { catalog, storage, ... } } }\`. | | \`dbt_warehouses\` | dbt warehouse connections. | +| \`mcp_tool_sets\` | \`{ : { scripts?: [paths], flows?: [paths], instructions? } }\`: selections of scripts and flows, each served at \`/api/mcp/w//s//mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run. | | \`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. | diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md index 6bc8cdccbe..5594d6e8d5 100644 --- a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -50,6 +50,7 @@ write a secret you were not given: keep the placeholder. | `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. | | `dbt_warehouses` | dbt warehouse connections. | +| `mcp_tool_sets` | `{ : { scripts?: [paths], flows?: [paths], instructions? } }`: selections of scripts and flows, each served at `/api/mcp/w//s//mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run. | | `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. | @@ -77,7 +78,7 @@ With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the docum `settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and `wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite -instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, +instance groups, and the keys `ducklake`, `dbt_warehouses`, `mcp_tool_sets`, `deploy_ui`, `teams_command_script`, `public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and `add_admins_and_developers_to_forks`, which are managed only when the file states them. diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md index ae2277e1b9..71b5d26d70 100644 --- a/system_prompts/base/workspace-settings.md +++ b/system_prompts/base/workspace-settings.md @@ -45,6 +45,7 @@ write a secret you were not given: keep the placeholder. | `protection_rules` | `{ : { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { : } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | | `ducklake` | `{ ducklakes: { : { catalog, storage, ... } } }`. | | `dbt_warehouses` | dbt warehouse connections. | +| `mcp_tool_sets` | `{ : { scripts?: [paths], flows?: [paths], instructions? } }`: selections of scripts and flows, each served at `/api/mcp/w//s//mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run. | | `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. | @@ -73,7 +74,7 @@ With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the docum `settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and `wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole document: a setting the file omits is cleared, except `operator_settings`, `role_overrides`, `color`, the auto-invite -instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, +instance groups, and the keys `ducklake`, `dbt_warehouses`, `mcp_tool_sets`, `deploy_ui`, `teams_command_script`, `public_app_execution_limit_per_minute`, `guest_jwt_public_key`, `guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and `add_admins_and_developers_to_forks`, which are managed only when the file states them.