feat: approve-only mcp connect page (#12785)

* feat: cap mcp access per workspace role

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep read-and-run tools under a selection, audit capped calls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: no hub scripts under an mcp limit, count role changes once stored

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: choose mcp scripts and flows per workspace, not on instance roles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: limit mcp access of a role with a toggle

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: point ee ref at the companion merged with ee main

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: read a role's instance mcp limit only from its own key

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: disable scripts and flows as tools on a role that cannot run

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: approve-only mcp connect page showing per-workspace access

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: name only what a connection gets, refuse scoped callers

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* style: align the limit access fold

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show the access the server gives, keep picked workspaces

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: name what a non-authoring role edits over mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the workspace picked under a selection, cap the tool count query

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show what a role limit leaves a new mcp token

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: preview a token's mcp access with its superadmin rights

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show the mcp consent page's access per workspace, edit it in a dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: bind a tools-only connection to its workspace, list a run-and-edit role's full tools

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: shorten the run-and-edit access label, list the edits in its tooltip

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: name a non-authoring role's access build and run, with a restricted badge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: name the workspace that connects on its own, set its two ways apart

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: bold title and two subheaders for a workspace that connects on its own

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: list the one toolset a connection gets, trimmed only for a bound workspace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: one tool list per connection, fold the workspaces that connect on their own

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: show the consent page's tools in a searchable dialog, pick the access from a select

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: one access select in the token form and the consent page, workspace url beside /api/mcp

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: one per-workspace access list on the consent page and token forms, in place of the narrowing alert

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: list a role's scripts and flows as tools on the consent page, restricted badge before the access

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep withheld admin rights in the tools preview, name what a partial author or the deploy rules hold back

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: refuse the tools preview to a token withholding superadmin rights, restricted badge after a single access line

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: workspace line before the token form's access, one workspace's access as a line, plainer hints

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: preview tools with the rights the credential carries, one access section shared by the consent page and token forms

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: list a role's runnable tools under the workspace route, authenticated there as any workspace call

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: put the consent page's pens next to their section titles

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: leave a tools workspace out of a read-only connection's list and say why in its card, select it from the card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep one row and url per workspace that connects separately

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: offer the access pen unless every covered workspace's role settles the access

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: mcp token form reaches every workspace by default, editable everywhere; plain generated-token card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: one not-included card for tools workspaces on the consent page and token forms, global mcp url label

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: close the consent page's card markup

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show the not-included card under the workspaces it is about

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: quiet show tools action at the right of the access title

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: one access line on the mcp consent page, limit access capped at it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: same access line on the mcp token forms as on the consent page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: mcp tool listing reckons access as the consent page does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: token form shows the tools the connection lists, drop the old toolset guess

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: one mcp access check for calls, tool listing and the consent page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: pens next to the workspace and access values on the mcp consent page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: limit access dialog keeps the clamped level when it opens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: mcp refusal names the workspace and what the session can do there

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: no limit pen on a tools workspace, stricter-of note in the limit dialog

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: one sentence for the role cap on the mcp page, dialog and token form

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: role mcp access as a select with what members get and the urls to share

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: name the top mcp level everything your role allows; keep the pen for a requested selection

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep read only for a role that cannot run, which still holds its admins

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: tools workspaces selectable for a selection, one full-access label for external clients

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat: workspace role mcp access always starts from the instance's setting

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: a stored read only holds admins too in the members-get line

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the limit pen once a selection is made on a tools workspace

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 4a19159ab6f634de29673aa530b76d9a9710ab78

This commit updates the EE repository reference after PR #1033 was merged in windmill-ee-private.

Previous ee-repo-ref: 8317dbf5116aaca61acfe2f20e4c2340b3f17377

New ee-repo-ref: 4a19159ab6f634de29673aa530b76d9a9710ab78

Automated by sync-ee-ref workflow.

* chore: update ee-repo-ref to 4a19159ab6f634de29673aa530b76d9a9710ab78

This commit updates the EE repository reference after PR #1033 was merged in windmill-ee-private.

Previous ee-repo-ref: 8317dbf5116aaca61acfe2f20e4c2340b3f17377

New ee-repo-ref: 4a19159ab6f634de29673aa530b76d9a9710ab78

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <ruben@windmill.dev>
This commit is contained in:
hugocasa
2026-12-04 06:37:42 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot] Ruben Fiszel
parent b936016dc2
commit 5eff9aa1ac
32 changed files with 1796 additions and 490 deletions
@@ -0,0 +1,29 @@
{
"db_name": "PostgreSQL",
"query": "SELECT id, name FROM workspace\n WHERE deleted = false AND ($2 OR EXISTS (\n SELECT 1 FROM usr WHERE workspace_id = workspace.id AND email = $1 AND disabled = false\n ))\n ORDER BY name",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "name",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text",
"Bool"
]
},
"nullable": [
false,
false
]
},
"hash": "e93f5b749870394d8258b784bf4065d0d3d32856ead1a2a01d80566dfaac71e4"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "SELECT workspace_id, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false",
"query": "SELECT workspace_id, username, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false",
"describe": {
"columns": [
{
@@ -10,16 +10,21 @@
},
{
"ordinal": 1,
"name": "username",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "is_admin",
"type_info": "Bool"
},
{
"ordinal": 2,
"ordinal": 3,
"name": "operator",
"type_info": "Bool"
},
{
"ordinal": 3,
"ordinal": 4,
"name": "workspace_role",
"type_info": "Varchar"
}
@@ -34,8 +39,9 @@
false,
false,
false,
false,
true
]
},
"hash": "cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b"
"hash": "ee761c085738bb22b01a48627e067b145f92f1c396817e4c13e50019fc085d6c"
}
+4 -1
View File
@@ -140,6 +140,9 @@ async fn test_view_only_role_lists_no_runnable_tools(db: Pool<Postgres>) -> anyh
)
.await?;
let msg = run["error"]["message"].as_str().unwrap_or_default();
assert!(msg.contains("read-only"), "run must stay refused: {run}");
assert!(
msg.contains("in workspace test-workspace this session can only read"),
"run must stay refused: {run}"
);
Ok(())
}
+113 -1
View File
@@ -140,6 +140,66 @@ async fn role_setting_caps_every_token(db: Pool<Postgres>) -> anyhow::Result<()>
}
assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty());
assert!(tools(port, WORKSPACE, "ROLEREAD_TOKEN").await.is_empty());
// The consent page's preview of a sign-in bound here lists what the connection lists.
let preview: Value = reqwest::Client::new()
.get(format!(
"http://localhost:{port}/api/w/test-workspace/mcp/runnable_tools"
))
.bearer_auth("SECRET_TOKEN")
.send()
.await?
.json()
.await?;
let names: Vec<&str> = preview
.as_array()
.unwrap()
.iter()
.filter_map(|t| t["name"].as_str())
.collect();
assert_eq!(names, ["in_set"], "{preview}");
// A credential holding back its owner's admin rights is previewed without them: a script only
// an admin reads is listed to the full credential alone.
sqlx::raw_sql(
"INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES
('test-workspace', 'test-user-2', 'export function main() { return 1 }', '{}', '', '', 'u/test-user-2/private', 7788403, 'bun', '');
INSERT INTO token (token_hash, token_prefix, email, label, super_admin, admin)
VALUES (encode(sha256('NOADMIN_TOKEN'::bytea), 'hex'), 'NOADMIN_TO', 'test@windmill.dev', 'mcp', false, false);",
)
.execute(&db)
.await?;
set_access(
&db,
json!({"access": "runnables", "scripts": ["u/test-user/in_set", "u/test-user-2/private"]}),
)
.await;
let preview = |bearer: &'static str| async move {
let tools: Value = reqwest::Client::new()
.get(format!(
"http://localhost:{port}/api/w/test-workspace/mcp/runnable_tools"
))
.bearer_auth(bearer)
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let mut names: Vec<String> = tools
.as_array()
.unwrap()
.iter()
.filter_map(|t| t["name"].as_str().map(str::to_string))
.collect();
names.sort();
names
};
assert_eq!(preview("SECRET_TOKEN").await, ["in_set", "private"]);
assert_eq!(preview("NOADMIN_TOKEN").await, ["in_set"]);
set_access(
&db,
json!({"access": "runnables", "scripts": ["u/test-user/in_set"]}),
)
.await;
let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move {
mcp(
port,
@@ -168,7 +228,36 @@ async fn role_setting_caps_every_token(db: Pool<Postgres>) -> anyhow::Result<()>
);
}
// A workspace that disables direct deployment lists the read-and-run tools, as the consent
// page shows it.
sqlx::raw_sql(
"UPDATE workspace_settings SET role_overrides = NULL WHERE workspace_id = 'test-workspace';
INSERT INTO workspace_protection_rule (workspace_id, name, rules, bypass_groups, bypass_users)
VALUES ('test-workspace', 'locked', 1, '{}', '{}');",
)
.execute(&db)
.await?;
windmill_common::roles::invalidate_workspace_roles_cache("test-workspace");
windmill_common::workspaces::invalidate_protection_rules_cache("test-workspace");
for t in ["ROLESESS_TOKEN", "ROLEUNBOUND_TOKEN"] {
let listed = tools(port, DEFAULT, t).await;
assert!(
has(&listed, "run_script") && !has(&listed, "deploy_workspace_item"),
"{t}: {listed:?}"
);
}
sqlx::query("DELETE FROM workspace_protection_rule WHERE workspace_id = 'test-workspace'")
.execute(&db)
.await?;
windmill_common::workspaces::invalidate_protection_rules_cache("test-workspace");
set_access(&db, json!({"access": "read_only"})).await;
// A connection covering several workspaces lists what the best of them gives.
let listed = tools(port, DEFAULT, "ROLEUNBOUND_TOKEN").await;
assert!(
has(&listed, "list_workspace_items") && !has(&listed, "run_script"),
"{listed:?}"
);
for url in [WORKSPACE, DEFAULT, GATEWAY] {
let t = tools(port, url, "ROLEPLAIN_TOKEN").await;
assert!(has(&t, "list_workspace_items"), "{url}: {t:?}");
@@ -188,12 +277,35 @@ async fn role_setting_caps_every_token(db: Pool<Postgres>) -> anyhow::Result<()>
assert!(
out["error"]["message"]
.as_str()
.is_some_and(|m| m.contains("read-only")),
.is_some_and(|m| m.contains("in workspace test-workspace this session can only read")),
"{out}"
);
let out = call(DEFAULT, "ROLEUNBOUND_TOKEN", "list_workspaces", json!({})).await;
assert!(out["result"].to_string().contains("read only"), "{out}");
let listed = |bearer: &'static str| async move {
reqwest::Client::new()
.get(format!(
"http://localhost:{port}/api/mcp/gateway/oauth/server/workspace_access"
))
.bearer_auth(bearer)
.send()
.await
.unwrap()
};
let access: Value = listed("SECRET_TOKEN").await.json().await?;
let here = access
.as_array()
.unwrap()
.iter()
.find(|w| w["id"] == "test-workspace")
.unwrap();
assert_eq!(here["access"], json!("read_only"));
assert!(
!listed("ROLEUNBOUND_TOKEN").await.status().is_success(),
"a scoped token must not list its owner's other workspaces"
);
set_access(&db, json!({"access": "off"})).await;
assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty());
assert_eq!(
+79
View File
@@ -30019,6 +30019,67 @@ paths:
items:
$ref: "#/components/schemas/EndpointTool"
/mcp/gateway/oauth/server/workspace_access:
get:
summary: list what an MCP connection gets in each workspace
description: |
For each workspace the caller is a member of, what a connection asking for everything gets
there once their role and the workspace's rules have narrowed it.
operationId: listMcpWorkspaceAccess
tags:
- mcp_oauth
parameters:
- name: super_admin
in: query
description: As a connection carrying the caller's superadmin rights, in every workspace of the instance.
schema:
type: boolean
- name: with_counts
in: query
description: Count the scripts and flows offered as tools.
schema:
type: boolean
responses:
"200":
description: the workspaces and their access
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/McpWorkspaceAccess"
/w/{workspace}/mcp/runnable_tools:
get:
summary: list the scripts and flows a role offers as MCP tools in a workspace
description: |
What a sign-in bound to the workspace lists where the caller's role offers scripts and
flows as tools, with their arguments; empty under any other role. Listed with the rights
the caller's credential carries in the workspace.
operationId: listMcpRunnableTools
tags:
- mcp_oauth
parameters:
- $ref: "#/components/parameters/WorkspaceId"
responses:
"200":
description: the tools
content:
application/json:
schema:
type: array
items:
type: object
properties:
name:
type: string
description:
type: string
parameters:
type: object
description: The JSON Schema of its arguments.
required: [name, description, parameters]
/mcp/gateway/oauth/server/client/{client_id}:
get:
summary: get an MCP client registered with Windmill's OAuth server
@@ -42268,6 +42329,24 @@ components:
additionalProperties:
type: boolean
McpWorkspaceAccess:
type: object
properties:
id:
type: string
name:
type: string
access:
type: string
enum: [build_and_run, run_and_edit, read_and_run, read_only, runnables, "off"]
runnables:
type: integer
description: With `runnables`, how many scripts and flows are offered.
restricted:
type: boolean
description: With `build_and_run`, whether the caller's role still authors only some kinds, or the deploy rules block the caller.
required: [id, name, access, restricted]
McpRoleSetting:
type: object
description: The most a role's members may do through MCP, whatever their token grants (EE). Unset falls through to the layer below.
@@ -883,12 +883,14 @@ async fn call_generated_tool(
return Err(CallRefused::UnknownTool(format!("Unknown tool '{name}'")));
};
if !allowed(def, ctx.access) {
let token = match ctx.access {
SessionAccess::ReadAndRun => "can only read and run deployed scripts and flows",
_ => "is read-only",
// Named per workspace: a session covering several gives each its own access.
let can = match ctx.access {
SessionAccess::ReadAndRun => "only read and run deployed scripts and flows",
_ => "only read",
};
return Err(CallRefused::NotAllowed(format!(
"Tool '{name}' changes or runs something, and this session {token}"
"Tool '{name}' changes or runs something, and in workspace {} this session can {can}",
ctx.w_id
)));
}
dispatch(ctx, name, args).await.ok_or_else(|| {
+9
View File
@@ -845,6 +845,15 @@ pub async fn run_server(
#[cfg(not(feature = "mcp"))]
Router::new()
})
.nest("/mcp/runnable_tools", {
#[cfg(feature = "mcp")]
{
mcp::runnable_tools_service()
}
#[cfg(not(feature = "mcp"))]
Router::new()
})
.nest("/ai", ai::workspaced_service())
.nest(
"/ai_session_tools",
+47 -43
View File
@@ -14,7 +14,7 @@ use windmill_mcp::common::types::{
FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo,
};
use windmill_mcp::server::{
admits, session_limit, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend,
admits, session_in, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend,
McpLimit, McpRequest, PathFilter, RunOutcome, SessionAccess, Tool,
};
@@ -74,16 +74,12 @@ pub struct WindmillBackend {
/// chat applies the same rule (`protects` in `chat/global/sessionAccess.ts`): change both. The
/// chat alone lets a bypasser opt one session into working there directly, behind a confirmation
/// an MCP client has no equivalent of, so a token stays held.
fn workspace_access(access: SessionAccess, rules: Option<&[ProtectionRuleset]>) -> SessionAccess {
let locked = rules.map_or(true, |rules| {
fn locked(rules: Option<&[ProtectionRuleset]>) -> bool {
rules.map_or(true, |rules| {
rules
.iter()
.any(|r| r.rules.contains(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT))
});
match access {
SessionAccess::Full if locked => SessionAccess::ReadAndRun,
other => other,
}
})
}
impl WindmillBackend {
@@ -93,26 +89,7 @@ impl WindmillBackend {
w_id: &'a str,
access: SessionAccess,
) -> BackendResult<session::Ctx<'a>> {
let access = match self.mcp_limit(auth, w_id).await? {
Some(limit) => access.min(session_limit(w_id, &limit)?),
None => access,
};
let access = match access {
SessionAccess::Full => {
let rules = get_protection_rules(w_id, &self.db).await.ok();
workspace_access(access, rules.as_deref().map(Vec::as_slice))
}
other => other,
};
// A role without `run` reads only, whatever the token grants. The in-app chat applies the
// same rule (`resolveSessionAccess` in `chat/global/sessionAccess.ts`): change both.
let access = if access != SessionAccess::ReadOnly
&& !self.can_run(auth, w_id).await.unwrap_or(true)
{
SessionAccess::ReadOnly
} else {
access
};
let access = self.session_access(auth, w_id, access).await?;
Ok(session::Ctx::new(
auth,
w_id,
@@ -572,10 +549,30 @@ impl McpBackend for WindmillBackend {
auth: &ApiAuthed,
workspaces: &[WorkspaceInfo],
access: SessionAccess,
) -> BackendResult<HashMap<String, &'static str>> {
) -> BackendResult<HashMap<String, String>> {
super::role_access::workspace_accesses(&self.db, &auth.email, workspaces, access).await
}
async fn session_access(
&self,
auth: &ApiAuthed,
workspace_id: &str,
access: SessionAccess,
) -> BackendResult<SessionAccess> {
// The in-app chat applies the same rules (`resolveSessionAccess` in
// `chat/global/sessionAccess.ts`): change both.
let limit = self.mcp_limit(auth, workspace_id).await?;
let rules = get_protection_rules(workspace_id, &self.db).await.ok();
let can_run = self.can_run(auth, workspace_id).await.unwrap_or(true);
session_in(
workspace_id,
access,
limit.as_ref(),
locked(rules.as_deref().map(Vec::as_slice)),
can_run,
)
}
async fn session_instructions(
&self,
auth: &ApiAuthed,
@@ -906,6 +903,16 @@ pub async fn add_www_authenticate_header_gateway(
}
}
impl From<windmill_mcp::server::Tool> for ToolsetEntry {
fn from(tool: windmill_mcp::server::Tool) -> Self {
ToolsetEntry {
name: tool.name.to_string(),
description: tool.description.map(|d| d.to_string()).unwrap_or_default(),
parameters: serde_json::Value::Object((*tool.input_schema).clone()),
}
}
}
/// Setup the MCP server with HTTP transport
pub async fn setup_mcp_server(
db: DB,
@@ -1026,9 +1033,11 @@ struct ToolsetQuery {
}
#[derive(serde::Serialize)]
struct ToolsetEntry {
pub(crate) struct ToolsetEntry {
name: String,
description: String,
/// The JSON Schema of its arguments.
parameters: serde_json::Value,
}
/// The tools `/api/mcp` offers an `mcp:all` token at each access level, for the token
@@ -1044,10 +1053,7 @@ async fn list_toolset_handler(
Ok(Json(
session::session_tools(access)
.into_iter()
.map(|tool| ToolsetEntry {
name: tool.name.to_string(),
description: tool.description.map(|d| d.to_string()).unwrap_or_default(),
})
.map(ToolsetEntry::from)
.collect(),
))
}
@@ -1059,8 +1065,8 @@ pub fn toolset_service() -> Router {
#[cfg(test)]
mod tests {
use super::{
scoped_to_selection, serves_session_toolset, workspace_access, ProtectionRules,
ProtectionRuleset, SessionAccess,
locked, scoped_to_selection, serves_session_toolset, ProtectionRules, ProtectionRuleset,
SessionAccess,
};
#[test]
@@ -1073,14 +1079,12 @@ mod tests {
bypass_users: vec!["admin".to_string()],
fork_role_mapping: Default::default(),
};
let locked = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)];
let held = [ruleset(ProtectionRules::DISABLE_DIRECT_DEPLOYMENT)];
let open = [ruleset(ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS)];
use SessionAccess::*;
assert_eq!(workspace_access(Full, Some(&locked)), ReadAndRun);
assert_eq!(workspace_access(Full, None), ReadAndRun);
assert_eq!(workspace_access(Full, Some(&open)), Full);
assert_eq!(workspace_access(Full, Some(&[])), Full);
assert_eq!(workspace_access(ReadOnly, Some(&locked)), ReadOnly);
assert!(locked(Some(&held)));
assert!(locked(None));
assert!(!locked(Some(&open)));
assert!(!locked(Some(&[])));
}
#[test]
+1
View File
@@ -17,3 +17,4 @@ pub use core::{
extract_and_store_workspace_id, extract_workspace_from_token, list_tools_service,
reject_token_query_param, setup_mcp_server, toolset_service, McpEndpoint,
};
pub use role_access::runnable_tools_service;
@@ -1297,6 +1297,10 @@ pub fn gateway_authed_service() -> Router {
Router::new()
.route("/approve", post(gateway_oauth_approve))
.route("/client/{client_id}", get(get_registered_client))
.route(
"/workspace_access",
get(super::role_access::list_workspace_access),
)
}
#[cfg(test)]
+304 -53
View File
@@ -2,13 +2,25 @@
use std::collections::HashMap;
use axum::{
extract::{Path, Query},
Extension, Json,
};
use serde::{Deserialize, Serialize};
use windmill_api_auth::ApiAuthed;
use windmill_common::{
db::UserDB,
error::{Error, JsonResult},
roles::{self, McpRoleAccess, McpRoleSetting, RoleCapabilities},
workspaces::ProtectionRules,
workspaces::{check_deploy_rules, ProtectionRules, RuleCheckResult},
DB,
};
use windmill_mcp::server::{BackendResult, ErrorData, McpLimit, SessionAccess, WorkspaceInfo};
use windmill_mcp::server::{
session_in, workspace_mcp_url, BackendResult, ErrorData, McpLimit, PathFilter, SessionAccess,
WorkspaceInfo,
};
use super::utils::count_items;
fn limit_of(setting: &McpRoleSetting) -> Option<McpLimit> {
match setting.access {
@@ -43,38 +55,85 @@ pub(super) async fn mcp_limit(
})
}
/// What a connection with `access` gets in each workspace, in three queries however many there
/// are. Community, where no role limits anything, queries nothing and lists none.
/// What a connection gets in one workspace, once its member's role and the workspace's rules have
/// narrowed the access it was granted.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceMcpAccess {
BuildAndRun,
/// A role that authors no script, flow or app still edits what it may: schedules, triggers,
/// resources.
RunAndEdit,
ReadAndRun,
ReadOnly,
Runnables,
Off,
}
struct MemberAccess {
access: WorkspaceMcpAccess,
/// The role's own limit there.
limit: Option<McpLimit>,
username: Option<String>,
can_run: bool,
/// With `RunAndEdit`, what the role edits.
edits: Vec<&'static str>,
/// With `BuildAndRun`, whether the role still authors only some kinds, or the deploy rules
/// block the member.
restricted: bool,
}
/// What a connection with `access` gets in each workspace, for `list_workspaces`. Community, where
/// no role limits anything, queries nothing and lists none.
pub(super) async fn workspace_accesses(
db: &DB,
email: &str,
workspaces: &[WorkspaceInfo],
access: SessionAccess,
) -> BackendResult<HashMap<String, &'static str>> {
) -> BackendResult<HashMap<String, String>> {
if !cfg!(feature = "enterprise") {
return Ok(HashMap::new());
}
accesses(db, email, workspaces, access)
let ids = workspaces.iter().map(|w| w.id.clone()).collect();
Ok(accesses(db, email, ids, access, false)
.await
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
.map_err(|e| ErrorData::internal_error(e.to_string(), None))?
.into_iter()
.map(|(id, m)| {
let text = match m.access {
WorkspaceMcpAccess::BuildAndRun => "build and run".to_string(),
WorkspaceMcpAccess::RunAndEdit => {
format!("read and run, edit {}", m.edits.join(", "))
}
WorkspaceMcpAccess::ReadAndRun => "read and run".to_string(),
WorkspaceMcpAccess::ReadOnly => "read only".to_string(),
WorkspaceMcpAccess::Runnables => {
format!("scripts and flows as tools, on {}", workspace_mcp_url(&id))
}
WorkspaceMcpAccess::Off => "off".to_string(),
};
(id, text)
})
.collect())
}
/// `super_admin`: the connection carries its owner's superadmin rights. In three queries however many workspaces there are.
async fn accesses(
db: &DB,
email: &str,
workspaces: &[WorkspaceInfo],
ids: Vec<String>,
access: SessionAccess,
) -> windmill_common::error::Result<HashMap<String, &'static str>> {
let ids: Vec<String> = workspaces.iter().map(|w| w.id.clone()).collect();
super_admin: bool,
) -> windmill_common::error::Result<HashMap<String, MemberAccess>> {
let members = sqlx::query!(
"SELECT workspace_id, is_admin, operator, workspace_role FROM usr
"SELECT workspace_id, username, is_admin, operator, workspace_role FROM usr
WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false",
email,
&ids
)
.fetch_all(db)
.await?;
let mut overrides: HashMap<String, roles::RoleOverrides> = sqlx::query!(
let mut overrides: HashMap<String, Option<roles::RoleOverrides>> = sqlx::query!(
"SELECT workspace_id, role_overrides FROM workspace_settings
WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL",
&ids
@@ -82,11 +141,9 @@ async fn accesses(
.fetch_all(db)
.await?
.into_iter()
.filter_map(|r| {
Some((
r.workspace_id,
serde_json::from_value(r.role_overrides?).ok()?,
))
.map(|r| {
let overrides = serde_json::from_value(r.role_overrides.unwrap_or_default()).ok();
(r.workspace_id, overrides)
})
.collect();
let locked: Vec<String> = sqlx::query_scalar!(
@@ -97,57 +154,251 @@ async fn accesses(
)
.fetch_all(db)
.await?;
let deployers_only: Vec<String> = sqlx::query_scalar!(
"SELECT DISTINCT workspace_id FROM workspace_protection_rule
WHERE workspace_id = ANY($1) AND rules & $2 <> 0",
&ids,
ProtectionRules::RESTRICT_DEPLOY_TO_DEPLOYERS.bits()
)
.fetch_all(db)
.await?;
let instance = roles::instance_roles(db).await?;
let mut out = HashMap::with_capacity(ids.len());
for id in ids {
let mut access = access;
let mut can_run = true;
let mut builds = true;
if let Some(m) = members.iter().find(|m| m.workspace_id == id) {
let roles =
roles::effective_roles(&instance, &overrides.remove(&id).unwrap_or_default())?;
let mut restricted = false;
let mut limit = None;
let mut edits = vec![];
let member = members.iter().find(|m| m.workspace_id == id);
if let Some(m) = member {
// Roles that cannot be read refuse every call there, as `caller_mcp_limit` does.
let roles = overrides
.remove(&id)
.unwrap_or_else(|| Some(Default::default()))
.and_then(|o| roles::effective_roles(&instance, &o).ok());
let name = roles::resolve_role_name(m.workspace_role.clone(), m.operator);
let role = roles.iter().find(|r| r.name == name);
let limited = roles.iter().any(|r| r.mcp_limit().is_some());
let limit = match role {
Some(role) => role.mcp_limit().and_then(limit_of),
None => limited.then_some(McpLimit::Off),
let role = roles.iter().flatten().find(|r| r.name == name);
limit = match (&roles, role) {
(Some(_), Some(role)) => role.mcp_limit().and_then(limit_of),
(Some(roles), None) => roles
.iter()
.any(|r| r.mcp_limit().is_some())
.then_some(McpLimit::Off),
(None, _) => cfg!(feature = "enterprise").then_some(McpLimit::Off),
};
match limit {
None => {}
Some(McpLimit::ReadAndRun) => access = access.min(SessionAccess::ReadAndRun),
Some(McpLimit::ReadOnly) => access = SessionAccess::ReadOnly,
Some(McpLimit::Runnables { .. }) => {
out.insert(
id,
"scripts and flows as tools, on this workspace's own MCP URL",
);
continue;
}
Some(McpLimit::Off) => {
out.insert(id, "off");
continue;
}
}
if !m.is_admin {
if !m.is_admin && !super_admin {
let caps = role.map_or(RoleCapabilities::NONE, |r| r.capabilities);
if !caps.run {
access = SessionAccess::ReadOnly;
}
can_run = caps.run;
builds = caps.is_author();
restricted = !caps.code
|| caps.flows == roles::AuthorLevel::None
|| caps.apps == roles::AuthorLevel::None;
// Folder rights, not the role, gate these two.
edits.extend(["resources", "variables"]);
if caps.manage_schedules {
edits.push("schedules");
}
if caps.manage_triggers {
edits.push("triggers");
}
}
}
if access == SessionAccess::Full && (!builds || locked.contains(&id)) {
access = SessionAccess::ReadAndRun;
let session = session_in(&id, access, limit.as_ref(), locked.contains(&id), can_run);
let access = match (&limit, session) {
(Some(McpLimit::Runnables { .. }), Err(_)) => WorkspaceMcpAccess::Runnables,
(_, Err(_)) => WorkspaceMcpAccess::Off,
(_, Ok(SessionAccess::ReadOnly)) => WorkspaceMcpAccess::ReadOnly,
(_, Ok(SessionAccess::ReadAndRun)) => WorkspaceMcpAccess::ReadAndRun,
(_, Ok(SessionAccess::Full)) if !builds => WorkspaceMcpAccess::RunAndEdit,
(_, Ok(SessionAccess::Full)) => WorkspaceMcpAccess::BuildAndRun,
};
// Checked per member, only where a rule keeps deploying to deployers.
if let Some(m) = member.filter(|_| {
access == WorkspaceMcpAccess::BuildAndRun && !restricted && deployers_only.contains(&id)
}) {
let groups =
windmill_common::auth::get_groups_for_user(&id, &m.username, email, db).await?;
restricted = matches!(
check_deploy_rules(&id, &m.username, &groups, m.is_admin || super_admin, db)
.await?,
RuleCheckResult::Blocked(_)
);
}
let restricted = restricted && access == WorkspaceMcpAccess::BuildAndRun;
let username = member.map(|m| m.username.clone());
out.insert(
id,
match access {
SessionAccess::ReadOnly => "read only",
SessionAccess::ReadAndRun => "read and run",
SessionAccess::Full => "build and run",
},
MemberAccess { access, limit, username, can_run, edits, restricted },
);
}
Ok(out)
}
#[derive(Serialize)]
pub struct WorkspaceAccessEntry {
id: String,
name: String,
access: WorkspaceMcpAccess,
/// With `runnables`, how many scripts and flows the caller would be offered.
#[serde(skip_serializing_if = "Option::is_none")]
runnables: Option<usize>,
/// With `build_and_run`, whether the role still authors only some kinds, or the deploy rules
/// block the caller.
restricted: bool,
}
#[derive(Deserialize)]
pub struct WorkspaceAccessQuery {
/// As a connection carrying the caller's superadmin rights: every workspace of the instance.
#[serde(default)]
super_admin: bool,
#[serde(default)]
with_counts: bool,
}
/// GET /api/mcp/gateway/oauth/server/workspace_access: what an MCP connection gets in each
/// workspace the caller is a member of, for the consent page to show.
pub async fn list_workspace_access(
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
authed: ApiAuthed,
Query(query): Query<WorkspaceAccessQuery>,
) -> JsonResult<Vec<WorkspaceAccessEntry>> {
// A token confined to some workspaces or routes must not learn of its owner's other ones.
if authed
.scopes
.as_deref()
.is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:")))
{
return Err(Error::NotAuthorized(
"A scope-restricted token cannot list its owner's workspaces".to_string(),
));
}
if query.super_admin {
windmill_api_auth::require_super_admin(&db, &authed).await?;
}
let workspaces = sqlx::query!(
"SELECT id, name FROM workspace
WHERE deleted = false AND ($2 OR EXISTS (
SELECT 1 FROM usr WHERE workspace_id = workspace.id AND email = $1 AND disabled = false
))
ORDER BY name",
authed.email,
query.super_admin
)
.fetch_all(&db)
.await?;
let ids = workspaces.iter().map(|w| w.id.clone()).collect();
let found = accesses(
&db,
&authed.email,
ids,
SessionAccess::Full,
query.super_admin,
)
.await?;
// Counted as the owner, who as a superadmin sees more than a connection without those rights.
let owner_is_super_admin =
windmill_common::auth::is_super_admin_email(&db, &authed.email).await?;
let mut out = Vec::with_capacity(workspaces.len());
for w in workspaces {
let Some(member) = found.get(&w.id) else {
continue;
};
let runnables = match (&member.limit, &member.username) {
// A role that cannot run is offered none of them.
(Some(McpLimit::Runnables { .. }), _) if !member.can_run => Some(0),
(Some(McpLimit::Runnables { scripts, flows }), Some(username))
if query.with_counts && !owner_is_super_admin =>
{
count_runnables(
&db,
&user_db,
&authed.email,
username,
&w.id,
scripts,
flows,
)
.await
.ok()
}
_ => None,
};
out.push(WorkspaceAccessEntry {
access: member.access,
runnables,
restricted: member.restricted,
id: w.id,
name: w.name,
});
}
Ok(Json(out))
}
/// Mounted at /api/w/{workspace}/mcp/runnable_tools.
pub fn runnable_tools_service() -> axum::Router {
axum::Router::new().route("/", axum::routing::get(list_runnable_tools))
}
/// GET /api/w/{workspace}/mcp/runnable_tools: the scripts and flows a sign-in bound to the
/// workspace would list where the caller's role offers them as tools, with their arguments. The
/// caller is authenticated in that workspace, holding there only the rights its credential carries.
async fn list_runnable_tools(
Extension(db): Extension<DB>,
Extension(user_db): Extension<UserDB>,
Extension(auth_cache): Extension<std::sync::Arc<crate::auth::AuthCache>>,
Path(w_id): Path<String>,
authed: ApiAuthed,
) -> JsonResult<Vec<super::core::ToolsetEntry>> {
if authed
.scopes
.as_deref()
.is_some_and(|s| s.iter().any(|x| !x.starts_with("if_jobs:filter_tags:")))
{
return Err(Error::NotAuthorized(
"A scope-restricted token cannot list its owner's tools".to_string(),
));
}
// Listing reads the database only, so no internal URL is needed.
let runner = windmill_mcp::server::Runner::new(super::core::WindmillBackend::new(
db,
user_db,
String::new(),
auth_cache,
));
let tools = runner
.role_runnable_tools(&authed, &w_id)
.await
.map_err(|e| Error::internal_err(e.message.into_owned()))?;
Ok(Json(tools.tools.into_iter().map(Into::into).collect()))
}
async fn count_runnables(
db: &DB,
user_db: &UserDB,
email: &str,
username: &str,
w_id: &str,
scripts: &[String],
flows: &[String],
) -> windmill_common::error::Result<usize> {
let there: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as(
&format!("u/{username}"),
email,
w_id,
db,
)
.await?
.into();
let mut count = 0;
for (kind, patterns) in [("script", scripts), ("flow", flows)] {
let filter = Some(PathFilter::Patterns(patterns));
count += count_items(user_db, &there, w_id, kind, filter)
.await
.map_err(|e| Error::internal_err(e.message.into_owned()))?;
}
Ok(count)
}
+14
View File
@@ -288,6 +288,20 @@ pub async fn get_item_paths(
Ok(rows.into_iter().map(|(path,)| path).collect())
}
/// How many tools `get_items` would list, its cap included, without fetching them.
pub async fn count_items(
user_db: &UserDB,
authed: &ApiAuthed,
workspace_id: &str,
item_type: &str,
path_filter: Option<PathFilter<'_>>,
) -> Result<usize, ErrorData> {
let mut sqlb = items_query(authed, workspace_id, "all", item_type, path_filter);
sqlb.distinct().field("o.path").limit(ITEMS_FETCH_MAX_LIMIT);
let rows: Vec<(String,)> = fetch_items(user_db, authed, &sqlb, item_type).await?;
Ok(rows.len())
}
/// Get scripts from the Hub
pub async fn get_scripts_from_hub(
db: &DB,
+10 -1
View File
@@ -293,7 +293,16 @@ pub trait McpBackend: Send + Sync + Clone + 'static {
auth: &Self::Auth,
workspaces: &[WorkspaceInfo],
access: SessionAccess,
) -> BackendResult<HashMap<String, &'static str>>;
) -> BackendResult<HashMap<String, String>>;
/// What a session granted `access` gets in `workspace_id`, by `session_in`, or why it gets
/// none. `auth` is the caller's there. Every call and the tool listing go through it.
async fn session_access(
&self,
auth: &Self::Auth,
workspace_id: &str,
access: SessionAccess,
) -> BackendResult<SessionAccess>;
/// The instructions a client reaching one workspace receives on connecting, built for
/// this user and what the token lets them do.
+1 -1
View File
@@ -23,7 +23,7 @@ pub use endpoints::{
list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool,
};
pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES};
pub use session::{admits, session_limit, SessionRunner};
pub use session::{admits, session_in, session_limit, workspace_mcp_url, SessionRunner};
pub use tools::create_tool_from_item;
// Re-export rmcp types for convenience
+21
View File
@@ -819,6 +819,27 @@ impl<B: McpBackend> Runner<B> {
.collect())
}
/// What a sign-in bound to `workspace_id` lists where the caller's role offers scripts and
/// flows as tools, for the consent page to show; empty under any other role. `auth` is the
/// caller as a member of that workspace.
pub async fn role_runnable_tools(
&self,
auth: &B::Auth,
workspace_id: &str,
) -> Result<ListToolsResult, ErrorData> {
let Some(limit @ McpLimit::Runnables { .. }) =
self.backend.mcp_limit(auth, workspace_id).await?
else {
return Ok(ListToolsResult::default());
};
let scope_config = parse_mcp_scopes(&["mcp:all".to_string()])
.map_err(|e| ErrorData::internal_error(e, None))?
.limited_by(&limit);
let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only;
self.list_tools_single(auth, workspace_id, &scope_config, read_only)
.await
}
/// List tools for a single, bound workspace (URL-path or token-bound).
async fn list_tools_single(
&self,
+59 -39
View File
@@ -55,13 +55,45 @@ pub fn session_limit(workspace_id: &str, limit: &McpLimit) -> Result<SessionAcce
}
}
/// What a session granted `access` gets in a workspace, or why it gets none: the role's MCP
/// `limit`, a workspace disabling direct deployment (`locked`) and a role that cannot run each
/// lower it. Every call, the tool listing and the consent page reckon it here.
pub fn session_in(
workspace_id: &str,
access: SessionAccess,
limit: Option<&McpLimit>,
locked: bool,
can_run: bool,
) -> Result<SessionAccess, ErrorData> {
let mut access = match limit {
Some(limit) => access.min(session_limit(workspace_id, limit)?),
None => access,
};
if locked {
access = access.min(SessionAccess::ReadAndRun);
}
if !can_run {
access = SessionAccess::ReadOnly;
}
Ok(access)
}
/// The MCP URL connecting to this workspace alone.
pub fn workspace_mcp_url(workspace_id: &str) -> String {
format!(
"{}/api/mcp/w/{workspace_id}/mcp",
windmill_common::global_settings::mcp_base_url()
)
}
/// Says what is allowed there instead, so the model does not retry.
pub(super) fn limit_refusal(workspace_id: &str, limit: &McpLimit) -> ErrorData {
let allowed = match limit {
McpLimit::Off => "your role has no MCP access there".to_string(),
McpLimit::Runnables { .. } => format!(
"your role is limited there to chosen scripts and flows as tools, which a connection \
to that workspace's own MCP URL (/api/mcp/w/{workspace_id}/mcp) serves"
to that workspace's own MCP URL, {}, serves",
workspace_mcp_url(workspace_id)
),
McpLimit::ReadOnly => "your role is limited there to reading, through /api/mcp".to_string(),
McpLimit::ReadAndRun => {
@@ -228,14 +260,10 @@ impl<B: McpBackend> SessionRunner<B> {
// Connecting succeeds so the client shows why no tool works there.
Some(limit @ (McpLimit::Off | McpLimit::Runnables { .. })) =>
limit_refusal(&only.id, &limit).message.into_owned(),
_ =>
self.backend
.session_instructions(
&auth,
&only.id,
access(&auth, &caller.scope),
)
.await?,
_ => self
.backend
.session_instructions(&auth, &only.id, access(&auth, &caller.scope),)
.await?,
}
)
}
@@ -322,37 +350,29 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
if let McpMode::Multi(_) = caller.mode {
tools.push(get_workspace_context_tool());
}
let mut access = access(&caller.auth, &caller.scope);
// A bound token's one workspace decides its toolset as it decides its instructions:
// a role there that cannot run gets the read-only tools.
if let McpMode::Single(bound) = &caller.mode {
match self.backend.mcp_limit(&caller.auth, bound).await? {
Some(limit) => match session_limit(bound, &limit) {
Ok(most) => access = access.min(most),
Err(_) => {
return Ok(ListToolsResult::with_all_items(tools)
.with_ttl_ms(LIST_TTL_MS)
.with_cache_scope(LIST_CACHE_SCOPE))
}
},
None => {}
}
if access != SessionAccess::ReadOnly
&& !self
.backend
.can_run(&caller.auth, bound)
.await
.unwrap_or(true)
{
access = SessionAccess::ReadOnly;
// The highest access a covered workspace gives, as each call there is checked; one giving
// less refuses per call what it does not allow.
let granted = access(&caller.auth, &caller.scope);
let mut listed = None;
for w in self.workspaces(&caller).await? {
let Ok(auth) = self.auth_in(&caller, &w.id).await else {
continue;
};
if let Ok(got) = self.backend.session_access(&auth, &w.id, granted).await {
listed = listed.max(Some(got));
if got == granted {
break;
}
}
}
tools.extend(
self.backend
.session_tools(access)
.into_iter()
.map(with_workspace_id_arg),
);
if let Some(listed) = listed {
tools.extend(
self.backend
.session_tools(listed)
.into_iter()
.map(with_workspace_id_arg),
);
}
if declines_cards(context.meta.client_capabilities().as_ref()) {
tools.retain(|tool| {
!tool.meta.as_ref().is_some_and(|m| {
@@ -433,7 +453,7 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
.map(|w| {
let mut entry = serde_json::json!({ "id": w.id, "name": w.name });
if let Some(access) = accesses.get(&w.id) {
entry["access"] = (*access).into();
entry["access"] = access.as_str().into();
}
entry
})
+2
View File
@@ -75,6 +75,8 @@ it must not restrict a role, cost a seat or reach an authoring gate.
`runnables` gets the tools server whatever the token, and an `mcp:all` token under another limit
the session toolset, since endpoint tools are never served under one. Where a connection covers
several workspaces the list is one for all, so the limit refuses at call time.
- The connect page and the MCP tab of the home page read `workspace_access`, the same computation
as `list_workspaces`, so a user is shown what they get rather than what they ask for.
- A selection intersects with the token's own (`McpScopeConfig::limited_by`).
- A lapsed license freezes it as it does roles: it keeps applying and can be removed, not changed.
On Community it is ignored and refused at write.
@@ -93,7 +93,7 @@
}
const ACCESS_LABELS = {
full: 'Build and run',
full: 'Everything your role allows',
read_run: 'Read and run',
read: 'Read only'
}
@@ -0,0 +1,41 @@
<script lang="ts">
import type { McpWorkspaceAccess } from '$lib/gen'
import type { McpAccess } from './McpAccessPicker.svelte'
import Tooltip from '$lib/components/Tooltip.svelte'
import type { Snippet } from 'svelte'
import { connectionLevel, narrows } from './workspaceAccess'
interface Props {
/** The workspaces the connection serves. */
workspaces: McpWorkspaceAccess[]
access: McpAccess
/** Names the level, for where no select already shows it. */
labelled?: boolean
/** Rendered after the level, to change it. */
edit?: Snippet
}
let { workspaces, access, labelled = false, edit }: Props = $props()
const shown = $derived(connectionLevel(workspaces, access))
// Under a select, a workspace giving less than the level picked is what the sentence is about.
// The top level names the role already.
const less = $derived(
labelled
? shown.less && shown.level !== 'full'
: access !== 'full' && workspaces.some((w) => narrows(w, access))
)
</script>
{#if labelled}
<div class="flex items-center gap-1.5 text-xs text-primary">
{shown.label}
{#if shown.hint}<Tooltip small>{shown.hint}</Tooltip>{/if}
{@render edit?.()}
</div>
{/if}
{#if less}
<p class="text-2xs text-secondary">
In each workspace, the client can do at most what your role allows there.
</p>
{/if}
@@ -9,7 +9,7 @@
* tools. Grants nothing, so it is never shown. */
export const MCP_SESSION = 'mcp:session'
const ACCESS_SCOPES: Record<Exclude<McpAccess, 'selected'>, string[]> = {
export const ACCESS_SCOPES: Record<Exclude<McpAccess, 'selected'>, string[]> = {
read: ['mcp:all', 'mcp:read_only'],
read_run: ['mcp:all', 'mcp:read_run'],
full: ['mcp:all', MCP_SESSION]
@@ -27,42 +27,54 @@
</script>
<script lang="ts">
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
import McpScopeSelector from './McpScopeSelector.svelte'
import Popover from '$lib/components/Popover.svelte'
import { Badge } from '$lib/components/common'
import Section from '$lib/components/Section.svelte'
import { SvelteMap } from 'svelte/reactivity'
import Select from '$lib/components/select/Select.svelte'
import McpAccessSection from './McpAccessSection.svelte'
import type { Snippet } from 'svelte'
import { resource } from 'runed'
import Alert from '$lib/components/common/alert/Alert.svelte'
import { resolveSessionAccess } from '$lib/components/copilot/chat/global/sessionAccess'
import { accessNarrowing } from './accessNarrowing'
import { userWorkspaces } from '$lib/stores'
import { ACCESS_HINTS, RANK, connectionLevel } from './workspaceAccess'
import type { McpWorkspaceAccess } from '$lib/gen'
import type { ToolsetLevel } from './toolsets.svelte'
interface Props {
/** The workspace the selection picker browses. */
workspaceId: string
/** The workspaces the token reaches, to warn where one holds it to less than `access`. */
workspaces?: string[]
/** The token's MCP scopes, the workspace list aside. */
scopes?: string[]
access?: McpAccess
initialScopes?: string[]
/** Rendered between the access choice and the tool list. */
/** Rendered right under the access choice, as part of it. */
belowAccess?: Snippet
/** Rendered after the access choice. */
afterAccess?: Snippet
/** Offers the chosen level's tools in a dialog. */
showTools?: boolean
/** The workspaces the connection serves, whose best level is the one listed. */
served?: McpWorkspaceAccess[]
/** The highest level offered; scripts and flows as tools stay offered under it. */
max?: ToolsetLevel
}
let {
workspaceId,
workspaces = [],
scopes = $bindable(),
access = $bindable(),
initialScopes = [],
afterAccess
belowAccess,
afterAccess,
showTools = false,
max,
served
}: Props = $props()
const LEVELS = $derived(
[
{ value: 'full', label: 'Everything your role allows' },
{ value: 'read_run', label: 'Read and run' },
{ value: 'read', label: 'Read only' },
{ value: 'selected', label: 'Scripts and flows as tools' }
].filter((l) => !max || l.value === 'selected' || RANK[l.value as ToolsetLevel] <= RANK[max])
)
const initialAccess = mcpAccessOf(initialScopes)
access = initialAccess
const initialSelection =
@@ -81,103 +93,25 @@
: ACCESS_SCOPES[access]
})
// The tools each access level gives, as the server lists them.
type ToolsetEntry = { name: string; description: string }
let toolsCollapsed = $state(true)
const toolsets = new SvelteMap<string, ToolsetEntry[]>()
const toolsetAccess = $derived(access === 'selected' ? undefined : access)
$effect(() => {
const level = toolsetAccess
if (toolsCollapsed || !level || toolsets.has(level)) return
fetch(`/api/mcp/toolset?access=${level}`)
.then((r) => (r.ok ? r.json() : []))
.then((tools: ToolsetEntry[]) => toolsets.set(level, tools))
.catch(() => toolsets.set(level, []))
})
const tools = $derived(toolsetAccess ? toolsets.get(toolsetAccess) : undefined)
// Each workspace's access, as the chat resolves it, to compare with the level picked.
const workspaceAccess = resource(
// Rerun once the workspace list loads: until then a role reads as its legacy defaults.
() => ({ ids: [...workspaces], roles: $userWorkspaces }),
({ ids }) => Promise.all(ids.map(async (id) => ({ id, there: await resolveSessionAccess(id) })))
)
const narrowed = $derived(
access
? (workspaceAccess.current ?? []).flatMap(({ id, there }) => {
const why = accessNarrowing(access!, there)
return why ? [{ id, why }] : []
})
: []
const toolsetAccess = $derived(
access === 'selected' || !access
? undefined
: served
? connectionLevel(served, access).level
: access
)
</script>
<div class="flex flex-col gap-4">
<div>
<span class="block mb-1 text-emphasis text-xs font-semibold">Access</span>
<ToggleButtonGroup bind:selected={access} allowEmpty={false}>
{#snippet children({ item })}
<ToggleButton
{item}
value="full"
label="Build and run"
tooltip="Everything you can do yourself: explore, write, test and deploy drafts, and run."
/>
<ToggleButton
{item}
value="read_run"
label="Read and run"
tooltip="Explore, and run deployed scripts, flows and agents. The client changes nothing itself; what it runs can."
/>
<ToggleButton
{item}
value="read"
label="Read only"
tooltip="Explore and read. Nothing is run or changed."
/>
<ToggleButton
{item}
value="selected"
label="Scripts and flows as tools"
tooltip="The scripts and flows you pick, each as its own tool, and nothing else. To share a few automations."
/>
{/snippet}
</ToggleButtonGroup>
</div>
{#if narrowed.length > 0}
<Alert type="warning" size="xs" title="Narrower in some workspaces">
<ul class="flex flex-col gap-0.5">
{#each narrowed as { id, why } (id)}
<li>In <span class="font-semibold">{id}</span>, {why}.</li>
{/each}
</ul>
</Alert>
{/if}
<McpAccessSection tools={showTools && toolsetAccess ? { level: toolsetAccess } : undefined}>
<Select items={LEVELS} bind:value={() => access, (v) => v && (access = v as McpAccess)} />
{#if access}
<p class="text-2xs text-secondary">{ACCESS_HINTS[access]}</p>
{/if}
{@render belowAccess?.()}
</McpAccessSection>
{@render afterAccess?.()}
{#if toolsetAccess}
<Section label="Tools the client gets" small collapsable bind:collapsed={toolsCollapsed}>
<div class="flex flex-col gap-1 -mt-2">
<span class="text-2xs text-secondary">
{tools ? `${tools.length} tools. Hover one for what it does.` : 'Loading tools…'}
</span>
<div class="flex flex-wrap gap-1">
{#each tools ?? [] as tool (tool.name)}
<Popover notClickable>
{#snippet text()}
<div class="text-xs max-w-md">{tool.description}</div>
{/snippet}
<Badge rounded small color="gray">{tool.name}</Badge>
</Popover>
{/each}
</div>
</div>
</Section>
{/if}
{#if access === 'selected'}
<p class="text-2xs text-secondary -mt-2">
The client can run these scripts and flows and nothing else: it cannot explore the workspace,
read runs, build, or run anything outside the selection.
</p>
<!-- A selection names paths of one workspace, so switching workspace starts it over. -->
{#key workspaceId}
<McpScopeSelector {workspaceId} bind:scope={selection} initialScope={initialSelection} />
@@ -0,0 +1,40 @@
<script lang="ts">
import type { Snippet } from 'svelte'
import { Button } from '$lib/components/common'
import { Wrench } from 'lucide-svelte'
import McpToolsModal from './McpToolsModal.svelte'
import type { ToolsetLevel } from './toolsets.svelte'
interface Props {
/** The tools "Show tools" lists: a level's, or the scripts and flows a role offers as tools
* in `workspace`. None hides the button. */
tools?: { level?: ToolsetLevel; workspace?: string }
children: Snippet
}
let { tools, children }: Props = $props()
let open = $state(false)
const shown = $derived(!!tools && (!!tools.level || !!tools.workspace))
</script>
<div class="flex flex-col gap-1">
<div class="flex items-center gap-1.5">
<span class="text-xs font-semibold text-emphasis">Access</span>
{#if shown}
<div class="grow"></div>
<Button
variant="subtle"
unifiedSize="2xs"
startIcon={{ icon: Wrench }}
onClick={() => (open = true)}
>
Show tools
</Button>
{/if}
</div>
{@render children()}
</div>
{#if shown}
<McpToolsModal bind:open level={tools?.level} workspace={tools?.workspace} />
{/if}
@@ -0,0 +1,103 @@
<script lang="ts">
import type { McpWorkspaceAccess } from '$lib/gen'
import { Button } from '$lib/components/common'
import { copyToClipboard } from '$lib/utils'
import { ChevronDown, ChevronRight, Copy } from 'lucide-svelte'
import { workspaceMcpUrl } from './workspaceAccess'
interface Props {
/** Workspaces whose role offers scripts and flows as tools, which a connection covering
* several workspaces leaves out. */
workspaces: McpWorkspaceAccess[]
/** Each needs a connection of its own, none of the others being included either. */
onTheirOwn?: boolean
/** A read-only connection, which runs no tool, so their URLs would give it nothing. */
readOnly?: boolean
/** Offers each workspace's own URL to copy. */
showUrl?: boolean
/** Narrows the connection to that workspace; none hides the button. */
onSelect?: (id: string) => void
}
let {
workspaces,
onTheirOwn = false,
readOnly = false,
showUrl = false,
onSelect
}: Props = $props()
let open = $state(false)
const one = $derived(workspaces.length === 1)
const urlHint = $derived(`add ${one ? 'its' : 'each'} workspace URL to your AI client`)
const explanation = $derived(
'Scripts and flows as tools need a connection of their own' +
(showUrl && onSelect
? `: ${urlHint}, or select it here instead.`
: showUrl
? `: ${urlHint}.`
: onSelect
? ': select it here instead.'
: '.')
)
</script>
{#if workspaces.length > 0}
<div class="flex flex-col gap-2 rounded-md border bg-surface-secondary p-3">
<Button
variant="subtle"
unifiedSize="xs"
btnClasses="-m-1 w-fit font-semibold text-emphasis"
startIcon={{ icon: open ? ChevronDown : ChevronRight }}
aria-expanded={open}
onClick={() => (open = !open)}
>
{one ? 'Workspace' : 'Workspaces'}
{workspaces.map((w) => w.name).join(', ')}
{onTheirOwn
? one
? 'connects on its own'
: 'connect on their own'
: one
? 'is not included'
: 'are not included'}
</Button>
{#if open && readOnly}
<p class="text-xs text-primary">
{one ? 'Its role offers' : 'Their roles offer'} only scripts and flows as tools, which a read-only
client cannot run.
</p>
{:else if open}
<p class="text-xs text-primary">{explanation}</p>
{#if showUrl || onSelect}
<div class="flex flex-col gap-1">
{#each workspaces as w (w.id)}
<div class="flex items-center justify-between gap-2">
{#if !one}
<span class="text-xs font-semibold text-emphasis truncate">{w.name}</span>
{/if}
<div class="flex shrink-0 gap-1">
{#if showUrl}
<Button
variant="default"
unifiedSize="xs"
startIcon={{ icon: Copy }}
title={workspaceMcpUrl(w.id)}
onClick={() => copyToClipboard(workspaceMcpUrl(w.id), true)}
>
Copy workspace URL
</Button>
{/if}
{#if onSelect}
<Button variant="default" unifiedSize="xs" onClick={() => onSelect(w.id)}>
Select it
</Button>
{/if}
</div>
</div>
{/each}
</div>
{/if}
{/if}
</div>
{/if}
@@ -0,0 +1,55 @@
<script lang="ts">
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
import AssistantToolsSection from '$lib/components/copilot/chat/AssistantToolsSection.svelte'
import { runnableToolset, toolset, type ToolsetLevel } from './toolsets.svelte'
let {
open = $bindable(false),
level,
workspace
}: {
open: boolean
level?: ToolsetLevel
/** Lists the scripts and flows the role offers as tools there, in place of a level's. */
workspace?: string
} = $props()
let blocksClose = $state(false)
const tools = $derived(
!open ? undefined : workspace ? runnableToolset(workspace) : level ? toolset(level) : []
)
const summaries = $derived(
(tools ?? [])
.map((t) => ({
name: t.name,
description: t.description,
parameters: { required: [], ...(t.parameters ?? {}) }
}))
.sort((a, b) => a.name.localeCompare(b.name))
)
</script>
<Modal2
bind:isOpen={open}
title="What the client can call"
fixedWidth="md"
fixedHeight="lg"
closeOnOutsideClick={!blocksClose}
closeOnEscape={!blocksClose}
>
<div class="flex grow min-h-0 flex-col overflow-hidden">
{#if tools}
<AssistantToolsSection
tools={summaries}
providerTools={[]}
active={open}
bind:blocksClose
description={workspace
? `The scripts and flows your role offers in ${workspace}, one tool each.`
: "Where a workspace's role allows less, the call is refused there."}
/>
{:else}
<p class="p-4 text-xs text-secondary">Loading tools…</p>
{/if}
</div>
</Modal2>
@@ -1,31 +0,0 @@
import { describe, expect, it } from 'vitest'
import { accessNarrowing } from './accessNarrowing'
import {
capabilitiesForRole,
fullSessionAccess
} from '$lib/components/copilot/chat/global/sessionAccess'
import { NO_RUN_ACCESS, USE_MODE_ACCESS } from '$lib/components/copilot/chat/sessionCapabilities'
import { FULL_CAPABILITIES } from '$lib/roleCapabilities'
describe('accessNarrowing', () => {
it('says nothing where the workspace holds the token to what was picked', () => {
for (const picked of ['full', 'read_run', 'read', 'selected'] as const)
expect(accessNarrowing(picked, fullSessionAccess())).toBeUndefined()
expect(accessNarrowing('read_run', USE_MODE_ACCESS)).toBeUndefined()
expect(accessNarrowing('read', NO_RUN_ACCESS)).toBeUndefined()
})
it('names how a workspace narrows each level', () => {
expect(accessNarrowing('read_run', NO_RUN_ACCESS)).toContain('only reads')
expect(accessNarrowing('selected', NO_RUN_ACCESS)).toContain('no tools')
expect(accessNarrowing('full', USE_MODE_ACCESS)).toContain('protected')
const noCode = capabilitiesForRole({
isAdmin: false,
deployRulesPass: false,
capabilities: { ...FULL_CAPABILITIES, code: false, flows: 'compose', apps: 'compose' }
})
expect(accessNarrowing('full', noCode)).toBe(
"your role can't build scripts and the deploy rules don't let you deploy, so the client can't either"
)
})
})
@@ -1,38 +0,0 @@
import type {
SessionAccess,
SessionCapability
} from '$lib/components/copilot/chat/sessionCapabilities'
import type { McpAccess } from './McpAccessPicker.svelte'
const BUILDS: [SessionCapability, string][] = [
['write_draft', 'scripts'],
['write_flow_draft', 'flows'],
['write_app_draft', 'apps'],
['write_schedule_draft', 'schedules'],
['write_trigger_draft', 'triggers']
]
/** How a workspace narrows the access picked for a token, read from the session access the chat
* resolves there (`resolveSessionAccess`), the twin of what the MCP server holds the token to. */
export function accessNarrowing(picked: McpAccess, there: SessionAccess): string | undefined {
if (picked === 'read') return undefined
if (!there.has('run'))
return picked === 'selected'
? "your role can't run anything, so the client gets no tools"
: "your role can't run anything, so the client only reads"
if (picked !== 'full') return undefined
if (!there.has('modify_workspace'))
return 'it is protected against direct changes, so the client only reads and runs'
const cannot = BUILDS.filter(([cap]) => !there.has(cap)).map(([, what]) => what)
const parts: string[] = []
if (cannot.length > 0) parts.push(`your role can't build ${listed(cannot)}`)
if (!there.has('deploy')) parts.push("the deploy rules don't let you deploy")
if (parts.length === 0) return undefined
return `${parts.join(' and ')}, so the client can't either`
}
function listed(items: string[]): string {
return items.length === 1
? items[0]
: `${items.slice(0, -1).join(', ')} or ${items[items.length - 1]}`
}
@@ -0,0 +1,36 @@
import { SvelteMap } from 'svelte/reactivity'
export type ToolsetEntry = {
name: string
description: string
/** The JSON Schema of its arguments. */
parameters?: Record<string, any>
}
export type ToolsetLevel = 'read' | 'read_run' | 'full'
const toolsets = new SvelteMap<string, ToolsetEntry[]>()
const loading = new Set<string>()
function load(url: string): ToolsetEntry[] | undefined {
if (!toolsets.has(url) && !loading.has(url)) {
loading.add(url)
fetch(url)
.then((r) => (r.ok ? r.json() : []))
.then((tools: ToolsetEntry[]) => toolsets.set(url, tools))
.catch(() => toolsets.set(url, []))
.finally(() => loading.delete(url))
}
return toolsets.get(url)
}
/** The tools the server lists for an access level, undefined until loaded. The first read
* starts the load. */
export function toolset(level: ToolsetLevel): ToolsetEntry[] | undefined {
return load(`/api/mcp/toolset?access=${level}`)
}
/** The scripts and flows a connection to `workspace` lists where the caller's role offers them
* as tools. */
export function runnableToolset(workspace: string): ToolsetEntry[] | undefined {
return load(`/api/w/${encodeURIComponent(workspace)}/mcp/runnable_tools`)
}
@@ -0,0 +1,112 @@
import { describe, expect, it } from 'vitest'
import type { McpWorkspaceAccess } from '$lib/gen'
import type { McpAccess } from './McpAccessPicker.svelte'
import {
accessLabel,
connectionLevel,
defaultConnection,
narrows,
restricted,
servedOn,
toolsetLevel
} from './workspaceAccess'
const ws = (id: string, access: McpWorkspaceAccess['access']): McpWorkspaceAccess => ({
id,
name: id,
access,
restricted: false
})
describe('defaultConnection', () => {
it('covers every workspace as soon as one serves the session toolset', () => {
expect(defaultConnection([ws('a', 'runnables'), ws('b', 'read_only')]).all).toBe(true)
expect(defaultConnection([]).all).toBe(true)
})
it('preselects one workspace when all of them are tools', () => {
const one = { all: false, picked: ['a'], oneEach: false }
expect(defaultConnection([ws('a', 'runnables')])).toEqual(one)
expect(defaultConnection([ws('x', 'off'), ws('a', 'runnables')])).toEqual(one)
const several = defaultConnection([ws('a', 'runnables'), ws('b', 'runnables')])
expect(several).toEqual({ ...one, oneEach: true })
})
})
it('names the lower of the picked access and the workspace one', () => {
expect(accessLabel(ws('a', 'build_and_run'), 'read_run')).toBe('Read and run')
expect(accessLabel(ws('a', 'read_and_run'), 'full')).toBe('Read and run')
expect(accessLabel(ws('a', 'read_and_run'), 'read')).toBe('Read only')
expect(accessLabel({ ...ws('a', 'runnables'), runnables: 12 }, 'full')).toBe(
'12 scripts and flows as tools'
)
const edits = ws('a', 'run_and_edit')
expect(accessLabel(edits, 'full')).toBe('Everything your role allows')
expect(restricted(edits, 'full')).toBe(true)
expect(restricted(edits, 'read_run')).toBe(false)
expect(accessLabel(ws('a', 'run_and_edit'), 'read_run')).toBe('Read and run')
expect(accessLabel(ws('a', 'read_only'), 'read_run')).toBe('Read only')
expect(accessLabel(ws('a', 'read_only'), 'selected')).toBe('Not available')
expect(accessLabel(ws('a', 'runnables'), 'read')).toBe('Not available')
})
it('serves a tools workspace only to a connection covering it alone', () => {
const tools = ws('a', 'runnables')
const session = ws('b', 'read_only')
expect(servedOn([tools], false, 'full')).toEqual([tools])
expect(servedOn([tools], true, 'full')).toEqual([])
expect(servedOn([tools], true, 'read')).toEqual([])
expect(servedOn([tools, session], false, 'full')).toEqual([session])
})
it('lists the session tools of the lower of the picked access and the workspace one', () => {
expect(toolsetLevel(ws('a', 'build_and_run'), 'full')).toBe('full')
expect(toolsetLevel(ws('a', 'run_and_edit'), 'full')).toBe('full')
expect(toolsetLevel(ws('a', 'read_and_run'), 'full')).toBe('read_run')
expect(toolsetLevel(ws('a', 'read_only'), 'read_run')).toBe('read')
expect(toolsetLevel(ws('a', 'build_and_run'), 'read')).toBe('read')
expect(toolsetLevel(ws('a', 'runnables'), 'full')).toBeUndefined()
expect(toolsetLevel(ws('a', 'build_and_run'), 'selected')).toBeUndefined()
})
describe('narrows', () => {
it('flags a workspace giving less or other than the pick', () => {
expect(narrows(ws('a', 'build_and_run'), 'full')).toBe(false)
expect(narrows(ws('a', 'read_and_run'), 'full')).toBe(true)
expect(narrows(ws('a', 'run_and_edit'), 'full')).toBe(true)
expect(narrows(ws('a', 'read_only'), 'read_run')).toBe(true)
expect(narrows(ws('a', 'read_only'), 'read')).toBe(false)
expect(narrows(ws('a', 'runnables'), 'full')).toBe(true)
expect(narrows(ws('a', 'read_only'), 'selected')).toBe(true)
expect(narrows(ws('a', 'off'), 'read')).toBe(true)
const partial = { ...ws('a', 'build_and_run'), restricted: true }
expect(narrows(partial, 'full')).toBe(true)
expect(narrows(partial, 'read_run')).toBe(false)
})
})
describe('connectionLevel', () => {
const level = (served: McpWorkspaceAccess[], picked: McpAccess = 'full') => {
const { label, less } = connectionLevel(served, picked)
return [label, less]
}
it('shows the highest level a workspace gives, and whether another gives less', () => {
expect(level([ws('a', 'read_only')])).toEqual(['Read only', false])
expect(level([ws('a', 'read_only'), ws('b', 'read_only')])).toEqual(['Read only', false])
expect(level([ws('a', 'read_only'), ws('b', 'read_and_run')])).toEqual(['Read and run', true])
expect(level([ws('a', 'build_and_run'), ws('b', 'read_only')])).toEqual([
'Everything your role allows',
true
])
expect(level([ws('a', 'build_and_run'), ws('b', 'build_and_run')])).toEqual([
'Everything your role allows',
false
])
expect(level([ws('a', 'run_and_edit')])).toEqual(['Everything your role allows', true])
})
it('caps it at what the client asked for', () => {
expect(level([ws('a', 'build_and_run'), ws('b', 'read_only')], 'read')).toEqual([
'Read only',
false
])
})
})
@@ -0,0 +1,161 @@
import { apiBaseUrl } from '$lib/apiBaseUrl.svelte'
import type { McpWorkspaceAccess } from '$lib/gen'
import type { McpAccess } from './McpAccessPicker.svelte'
import type { ToolsetLevel } from './toolsets.svelte'
export type WorkspaceAccess = McpWorkspaceAccess['access']
/** What each access level lets the client do. */
export const ACCESS_HINTS: Record<McpAccess, string> = {
full: 'Explore, build, test, deploy and run, as far as your role allows.',
read_run:
'Explore, and run deployed scripts, flows and agents, without building or deploying anything.',
read: 'Explore and read. Nothing is run or changed.',
selected: 'The scripts and flows you pick, each as its own tool. To share a few automations.'
}
const LABELS: Record<WorkspaceAccess, string> = {
build_and_run: 'Everything your role allows',
run_and_edit: 'Everything your role allows',
read_and_run: 'Read and run',
read_only: 'Read only',
runnables: 'Scripts and flows as tools',
off: 'Not available'
}
/** Whether a connection with the `picked` access gets anything in a workspace: tools run, so a
* read-only pick leaves nothing of a role's tools, and a read-only role nothing of a selection. */
export function givesAnything(workspace: McpWorkspaceAccess, picked: McpAccess): boolean {
const { access } = workspace
return !(
access === 'off' ||
(picked === 'read' && access === 'runnables') ||
(picked === 'selected' && access === 'read_only')
)
}
/** What a connection with the `picked` access gets in a workspace. */
export function accessLabel(workspace: McpWorkspaceAccess, picked: McpAccess): string {
const { access, runnables } = workspace
if (!givesAnything(workspace, picked)) return LABELS.off
if (picked === 'read') return LABELS.read_only
if (picked === 'selected') {
return access === 'runnables'
? 'The ones you select among those your role offers'
: 'The scripts and flows you select'
}
if (access === 'runnables') {
if (runnables === undefined) return LABELS.runnables
return `${runnables} ${runnables === 1 ? 'script or flow' : 'scripts and flows'} as tools`
}
if (picked === 'read_run' && access !== 'read_only') return LABELS.read_and_run
return LABELS[access]
}
/** Whether build and run holds back something in a workspace all the same, keeping the label
* of the level picked: a role writing no scripts, flows or apps, or only some kinds, or deploy
* rules blocking the user. */
export function restricted(workspace: McpWorkspaceAccess, picked: McpAccess): boolean {
return (
picked === 'full' &&
(workspace.access === 'run_and_edit' ||
(workspace.access === 'build_and_run' && workspace.restricted))
)
}
/** The covered workspaces a connection serves. One set to scripts and flows as tools is served
* only to a connection covering it alone. */
export function servedOn(
covered: McpWorkspaceAccess[],
all: boolean,
picked: McpAccess
): McpWorkspaceAccess[] {
const alone = !all && covered.length === 1
return covered.filter((w) => w.access !== 'runnables' || alone)
}
/** The session toolset a connection with the `picked` access gets in a workspace, none where it
* gets scripts and flows as tools or nothing. */
export function toolsetLevel(
workspace: McpWorkspaceAccess,
picked: McpAccess
): ToolsetLevel | undefined {
const { access } = workspace
if (access === 'runnables' || access === 'off' || picked === 'selected') return undefined
if (picked === 'read' || access === 'read_only') return 'read'
// A role that edits a few kinds is served the full toolset, held to those kinds.
if (picked === 'read_run' || access === 'read_and_run') return 'read_run'
return 'full'
}
export const RANK: Record<ToolsetLevel, number> = { read: 0, read_run: 1, full: 2 }
const LEVEL_LABELS: Record<ToolsetLevel, string> = {
full: LABELS.build_and_run,
read_run: LABELS.read_and_run,
read: LABELS.read_only
}
/** The one access a connection is shown: the highest level a served workspace gives, and whether
* another gives less. Which one gives less is not named, its role refusing per call. */
export function connectionLevel(
served: McpWorkspaceAccess[],
picked: McpAccess
): { level?: ToolsetLevel; label: string; hint: string; less: boolean } {
const levels = served.map((w) => toolsetLevel(w, picked))
const level = levels.reduce<ToolsetLevel | undefined>(
(top, l) => (l && (!top || RANK[l] > RANK[top]) ? l : top),
undefined
)
if (!level) {
// Nothing of the session toolset: a selection, scripts and flows as tools, or nothing.
const first = served[0]
return {
label: first ? accessLabel(first, picked) : LABELS.off,
hint: first ? accessHint(first, picked) : '',
less: false
}
}
const less = served.some((w, i) => levels[i] !== level || restricted(w, picked))
return { level, label: LEVEL_LABELS[level], hint: ACCESS_HINTS[level], less }
}
/** The MCP URL connecting to this workspace alone. */
export function workspaceMcpUrl(id: string): string {
return `${apiBaseUrl('mcp')}/api/mcp/w/${id}/mcp`
}
export type ConnectionDefault = {
/** Every workspace, those joined later included. */
all: boolean
picked: string[]
/** Each workspace needs a connection of its own, so one is preselected. */
oneEach: boolean
}
/** The workspaces a connection on the global URL covers by default. Scripts and flows as tools
* are served to a connection covering that workspace alone, so where a user has nothing else,
* one workspace is preselected: all of them would leave the client without a tool. */
export function defaultConnection(workspaces: McpWorkspaceAccess[]): ConnectionDefault {
const asTools = workspaces.filter((w) => w.access === 'runnables')
const session = workspaces.some((w) => w.access !== 'runnables' && w.access !== 'off')
if (session || asTools.length === 0) return { all: true, picked: [], oneEach: false }
const first = asTools.find((w) => w.runnables) ?? asTools[0]
return { all: false, picked: [first.id], oneEach: asTools.length > 1 }
}
/** What a level means in a workspace. */
export function accessHint(workspace: McpWorkspaceAccess, picked: McpAccess): string {
const level = toolsetLevel(workspace, picked)
return !givesAnything(workspace, picked)
? 'Nothing the client can use there with this access.'
: workspace.access === 'runnables'
? 'The scripts and flows your role offers, each as its own tool.'
: ACCESS_HINTS[level ?? picked]
}
/** Whether a workspace gives less than, or other than, the `picked` access. */
export function narrows(workspace: McpWorkspaceAccess, picked: McpAccess): boolean {
if (!givesAnything(workspace, picked) || restricted(workspace, picked)) return true
if (picked === 'read' || picked === 'selected') return false
return workspace.access === 'runnables' || toolsetLevel(workspace, picked) !== picked
}
@@ -1,5 +1,6 @@
<script lang="ts">
import { onMount, untrack } from 'svelte'
import { resource } from 'runed'
import {
enterpriseLicense,
superadmin,
@@ -11,7 +12,13 @@
import { Alert, Button, Skeleton } from '../common'
import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte'
import Toggle from '../Toggle.svelte'
import { SettingService, SettingsService, UserService, type NewToken } from '$lib/gen'
import {
McpOauthService,
SettingService,
SettingsService,
UserService,
type NewToken
} from '$lib/gen'
import { listEveryWorkspace, mcpTokenUrlDisabled } from '$lib/mcpAuth'
import { apiBaseUrl } from '$lib/apiBaseUrl.svelte'
import TokenDisplay from './TokenDisplay.svelte'
@@ -25,7 +32,10 @@
import Select from '../select/Select.svelte'
import Section from '../Section.svelte'
import ClipboardPanel from '../details/ClipboardPanel.svelte'
import { servedOn, workspaceMcpUrl } from '../mcp/workspaceAccess'
import McpNotIncludedCard from '../mcp/McpNotIncludedCard.svelte'
import McpAccessPicker, { type McpAccess } from '../mcp/McpAccessPicker.svelte'
import McpAccessLine from '../mcp/McpAccessLine.svelte'
import MultiSelect from '../select/MultiSelect.svelte'
import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte'
import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte'
@@ -64,6 +74,7 @@
let newTokenTestOpen = $state(false)
let newMcpToken = $state<string | undefined>(undefined)
let newMcpTokenUrl = $state('')
let newMcpWorkspaceTokenUrl = $state('')
// What an MCP token may do, as the access picker sets it.
let mcpAccess = $state<McpAccess>('full')
let mcpScopes = $state<string[]>(['mcp:all'])
@@ -198,7 +209,6 @@
mcpCreationMode = true
void loadMcpUrlPolicy()
resetExpirationOnModeChange()
mcpAllWorkspaces = false
const current = defaultNewTokenWorkspace ?? $operatingWorkspace
// A token locked to a workspace the superadmin is not a member of works only with their rights.
mcpSuperAdmin =
@@ -206,6 +216,9 @@
!!$superadmin &&
!!current &&
!($usersWorkspaceStore?.workspaces ?? []).some((w) => w.id === current)
// Every workspace by default, as a sign-in does, with the current one kept picked for
// narrowing; but superadmin rights stay confined to the workspace that needs them.
mcpAllWorkspaces = !mcpSuperAdmin
mcpWorkspaces =
current && (lockWorkspace || mcpWorkspaceItems.some((w) => w.value === current))
? [current]
@@ -247,10 +260,8 @@
if (on) {
everyWorkspace = await listEveryWorkspace()
}
if (!lockWorkspace) {
const offered = new Set(mcpWorkspaceItems.map((w) => w.value))
mcpWorkspaces = mcpWorkspaces.filter((w) => offered.has(w))
}
const offered = new Set(mcpWorkspaceItems.map((w) => w.value))
mcpWorkspaces = mcpWorkspaces.filter((w) => offered.has(w))
}
async function createToken(mcpMode: boolean = false): Promise<void> {
@@ -281,7 +292,15 @@
if (mcpMode) {
newToken = undefined
newMcpToken = `${createdToken}`
newMcpTokenUrl = `${mcpUrl}?token=${createdToken}`
newMcpTokenUrl = `${urlFor(mcpBoundWorkspace)}?token=${createdToken}`
// The token reaches the home workspace's own URL too when it covers that workspace.
newMcpWorkspaceTokenUrl =
workspaceUrlOffered &&
homeWorkspace &&
mcpBoundWorkspace !== homeWorkspace &&
(mcpAllWorkspaces || mcpWorkspaces.includes(homeWorkspace))
? `${workspaceMcpUrl(homeWorkspace)}?token=${createdToken}`
: ''
} else {
newMcpToken = undefined
newToken = `${createdToken}`
@@ -365,8 +384,40 @@
''
)
// The server builds this URL's OAuth metadata from the same API base url, and a client
// rejects a mismatch. One URL whatever the access: the token's scopes decide which tools it gets.
const mcpUrl = $derived(`${apiBaseUrl('mcp')}/api/mcp`)
// rejects a mismatch. One URL whatever the access, as the token's scopes decide which tools it
// gets, but for a workspace whose role offers scripts and flows as tools: those are served to a
// connection to that workspace alone, which its own URL makes of any sign-in.
const mcpWorkspaceAccess = resource(
() => [mcpCreationMode, mcpSuperAdmin] as const,
async ([on, superAdmin]) =>
on ? await McpOauthService.listMcpWorkspaceAccess({ superAdmin }).catch(() => []) : []
)
const asTools = (id: string | undefined) =>
!!id && !!mcpWorkspaceAccess.current?.some((w) => w.id === id && w.access === 'runnables')
// The home page's tab is about its own workspace, whatever the token form picks.
const homeWorkspace = $derived(
lockWorkspace ? (defaultNewTokenWorkspace ?? $operatingWorkspace) : undefined
)
const signInWorkspace = $derived(homeWorkspace ?? mcpBoundWorkspace)
const mcpAsTools = $derived(asTools(signInWorkspace))
// Shown only where a workspace gives other than the picked access.
const mcpCovered = $derived(
(mcpWorkspaceAccess.current ?? []).filter(
(w) => mcpAllWorkspaces || mcpWorkspaces.includes(w.id)
)
)
const mcpServed = $derived(servedOn(mcpCovered, mcpAllWorkspaces, mcpAccess))
// Left out of a token reaching several workspaces, as on the consent page.
const mcpLeftOut = $derived(
mcpAccess === 'selected'
? []
: mcpCovered.filter((w) => w.access === 'runnables' && !mcpServed.includes(w))
)
// The home page's tab also offers the workspace's own URL where `/api/mcp` is the main one.
const workspaceUrlOffered = $derived(!!homeWorkspace && !mcpAsTools)
const urlFor = (id: string | undefined) =>
id && asTools(id) ? workspaceMcpUrl(id) : `${apiBaseUrl('mcp')}/api/mcp`
const mcpUrl = $derived(urlFor(signInWorkspace))
$effect(() => {
const requestedMcpMode = mcpOnly || openWithMcpMode
@@ -392,17 +443,27 @@
{#snippet mcpTokenForm()}
<div class="flex flex-col gap-3">
{#if !lockWorkspace}
{@render mcpWorkspacePicker()}
{@render mcpWorkspacePicker()}
{#if mcpLeftOut.length > 0}
<McpNotIncludedCard
workspaces={mcpLeftOut}
readOnly={mcpAccess === 'read'}
onSelect={(id) => {
mcpAllWorkspaces = false
mcpWorkspaces = [id]
}}
/>
{/if}
<McpAccessPicker
workspaceId={scopeWorkspaceId}
workspaces={mcpAllWorkspaces
? ($usersWorkspaceStore?.workspaces ?? []).map((w) => w.id)
: mcpWorkspaces}
bind:scopes={mcpScopes}
bind:access={() => mcpAccess, setMcpAccess}
showTools
served={mcpServed}
>
{#snippet belowAccess()}
<div class="mt-1"><McpAccessLine workspaces={mcpServed} access={mcpAccess} /></div>
{/snippet}
{#snippet afterAccess()}
{#if canCarryAdmin}
{@render adminToggle(mcpSuperAdmin)}
@@ -410,6 +471,7 @@
{#if $superadmin}
<Toggle
bind:checked={() => mcpSuperAdmin, setMcpSuperAdmin}
disabled={mcpWorkspaceAccess.loading}
options={{
right: 'Superadmin rights',
rightTooltip:
@@ -587,14 +649,30 @@
{:else if mcpCreationMode}
<div class="flex flex-col gap-6">
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">MCP URL</span>
<span class="text-xs font-semibold text-emphasis"
>{workspaceUrlOffered ? 'Global MCP URL' : 'MCP URL'}</span
>
<ClipboardPanel content={mcpUrl} size="sm" />
<p class="text-2xs text-secondary">
Add it to your client as a remote MCP server. It opens a Windmill page where you sign in
and choose the workspaces and what the client may do: build and run, read and run, read
only, or only the scripts and flows you pick.
Add it to your client as a remote MCP server.
{#if mcpAsTools}
It opens a Windmill page where you sign in, and gives the client the scripts and flows
your role offers in this workspace as tools.
{:else}
It opens a Windmill page where you sign in and choose the workspaces. You can limit
what the client may do there.
{/if}
</p>
</div>
{#if workspaceUrlOffered && homeWorkspace}
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">{homeWorkspace} MCP URL</span>
<ClipboardPanel content={workspaceMcpUrl(homeWorkspace)} size="sm" />
<p class="text-2xs text-secondary">
The sign-in skips the workspace choice, and the client reaches no other workspace.
</p>
</div>
{/if}
{#if mcpUrlPolicy === 'token'}
<Section label="Use a token instead of signing in" small collapsable collapsed>
@@ -730,10 +808,10 @@
</p>
{#if privateRangesTrusted && allowedIps.length > 0}
<Alert type="warning" size="xs" title="Insiders can claim an allowed address">
This instance trusts a whole private range as proxies, so a host on its private network,
a job included, can name its own client address. The allowlist holds against callers
outside that network only. An instance admin can list the reverse proxies on the Client
IP instance settings page.
This instance trusts a whole private range as proxies, so a host on its private
network, a job included, can name its own client address. The allowlist holds against
callers outside that network only. An instance admin can list the reverse proxies on
the Client IP instance settings page.
</Alert>
{/if}
{#if clientIp}
@@ -799,6 +877,11 @@
{/if}
{#if newMcpToken && displayCreateToken}
<TokenDisplay token={newMcpToken} mcpUrl={newMcpTokenUrl} />
<TokenDisplay
token={newMcpToken}
mcpUrl={newMcpTokenUrl}
workspaceMcpUrl={newMcpWorkspaceTokenUrl || undefined}
workspace={homeWorkspace}
/>
{/if}
</div>
@@ -1,6 +1,10 @@
<script lang="ts">
import { untrack } from 'svelte'
import { UserService } from '$lib/gen'
import { McpOauthService, UserService } from '$lib/gen'
import { resource } from 'runed'
import McpAccessLine from '$lib/components/mcp/McpAccessLine.svelte'
import { servedOn } from '$lib/components/mcp/workspaceAccess'
import McpNotIncludedCard from '$lib/components/mcp/McpNotIncludedCard.svelte'
import { sendUserToast } from '$lib/toast'
import Button from '../common/button/Button.svelte'
import Modal from '../common/modal/Modal.svelte'
@@ -102,6 +106,20 @@
const warnsFor = $derived(
mcpEdited || (initialScopes ?? []).some(describedByPicker) ? mcpReached : []
)
const mcpWorkspaceAccess = resource(
() => isMcp,
async (on) => (on ? await McpOauthService.listMcpWorkspaceAccess({}).catch(() => []) : [])
)
const mcpAccess = $derived(mcpAccessOf(mcpScopes))
const mcpCovered = $derived(
(mcpWorkspaceAccess.current ?? []).filter((w) => warnsFor.includes(w.id))
)
const mcpServed = $derived(servedOn(mcpCovered, false, mcpAccess))
const mcpLeftOut = $derived(
mcpAccess === 'selected'
? []
: mcpCovered.filter((w) => w.access === 'runnables' && !mcpServed.includes(w))
)
// 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
// back to the endpoint tools once it is given `mcp:all` again.
@@ -249,10 +267,18 @@
>
<McpAccessPicker
workspaceId={mcpWorkspaceId}
workspaces={warnsFor}
initialScopes={(initialScopes ?? []).filter((s) => !isWorkspaceList(s))}
bind:scopes={mcpScopes}
/>
>
{#snippet belowAccess()}
<div class="mt-1"><McpAccessLine workspaces={mcpServed} access={mcpAccess} /></div>
{#if mcpLeftOut.length > 0}
<div class="mt-2">
<McpNotIncludedCard workspaces={mcpLeftOut} readOnly={mcpAccess === 'read'} />
</div>
{/if}
{/snippet}
</McpAccessPicker>
</div>
{:else}
<ScopesPicker workspaceId={mcpWorkspaceId} {initialScopes} bind:value={pickedScopes} />
@@ -1,85 +1,55 @@
<script lang="ts">
import { Check, Link, X } from 'lucide-svelte'
import { X } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import Alert from '../common/alert/Alert.svelte'
import { classes } from '../common/alert/model'
import { shell } from 'svelte-highlight/languages'
import CopyableCodeBlock from '../details/CopyableCodeBlock.svelte'
import ClipboardPanel from '../details/ClipboardPanel.svelte'
interface Props {
token: string
mcpUrl?: string
/** The same token on one workspace's own URL. */
workspaceMcpUrl?: string
workspace?: string
title?: string
onClose?: () => void
}
let { token, mcpUrl, title, onClose }: Props = $props()
let { token, mcpUrl, workspaceMcpUrl, workspace, title, onClose }: Props = $props()
const displayTitle = $derived(
title || (mcpUrl ? 'MCP URL generated successfully' : 'Token created successfully')
)
const info = $derived(
`Make sure to copy your ${mcpUrl ? 'MCP Server URL' : 'personal access token'} now. You won\'t be able to see it again!`
)
const tokenOrUrl = $derived(mcpUrl ? mcpUrl : token)
// Use alert model for consistent styling with design system
const alertStyles = classes.info
const displayTitle = $derived(title || (mcpUrl ? 'MCP URL generated' : 'Token created'))
</script>
<!-- Use surface-tertiary for elevated content according to brand guidelines -->
<div class="border bg-surface-tertiary rounded-lg mb-6 p-4 shadow-md relative">
<!-- Close button in top-right corner -->
{#if onClose}
<button
onclick={onClose}
class="absolute top-2 right-2 p-1 text-secondary hover:text-primary surface-hover hover:surface-secondary rounded transition-colors"
title="Close"
>
<X size={16} />
</button>
{/if}
<div class="flex items-start gap-3">
<!-- Icon with info alert styling -->
<div
class="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center mt-0.5 {alertStyles.iconClass}"
>
{#if mcpUrl}
<Link size={16} />
{:else}
<Check size={16} />
{/if}
</div>
<div class="flex-1 min-w-0 pr-6">
<!-- Page title typography according to brand guidelines -->
<h4 class="text-sm font-semibold text-emphasis mb-2">
{displayTitle}
</h4>
<div class="flex flex-col gap-y-1">
<!-- Token display with proper surface and border styling -->
<CopyableCodeBlock code={tokenOrUrl} language={shell} wrap />
<!-- Warning alert using existing Alert component -->
<div class="mt-1">
<Alert type="warning" title="Important" size="xs">
{info}
</Alert>
</div>
{#if mcpUrl}
<!-- Additional info using alert info styling -->
<div class="mt-1 {alertStyles.bgClass} rounded-md p-2">
<p class="text-xs {alertStyles.descriptionClass}">
<strong>Next steps:</strong> Add this URL to your MCP-compatible client (like Claude Desktop)
as a remote MCP server.
</p>
</div>
{/if}
</div>
</div>
<div class="mb-6 flex flex-col gap-3 rounded-md border bg-surface-tertiary p-4">
<div class="flex items-center justify-between gap-2">
<span class="text-sm font-semibold text-emphasis">{displayTitle}</span>
{#if onClose}
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: X }}
aria-label="Close"
title="Close"
onClick={onClose}
/>
{/if}
</div>
<div class="flex flex-col gap-1">
{#if workspaceMcpUrl}
<span class="text-xs font-semibold text-emphasis">Global MCP URL</span>
{/if}
<ClipboardPanel content={mcpUrl ?? token} size="sm" />
{#if mcpUrl}
<p class="text-2xs text-secondary">Add it to your AI client as a remote MCP server.</p>
{/if}
</div>
{#if workspaceMcpUrl}
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">{workspace} MCP URL</span>
<ClipboardPanel content={workspaceMcpUrl} size="sm" />
</div>
{/if}
<Alert type="warning" size="xs" title="Copy it now">
{mcpUrl ? 'The URL holds' : 'This is'} the token, and it is not shown again.
</Alert>
</div>
@@ -6,19 +6,37 @@
import { page } from '$app/state'
import CenteredModal from '$lib/components/CenteredModal.svelte'
import { Badge, Button } from '$lib/components/common'
import Modal from '$lib/components/common/modal/Modal.svelte'
import MultiSelect from '$lib/components/select/MultiSelect.svelte'
import Select from '$lib/components/select/Select.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import McpAccessPicker, { type McpAccess } from '$lib/components/mcp/McpAccessPicker.svelte'
import McpAccessPicker, {
ACCESS_SCOPES,
MCP_SESSION,
RUNNABLES_AS_TOOLS,
mcpAccessOf,
type McpAccess
} from '$lib/components/mcp/McpAccessPicker.svelte'
import McpAccessSection from '$lib/components/mcp/McpAccessSection.svelte'
import McpNotIncludedCard from '$lib/components/mcp/McpNotIncludedCard.svelte'
import McpAccessLine from '$lib/components/mcp/McpAccessLine.svelte'
import {
defaultConnection,
connectionLevel,
givesAnything,
RANK,
servedOn
} from '$lib/components/mcp/workspaceAccess'
import {
McpOauthService,
UserService,
WorkspaceService,
type GetMcpOauthServerClientResponse
type GetMcpOauthServerClientResponse,
type McpWorkspaceAccess
} from '$lib/gen'
import { listEveryWorkspace, parseScopeParam } from '$lib/mcpAuth'
import { parseScopeParam } from '$lib/mcpAuth'
import { sendUserToast } from '$lib/toast'
import { copyToClipboard } from '$lib/utils'
import Pencil from 'lucide-svelte/icons/pencil'
import Copy from 'lucide-svelte/icons/copy'
import Check from 'lucide-svelte/icons/check'
@@ -50,8 +68,17 @@
askedScopes.includes('mcp:read_run')
? askedScopes.filter((s) => s !== 'mcp:read_only' && s !== 'mcp:read_run')
: askedScopes
let scopes = $state<string[]>([])
let access = $state<McpAccess>()
const requestedAccess = mcpAccessOf(requestedScopes)
// What the client asked for, until the user edits the access in the dialog.
let access = $state<McpAccess>(requestedAccess)
let scopes = $state<string[]>(
requestedAccess === 'selected'
? [
...requestedScopes.filter((s) => s !== RUNNABLES_AS_TOOLS && s !== MCP_SESSION),
RUNNABLES_AS_TOOLS
]
: ACCESS_SCOPES[requestedAccess]
)
let oauthState = page.url.searchParams.get('state') || ''
let codeChallenge = page.url.searchParams.get('code_challenge') || ''
let codeChallengeMethod = page.url.searchParams.get('code_challenge_method') || ''
@@ -114,64 +141,169 @@
copied = await copyToClipboard(successRedirectUrl, false)
}
// What the user's role leaves a connection in each of their workspaces.
let workspaceAccess = $state<McpWorkspaceAccess[]>([])
let accessLoadFailed = $state(false)
// Gateway mode: fetch user's workspaces for the picker. One picked workspace binds the
// token to it; several, or all of them, leave it unbound and its tools name their workspace.
let memberWorkspaces: Array<{ value: string; label: string }> = $state([])
const workspaces = $derived(workspaceAccess.map((w) => ({ value: w.id, label: w.name })))
// A superadmin's token reaches only their memberships unless it carries their rights.
let isSuperAdmin = $state(false)
let superAdmin = $state(false)
let everyWorkspace: Array<{ value: string; label: string }> = $state([])
const workspaces = $derived(superAdmin ? everyWorkspace : memberWorkspaces)
let pickedWorkspaces = $state<string[]>([])
let allWorkspaces = $state(false)
let loadingWorkspaces = $state(false)
const grantsWorkspace = $derived(!isGateway || allWorkspaces || pickedWorkspaces.length > 0)
const isTools = (w: McpWorkspaceAccess) => w.access === 'runnables'
// Every workspace gives scripts and flows as tools, so a connection serves one of them, whatever
// "All my workspaces" was left at.
const toolsOnly = $derived(
isGateway &&
workspaceAccess.some(isTools) &&
workspaceAccess.every((w) => isTools(w) || w.access === 'off')
)
const coversAll = $derived(isGateway && allWorkspaces && !toolsOnly)
const grantsWorkspace = $derived(!isGateway || coversAll || pickedWorkspaces.length > 0)
const coveredIds = $derived(isGateway ? pickedWorkspaces : [workspaceId])
const covered = $derived(workspaceAccess.filter((w) => coversAll || coveredIds.includes(w.id)))
const served = $derived(servedOn(covered, coversAll, access))
const bound = $derived(!coversAll && covered.length === 1 ? covered[0] : undefined)
const unavailable = $derived(
!coversAll && served.length > 0 && served.every((w) => !givesAnything(w, access))
)
// A workspace set to tools is picked only on its own, through "Connect it only".
const pickable = $derived(
workspaceAccess.filter((w) => !isTools(w)).map((w) => ({ value: w.id, label: w.name }))
)
// A selection covers one workspace, so a tools workspace can be picked for it too.
const selectable = $derived(
workspaceAccess
.filter((w) => givesAnything(w, 'selected'))
.map((w) => ({ value: w.id, label: w.name }))
)
const toolsAlone = $derived(
isGateway && !toolsOnly && !allWorkspaces && covered.length === 1 && isTools(covered[0])
)
const leftOut = $derived(
isGateway && access !== 'selected'
? workspaceAccess.filter((w) => isTools(w) && !served.includes(w))
: []
)
const shown = $derived(connectionLevel(served, access))
// Limiting offers the highest level the client asked for and the workspaces give, and those
// below it; nothing is left to lower under read only.
const ceiling = $derived(connectionLevel(served, requestedAccess).level)
// A tools workspace connected alone gives what its role offers; there is nothing to lower.
// A selection, asked for or made here, can always be changed.
const editable = $derived(
served.length === 0 ||
requestedAccess === 'selected' ||
access === 'selected' ||
(ceiling !== 'read' && !(bound && isTools(bound)))
)
// One tool list per connection: the level shown, a workspace's role refusing per call what it
// does not allow.
// A connection bound to a workspace whose role offers scripts and flows as tools lists those.
const runnablesHere = $derived(
bound && isTools(bound) && access !== 'selected' && givesAnything(bound, access)
? bound.id
: undefined
)
const connectionTools = $derived(shown.level)
function coverDefault() {
const initial = defaultConnection(workspaceAccess)
allWorkspaces = initial.all
pickedWorkspaces = initial.picked
}
function connectOnly(id: string) {
allWorkspaces = false
pickedWorkspaces = [id]
}
// The access dialog edits the page's own state; closing it any way but Done puts it back.
let editing = $state(false)
let beforeEdit:
| { access: McpAccess; scopes: string[]; all: boolean; picked: string[] }
| undefined
function openEdit() {
beforeEdit = { access, scopes, all: allWorkspaces, picked: pickedWorkspaces }
// The dialog offers the level shown and those below it, so it opens on the level shown.
// The picker starts from `scopes`, so they move down with it.
if (ceiling && access !== 'selected' && RANK[access] > RANK[ceiling]) {
setAccess(ceiling)
scopes = ACCESS_SCOPES[ceiling]
}
editing = true
}
function closeEdit(keep: boolean) {
if (!keep && beforeEdit) {
;({ access, scopes } = beforeEdit)
allWorkspaces = beforeEdit.all
pickedWorkspaces = beforeEdit.picked
}
beforeEdit = undefined
editing = false
}
const selectionMissing = $derived(
access === 'selected' &&
((isGateway && pickedWorkspaces.length === 0) ||
scopes.every((s) => s === RUNNABLES_AS_TOOLS))
)
// Selected scripts and flows are listed per workspace, so a selection keeps one of them.
let beforeSelection: { all: boolean; picked: string[]; held: string | undefined } | undefined
function setAccess(next: McpAccess | undefined) {
access = next
if (next === 'selected') {
if (next === 'selected' && access !== 'selected') {
beforeSelection = access
? { all: allWorkspaces, picked: pickedWorkspaces, held: pickedWorkspaces[0] }
: undefined
allWorkspaces = false
pickedWorkspaces = pickedWorkspaces.slice(0, 1)
} else if (access === 'selected' && next !== 'selected') {
// Back to what was covered, unless the user picked another workspace meanwhile: changing
// the access never widens the workspaces.
if (beforeSelection && pickedWorkspaces[0] === beforeSelection.held) {
allWorkspaces = beforeSelection.all
pickedWorkspaces = beforeSelection.picked
} else if (pickedWorkspaces.length === 0) {
coverDefault()
}
}
access = next
}
// The workspace the scope picker browses scripts and flows in.
const scopeWorkspaceId = $derived(
isGateway ? (pickedWorkspaces[0] ?? (allWorkspaces ? workspaces[0]?.value : '')) : workspaceId
)
if (isGateway) {
async function loadWorkspaceAccess() {
loadingWorkspaces = true
WorkspaceService.listUserWorkspaces()
.then((result) => {
memberWorkspaces = result.workspaces
.filter((w) => !w.disabled)
.map((w) => ({
value: w.id,
label: w.name
}))
// Auto-select if only one workspace
if (memberWorkspaces.length === 1) {
pickedWorkspaces = [memberWorkspaces[0].value]
}
})
.catch((e) => {
// Logged out: the root layout is already sending the browser to the login page.
if (e?.status === 401) return
sendUserToast('Failed to load workspaces', true)
})
.finally(() => {
loadingWorkspaces = false
try {
workspaceAccess = await McpOauthService.listMcpWorkspaceAccess({
superAdmin,
withCounts: true
})
accessLoadFailed = false
} catch (e) {
// Logged out: the root layout is already sending the browser to the login page.
if (e?.status !== 401) accessLoadFailed = true
} finally {
loadingWorkspaces = false
}
}
loadWorkspaceAccess().then(() => {
// A client asking for a selection of scripts and flows is held to one workspace.
if (requestedAccess === 'selected') {
pickedWorkspaces = workspaceAccess.length === 1 ? [workspaceAccess[0].id] : []
} else {
coverDefault()
}
})
UserService.globalWhoami()
.then((me) => (isSuperAdmin = me.super_admin))
.catch(() => {})
async function setSuperAdmin(on: boolean) {
superAdmin = on
if (on && isGateway) {
everyWorkspace = (await listEveryWorkspace()).map((w) => ({ value: w.id, label: w.name }))
}
await loadWorkspaceAccess()
const offered = new Set(workspaces.map((w) => w.value))
pickedWorkspaces = pickedWorkspaces.filter((w) => offered.has(w))
}
@@ -215,8 +347,8 @@
// Gateway mode sends the workspaces in the body
if (isGateway) {
body.workspace_ids = allWorkspaces ? [] : pickedWorkspaces
body.all_workspaces = allWorkspaces
body.workspace_ids = coversAll ? [] : pickedWorkspaces
body.all_workspaces = coversAll
}
const response = await fetch(approveUrl, {
@@ -254,9 +386,8 @@
{#if !redirectUriValid}
<CenteredModal title="Authorization Request">
<p class="text-center text-sm text-primary break-all">
This client's redirect URI {redirectUri} cannot receive the authorization: it must be an
http(s) or app URL outside this instance's /api path. Register the client with its own
callback URL.
This client's redirect URI {redirectUri} cannot receive the authorization: it must be an http(s)
or app URL outside this instance's /api path. Register the client with its own callback URL.
</p>
</CenteredModal>
{:else if clientLookupFailed || (client && !redirectRegistered)}
@@ -351,18 +482,49 @@
{#if isGateway}
<div class="mb-6 flex flex-col gap-2">
<p class="text-xs font-semibold text-emphasis">
{access === 'selected'
? 'Workspace of its scripts and flows:'
: 'Workspaces it may work in:'}
{access === 'selected' || toolsOnly || toolsAlone ? 'Workspace' : 'Workspaces'}
</p>
{#if loadingWorkspaces}
<p class="text-xs text-secondary">Loading workspaces...</p>
{:else if accessLoadFailed}
<p class="text-xs text-red-600 dark:text-red-400">
Your workspaces could not be loaded. Reload this page.
</p>
{:else if access === 'selected'}
<p class="text-xs text-primary">
{pickedWorkspaces[0] ?? 'None yet'}
</p>
<p class="text-2xs text-secondary">
The workspace of its scripts and flows. Change it with the access.
</p>
{:else if toolsOnly}
<Select
items={workspaces}
bind:value={() => pickedWorkspaces[0], (v) => (pickedWorkspaces = v ? [v] : [])}
items={workspaceAccess.filter(isTools).map((w) => ({ value: w.id, label: w.name }))}
bind:value={
() => pickedWorkspaces[0],
(v) => {
allWorkspaces = false
pickedWorkspaces = v ? [v] : []
}
}
placeholder="Choose a workspace"
/>
<p class="text-2xs text-secondary">
Your role lets you connect scripts and flows as tools, one workspace per connection.
</p>
{:else if toolsAlone}
<div class="flex items-center gap-1.5">
<p class="text-xs text-primary">{covered[0].name}</p>
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: Pencil }}
aria-label="Change workspaces"
title="Change workspaces"
onClick={coverDefault}
/>
</div>
{:else}
<Toggle
bind:checked={allWorkspaces}
@@ -379,56 +541,142 @@
</p>
{:else if !allWorkspaces}
<MultiSelect
items={workspaces}
items={pickable}
bind:value={pickedWorkspaces}
placeholder="Choose workspaces"
reorderable={false}
/>
{#if pickedWorkspaces.length === 0}
<p class="text-2xs text-secondary">Choose at least one workspace.</p>
{/if}
{/if}
{/if}
{#if isSuperAdmin && !superAdmin && (access === 'selected' || !allWorkspaces)}
{#if isSuperAdmin && !superAdmin && !allWorkspaces}
<p class="text-xs text-tertiary">
Showing workspaces you are a member of. Superadmin rights, under Access, opens the
rest.
Showing workspaces you are a member of. Superadmin rights opens the rest.
</p>
{/if}
{#if leftOut.length > 0}
<McpNotIncludedCard
workspaces={leftOut}
onTheirOwn={toolsOnly}
readOnly={access === 'read'}
showUrl
onSelect={connectOnly}
/>
{/if}
</div>
{/if}
<div class="mb-6 flex flex-col gap-1">
{#if accessLoadFailed && !isGateway}
<p class="mb-6 text-xs text-red-600 dark:text-red-400">
Your access could not be loaded. Reload this page.
</p>
{/if}
{#if isSuperAdmin}
<div class="mb-6">
<Toggle
bind:checked={() => superAdmin, setSuperAdmin}
disabled={loadingWorkspaces}
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"
/>
</div>
{/if}
{#snippet pen()}
{#if editable}
<Button
variant="subtle"
unifiedSize="xs"
iconOnly
startIcon={{ icon: Pencil }}
aria-label="Limit access"
title="Limit access"
disabled={loadingWorkspaces}
onClick={openEdit}
/>
{/if}
{/snippet}
{#if !loadingWorkspaces && (served.length > 0 || access === 'selected')}
<div class="mb-6">
<McpAccessSection tools={{ level: connectionTools, workspace: runnablesHere }}>
{#if served.length > 0}
<McpAccessLine labelled workspaces={served} {access} edit={pen} />
{:else}
<div class="flex items-center gap-1.5">
<p class="text-xs text-primary">
Scripts and flows as tools. Choose the workspace and its scripts and flows.
</p>
{@render pen()}
</div>
{/if}
</McpAccessSection>
</div>
{/if}
<Modal
title="Limit access"
enterConfirms={false}
bind:open={() => editing, (v) => (v ? (editing = true) : closeEdit(false))}
>
<McpAccessPicker
workspaceId={scopeWorkspaceId ?? ''}
workspaces={isGateway
? allWorkspaces
? memberWorkspaces.map((w) => w.value)
: pickedWorkspaces
: [workspaceId]}
initialScopes={requestedScopes}
max={ceiling}
initialScopes={scopes}
bind:scopes
bind:access={() => access, setAccess}
>
{#snippet belowAccess()}
{#if !bound && access === 'read_run'}
<p class="text-2xs text-secondary">
In each workspace, the client can do at most what your role allows there.
</p>
{/if}
{/snippet}
{#snippet afterAccess()}
{#if isSuperAdmin}
<Toggle
bind:checked={() => 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 access === 'selected' && isGateway}
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">Workspace</span>
<Select
items={selectable}
bind:value={() => pickedWorkspaces[0], (v) => (pickedWorkspaces = v ? [v] : [])}
placeholder="Choose a workspace"
/>
</div>
{/if}
{/snippet}
</McpAccessPicker>
</div>
{#snippet actions()}
<Button
variant="accent"
unifiedSize="sm"
disabled={selectionMissing}
onClick={() => closeEdit(true)}
>
Done
</Button>
{/snippet}
</Modal>
<div class="flex flex-row justify-around gap-x-4">
<Button variant="default" unifiedSize="lg" disabled={loading} onClick={onDeny}>Deny</Button>
<Button
variant="accent"
unifiedSize="lg"
disabled={loading || !grantsWorkspace || scopes.length === 0}
disabled={loading ||
loadingWorkspaces ||
accessLoadFailed ||
!grantsWorkspace ||
unavailable ||
(isGateway && !coversAll && served.length === 0) ||
selectionMissing ||
scopes.length === 0}
{loading}
onClick={onApprove}>Approve</Button
>