From 50feb9ddba78419930b1795fb011ff4ff3d6f12e Mon Sep 17 00:00:00 2001 From: hugocasa Date: Mon, 26 Oct 2026 17:16:18 +0100 Subject: [PATCH] fix: serve marked MCP sign-ins the session toolset on the per-workspace URL too Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- backend/windmill-api/src/lib.rs | 17 ++++----- backend/windmill-api/src/mcp/core.rs | 38 ++++++++----------- backend/windmill-api/src/mcp/oauth_server.rs | 9 ++--- backend/windmill-mcp/src/common/scope.rs | 2 +- .../lib/components/mcp/McpAccessPicker.svelte | 2 +- .../settings/EditTokenScopesModal.svelte | 2 +- 7 files changed, 32 insertions(+), 40 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1bb30c21e9..ef87f1c4dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -66,7 +66,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/mcp/session/`), 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 `/api/mcp/gateway` gives the session toolset to an `mcp:all` token carrying `mcp:session` (added by the gateway OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/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). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). +- **Windmill MCP server**: `/api/mcp` gives a token with `mcp:all` the AI session's GLOBAL toolset (`backend/windmill-api/src/mcp/session/`), and a token scoped to a selection of scripts and flows the tools server's per-runnable tools, without endpoint tools. The tools server's own URLs, `/api/mcp/w/{workspace}/mcp` and `/api/mcp/gateway`, keep serving existing tokens, endpoint scopes included, except that they give the session toolset to an `mcp:all` token carrying `mcp:session` (added by the OAuth approve, kept across scope edits) or `mcp:read_only`/`mcp:read_run`. Every tool takes a `workspace_id`; the token bounds which (its bound workspace, the `mcp:workspaces:` list, or all of its owner's). What a model reads there (tool names, descriptions, input schemas, instructions, `get_instructions` texts) is generated from the session's TypeScript into `session/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). What a tool *does* is written twice, in `chat/global/core.ts` and in a Rust handler: a behaviour change on one side must be mirrored on the other, and a new session tool is either implemented in Rust or added to `EDITOR_ONLY` (a `cargo test` in `session/mod.rs` fails otherwise). - **Session recorder**: `frontend/src/lib/components/recording/` is also the recorder `wmill app dev --recording` serves, vendored into the CLI as `cli/src/commands/app/devRecorderBundle.gen.ts`. After changing `rawAppSnapshot.ts` or `rawAppRecording.svelte.ts`, run `bun run gen:dev-recorder` from `cli/` (`cli/test/dev_recorder_bundle_unit.test.ts` fails otherwise). - **Raw-app policy**: `frontend/src/lib/components/raw_apps/rawAppPolicy.ts` also derives the policy the server's raw-app deploy stores, vendored into the bundle job as `backend/windmill-api/src/apps_raw_policy.gen.js`. After changing it or anything it imports, run `bun run gen:app-policy` from `cli/` (`cli/test/app_policy_bundle_unit.test.ts` fails otherwise). It rides in the job rather than being read from the CLI the job runs because the images install `windmill-cli` unpinned, so an image can carry one older than its server. diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index 2acffd58ed..446a585d35 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -577,14 +577,13 @@ pub async fn run_server( add_www_authenticate_header, add_www_authenticate_header_gateway, extract_workspace_from_token, reject_token_query_param, }; - let (mcp_router, gateway_router, session_router, mcp_cancellation_token) = - setup_mcp_server( - db.clone(), - user_db, - _base_internal_url.clone(), - auth_cache.clone(), - ) - .await?; + let (mcp_router, session_router, mcp_cancellation_token) = setup_mcp_server( + db.clone(), + user_db, + _base_internal_url.clone(), + auth_cache.clone(), + ) + .await?; // Workspace-scoped MCP router let workspaced_mcp_router = mcp_router .clone() @@ -593,7 +592,7 @@ pub async fn run_server( .layer(axum::middleware::from_fn(add_www_authenticate_header)) .layer(axum::middleware::from_fn(extract_and_store_workspace_id)); // Gateway MCP router — resolves workspace from token - let gateway_mcp_router = gateway_router + let gateway_mcp_router = mcp_router .route_layer(from_extractor::()) .layer(axum::middleware::from_fn(extract_workspace_from_token)) .layer(axum::middleware::from_fn(reject_token_query_param)) diff --git a/backend/windmill-api/src/mcp/core.rs b/backend/windmill-api/src/mcp/core.rs index da90cdfbc6..52a6a32014 100644 --- a/backend/windmill-api/src/mcp/core.rs +++ b/backend/windmill-api/src/mcp/core.rs @@ -504,13 +504,11 @@ fn scoped_to_selection(scopes: &[String]) -> bool { mcp.clone().next().is_some() && !mcp.any(|scope| scope == "mcp:all") } -/// Set on a request whose token `/api/mcp/gateway` serves the session's toolset rather than -/// the tools server: an `mcp:all` grant marked `mcp:session`, or narrowed by `mcp:read_only` / -/// `mcp:read_run`, which leave the tools server only `list_workspaces` there. -#[derive(Clone, Copy)] -pub struct McpSessionGrant; - -fn serves_session_on_gateway(scopes: &[String]) -> bool { +/// Whether the tools server's URLs (`/api/mcp/gateway`, `/api/mcp/w/{workspace}/mcp`) serve +/// a token the session's toolset: an `mcp:all` grant marked `mcp:session`, or narrowed by +/// `mcp:read_only` / `mcp:read_run`, which the consent page describes as session access. +/// Every other token there keeps the tools server it was issued for. +fn serves_session_toolset(scopes: &[String]) -> bool { scopes.iter().any(|scope| scope == "mcp:all") && scopes .iter() @@ -647,13 +645,9 @@ pub async fn extract_workspace_from_token( .await { Ok(Some(row)) => { - let scopes = row.scopes.as_deref().unwrap_or_default(); - if scoped_to_selection(scopes) { + if scoped_to_selection(row.scopes.as_deref().unwrap_or_default()) { request.extensions_mut().insert(McpSelection); } - if serves_session_on_gateway(scopes) { - request.extensions_mut().insert(McpSessionGrant); - } match row.workspace_id { Some(workspace_id) => { request @@ -724,7 +718,7 @@ pub async fn setup_mcp_server( user_db: UserDB, base_internal_url: String, auth_cache: Arc, -) -> anyhow::Result<(Router, Router, Router, CancellationToken)> { +) -> anyhow::Result<(Router, Router, CancellationToken)> { let cancellation_token = CancellationToken::new(); let session_manager = Arc::new(LocalSessionManager::default()); @@ -759,10 +753,7 @@ pub async fn setup_mcp_server( let service = StreamableHttpService::new(move || Ok(runner.clone()), session_manager, service_config); - let router = Router::new().route_service("/", service.clone()); - // `/api/mcp/gateway` keeps the tools server for every token it served before the - // session's toolset existed, and answers a `McpSessionGrant` with that toolset. - let gateway_router = Router::new().route( + let router = Router::new().route( "/", axum::routing::any({ let (service, session_service) = (service.clone(), session_service.clone()); @@ -770,7 +761,10 @@ pub async fn setup_mcp_server( let (service, session_service) = (service.clone(), session_service.clone()); async move { use tower::ServiceExt; - let response = if request.extensions().get::().is_some() { + let session = request.extensions().get::().is_some_and(|a| { + serves_session_toolset(a.scopes.as_deref().unwrap_or_default()) + }); + let response = if session { session_service.oneshot(request).await } else { service.oneshot(request).await @@ -805,7 +799,7 @@ pub async fn setup_mcp_server( } }), ); - Ok((router, gateway_router, session_router, cancellation_token)) + Ok((router, session_router, cancellation_token)) } /// HTTP handler to list MCP tools as JSON @@ -857,7 +851,7 @@ pub fn toolset_service() -> Router { #[cfg(test)] mod tests { - use super::{scoped_to_selection, serves_session_on_gateway}; + use super::{scoped_to_selection, serves_session_toolset}; #[test] fn only_a_token_without_mcp_all_is_a_selection() { @@ -878,9 +872,9 @@ mod tests { } #[test] - fn gateway_keeps_the_tools_server_for_unmarked_tokens() { + fn tools_server_urls_keep_unmarked_tokens() { let session = |scopes: &[&str]| { - serves_session_on_gateway(&scopes.iter().map(|s| s.to_string()).collect::>()) + serves_session_toolset(&scopes.iter().map(|s| s.to_string()).collect::>()) }; assert!(session(&["mcp:all", "mcp:session"])); assert!(session(&["mcp:all", "mcp:read_only"])); diff --git a/backend/windmill-api/src/mcp/oauth_server.rs b/backend/windmill-api/src/mcp/oauth_server.rs index 2858964f0f..1ed9c2b5ee 100644 --- a/backend/windmill-api/src/mcp/oauth_server.rs +++ b/backend/windmill-api/src/mcp/oauth_server.rs @@ -873,11 +873,14 @@ async fn oauth_approve_inner( let code = format!("mcp-code-{}", rd_string(32)); - let scopes: Vec = form + let mut scopes: Vec = form .scope .split_whitespace() .map(|s| s.to_string()) .collect(); + if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) { + scopes.push(SESSION_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 @@ -1063,10 +1066,6 @@ pub async fn gateway_oauth_approve( Json(form): Json, ) -> Result> { let mut scope = form.scope; - let granted = scope.split_whitespace().collect::>(); - if granted.contains(&"mcp:all") && !granted.contains(&SESSION_SCOPE) { - scope.push_str(&format!(" {SESSION_SCOPE}")); - } let mut workspace_ids = form.workspace_ids; if workspace_ids.is_empty() { workspace_ids.extend(form.workspace_id); diff --git a/backend/windmill-mcp/src/common/scope.rs b/backend/windmill-mcp/src/common/scope.rs index 9ba0392ed3..cbff182c26 100644 --- a/backend/windmill-mcp/src/common/scope.rs +++ b/backend/windmill-mcp/src/common/scope.rs @@ -161,7 +161,7 @@ fn pattern_covers(caller: &str, requested: &str) -> bool { /// URL, which an older selection, carrying none of the newer scopes, still does. pub const RUNNABLES_AS_TOOLS_SCOPE: &str = "mcp:runnables_as_tools"; -/// Added server-side to an `mcp:all` OAuth grant so `/api/mcp/gateway` serves it the AI +/// Added server-side to an `mcp:all` OAuth grant so the tools server's URLs serve it the AI /// session's toolset. Grants nothing: an `mcp:all` token without it predates the session /// toolset there, and must keep the tools server's endpoint tools. pub const SESSION_SCOPE: &str = "mcp:session"; diff --git a/frontend/src/lib/components/mcp/McpAccessPicker.svelte b/frontend/src/lib/components/mcp/McpAccessPicker.svelte index 719a8894c9..6466bb8761 100644 --- a/frontend/src/lib/components/mcp/McpAccessPicker.svelte +++ b/frontend/src/lib/components/mcp/McpAccessPicker.svelte @@ -4,7 +4,7 @@ /** Marks a selection, so the per-workspace URLs add no API endpoint tools to it. */ export const RUNNABLES_AS_TOOLS = 'mcp:runnables_as_tools' - /** Added by the server to an `mcp:all` sign-in so `/api/mcp/gateway` serves it the AI + /** Added by the server to an `mcp:all` sign-in so the tools server's URLs serve it the AI * session's tools. Grants nothing, so it is never shown. */ export const MCP_SESSION = 'mcp:session' diff --git a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte index 374b0a776f..46ad5b4720 100644 --- a/frontend/src/lib/components/settings/EditTokenScopesModal.svelte +++ b/frontend/src/lib/components/settings/EditTokenScopesModal.svelte @@ -51,7 +51,7 @@ let mcpTouched = $state(false) // Carried over as is, the picker knowing nothing of them: dropping the workspace list // would widen the token to every workspace, dropping `mcp:session` would move a sign-in - // on `/api/mcp/gateway` back to the endpoint tools once it is given `mcp:all` again. + // back to the endpoint tools once it is given `mcp:all` again. const isWorkspaceList = (s: string) => s.startsWith('mcp:workspaces:') const keptAside = (s: string) => isWorkspaceList(s) ||