mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-12-03 16:10:37 +00:00
feat: cap mcp access per workspace role
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
047e1530c0
commit
6e81c227e2
+28
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT workspace_id, role_overrides FROM workspace_settings\n WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "workspace_id",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "role_overrides",
|
||||
"type_info": "Jsonb"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"TextArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "2b95dc313f255a63c19cf48a0e8806bbf2e9c126bbe65384e72a47260e4eb7d4"
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT DISTINCT workspace_id FROM workspace_protection_rule\n WHERE workspace_id = ANY($1) AND rules & $2 <> 0",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "workspace_id",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"TextArray",
|
||||
"Int4"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "9ad042a9c1a1dc7f2ddeeccbffb560e27093ac7fc54b14070debe9155cb9f04f"
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT workspace_id, is_admin, operator, workspace_role FROM usr\n WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "workspace_id",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 1,
|
||||
"name": "is_admin",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "operator",
|
||||
"type_info": "Bool"
|
||||
},
|
||||
{
|
||||
"ordinal": 3,
|
||||
"name": "workspace_role",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Text",
|
||||
"TextArray"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "cc2d27c55c3dac7b0f287b56c66ec1ee8856df25ebe62074bb1628ee7f39415b"
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! A role's MCP setting is a maximum for every connection of its members, whatever their token
|
||||
//! grants and whichever MCP URL they use, and an MCP token reaches nothing but MCP.
|
||||
#![cfg(feature = "mcp")]
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use sqlx::{Pool, Postgres};
|
||||
use windmill_test_utils::*;
|
||||
|
||||
async fn mcp(port: u16, path: &str, token: &str, method: &str, params: Value) -> Value {
|
||||
let body = reqwest::Client::new()
|
||||
.post(format!("http://localhost:{port}{path}"))
|
||||
.bearer_auth(token)
|
||||
.header("accept", "application/json, text/event-stream")
|
||||
.header("mcp-protocol-version", "2025-06-18")
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap()
|
||||
.text()
|
||||
.await
|
||||
.unwrap();
|
||||
let data = body
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("data: "))
|
||||
.unwrap_or(&body);
|
||||
serde_json::from_str(data).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
async fn tools(port: u16, path: &str, token: &str) -> Vec<String> {
|
||||
let list = mcp(port, path, token, "tools/list", json!({})).await;
|
||||
list["result"]["tools"]
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("no tools in {list}"))
|
||||
.iter()
|
||||
.filter_map(|t| t["name"].as_str().map(str::to_string))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
async fn set_access(db: &Pool<Postgres>, mcp: Value) {
|
||||
sqlx::query(
|
||||
"UPDATE workspace_settings SET role_overrides = $1 WHERE workspace_id = 'test-workspace'",
|
||||
)
|
||||
.bind(json!({"developer": {"mcp": mcp}}))
|
||||
.execute(db)
|
||||
.await
|
||||
.unwrap();
|
||||
windmill_common::roles::invalidate_workspace_roles_cache("test-workspace");
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
const WORKSPACE: &str = "/api/mcp/w/test-workspace/mcp";
|
||||
const DEFAULT: &str = "/api/mcp";
|
||||
#[cfg(feature = "enterprise")]
|
||||
const GATEWAY: &str = "/api/mcp/gateway";
|
||||
|
||||
async fn token(db: &Pool<Postgres>, name: &str, email: &str, scopes: &[&str], bound: bool) {
|
||||
sqlx::query(
|
||||
"INSERT INTO token (token_hash, token_prefix, email, label, super_admin, scopes, workspace_id)
|
||||
VALUES (encode(sha256($1::text::bytea), 'hex'), left($1::text, 10), $2, 'mcp', false, $3, $4)",
|
||||
)
|
||||
.bind(name)
|
||||
.bind(email)
|
||||
.bind(scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>())
|
||||
.bind(bound.then_some("test-workspace"))
|
||||
.execute(db)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[cfg(feature = "enterprise")]
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn role_setting_caps_every_token(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
sqlx::raw_sql(
|
||||
"INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES
|
||||
('test-workspace', 'test-user', 'export function main() { return 1 }', '{}', '', '', 'u/test-user/in_set', 7788401, 'bun', ''),
|
||||
('test-workspace', 'test-user', 'export function main() { return 1 }', '{}', '', '', 'u/test-user/outside', 7788402, 'bun', '');",
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
// test-user is a workspace admin: the setting of the role they hold applies to them too.
|
||||
let admin = "test@windmill.dev";
|
||||
token(&db, "ROLEPLAIN_TOKEN", admin, &["mcp:all"], true).await;
|
||||
token(
|
||||
&db,
|
||||
"ROLESESS_TOKEN",
|
||||
admin,
|
||||
&["mcp:all", "mcp:session"],
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
token(&db, "ROLEUNBOUND_TOKEN", admin, &["mcp:all"], false).await;
|
||||
token(
|
||||
&db,
|
||||
"ROLEREAD_TOKEN",
|
||||
admin,
|
||||
&["mcp:all", "mcp:read_only"],
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
token(
|
||||
&db,
|
||||
"ROLESEL_TOKEN",
|
||||
admin,
|
||||
&["mcp:scripts:u/test-user/outside"],
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
|
||||
let server = ApiServer::start_mcp(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
let has = |tools: &[String], name: &str| tools.iter().any(|t| t == name);
|
||||
|
||||
let before = tools(port, WORKSPACE, "ROLEPLAIN_TOKEN").await;
|
||||
assert!(has(&before, "listJobs"), "unconfigured: {before:?}");
|
||||
assert!(has(
|
||||
&tools(port, WORKSPACE, "ROLESEL_TOKEN").await,
|
||||
"outside"
|
||||
));
|
||||
|
||||
set_access(
|
||||
&db,
|
||||
json!({"access": "runnables", "scripts": ["u/test-user/in_set"]}),
|
||||
)
|
||||
.await;
|
||||
for t in ["ROLEPLAIN_TOKEN", "ROLESESS_TOKEN"] {
|
||||
for url in [WORKSPACE, DEFAULT, GATEWAY] {
|
||||
assert_eq!(tools(port, url, t).await, ["in_set"], "{t} {url}");
|
||||
}
|
||||
}
|
||||
assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty());
|
||||
assert!(tools(port, WORKSPACE, "ROLEREAD_TOKEN").await.is_empty());
|
||||
let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move {
|
||||
mcp(
|
||||
port,
|
||||
url,
|
||||
token,
|
||||
"tools/call",
|
||||
json!({"name": name, "arguments": args}),
|
||||
)
|
||||
.await
|
||||
};
|
||||
for (name, refused) in [
|
||||
("outside", "outside this token's selection"),
|
||||
("listJobs", ""),
|
||||
] {
|
||||
let out = call(WORKSPACE, "ROLESESS_TOKEN", name, json!({})).await;
|
||||
let msg = out["error"]["message"].as_str().unwrap_or_default();
|
||||
assert!(!msg.is_empty() && msg.contains(refused), "{name}: {out}");
|
||||
}
|
||||
let ws = json!({"workspace_id": "test-workspace"});
|
||||
for (url, name) in [(DEFAULT, "list_workspace_items"), (GATEWAY, "listJobs")] {
|
||||
let out = call(url, "ROLEUNBOUND_TOKEN", name, ws.clone()).await;
|
||||
let msg = out["error"]["message"].as_str().unwrap_or_default();
|
||||
assert!(
|
||||
msg.contains("/api/mcp/w/test-workspace/mcp"),
|
||||
"{name}: {out}"
|
||||
);
|
||||
}
|
||||
|
||||
set_access(&db, json!({"access": "read_only"})).await;
|
||||
for url in [WORKSPACE, DEFAULT, GATEWAY] {
|
||||
let t = tools(port, url, "ROLEPLAIN_TOKEN").await;
|
||||
assert!(has(&t, "list_workspace_items"), "{url}: {t:?}");
|
||||
assert!(
|
||||
!has(&t, "listJobs") && !has(&t, "run_script"),
|
||||
"{url}: {t:?}"
|
||||
);
|
||||
}
|
||||
assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty());
|
||||
let out = call(
|
||||
DEFAULT,
|
||||
"ROLEUNBOUND_TOKEN",
|
||||
"run_script",
|
||||
json!({"workspace_id": "test-workspace", "path": "u/test-user/in_set", "args": {}}),
|
||||
)
|
||||
.await;
|
||||
assert!(
|
||||
out["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("read-only")),
|
||||
"{out}"
|
||||
);
|
||||
let out = call(DEFAULT, "ROLEUNBOUND_TOKEN", "list_workspaces", json!({})).await;
|
||||
assert!(out["result"].to_string().contains("read only"), "{out}");
|
||||
|
||||
set_access(&db, json!({"access": "off"})).await;
|
||||
assert!(tools(port, WORKSPACE, "ROLESEL_TOKEN").await.is_empty());
|
||||
assert_eq!(
|
||||
tools(port, DEFAULT, "ROLESESS_TOKEN").await,
|
||||
["list_workspaces"]
|
||||
);
|
||||
let out = call(DEFAULT, "ROLESESS_TOKEN", "list_workspace_items", ws).await;
|
||||
assert!(
|
||||
out["error"]["message"]
|
||||
.as_str()
|
||||
.is_some_and(|m| m.contains("no MCP access")),
|
||||
"{out}"
|
||||
);
|
||||
|
||||
// A role nothing defines any more fails closed where a setting exists.
|
||||
set_access(&db, json!({"access": "read_run"})).await;
|
||||
sqlx::query("UPDATE usr SET workspace_role = 'gone' WHERE workspace_id = 'test-workspace' AND username = 'test-user'")
|
||||
.execute(&db)
|
||||
.await?;
|
||||
windmill_common::roles::invalidate_member_role_cache("test-workspace", "test-user");
|
||||
assert_eq!(
|
||||
tools(port, DEFAULT, "ROLESESS_TOKEN").await,
|
||||
["list_workspaces"]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[sqlx::test(fixtures("base"))]
|
||||
async fn mcp_tokens_reach_mcp_alone(db: Pool<Postgres>) -> anyhow::Result<()> {
|
||||
initialize_tracing().await;
|
||||
token(
|
||||
&db,
|
||||
"MCPONLY_TOKEN",
|
||||
"test@windmill.dev",
|
||||
&["mcp:all", "mcp:session"],
|
||||
true,
|
||||
)
|
||||
.await;
|
||||
let server = ApiServer::start_mcp(db.clone()).await?;
|
||||
let port = server.addr.port();
|
||||
let list = mcp(port, DEFAULT, "MCPONLY_TOKEN", "tools/list", json!({})).await;
|
||||
assert!(list["result"]["tools"].is_array(), "{list}");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
for route in [
|
||||
"w/test-workspace/scripts/list",
|
||||
"w/test-workspace/jobs/list",
|
||||
"w/test-workspace/variables/list",
|
||||
] {
|
||||
let status = client
|
||||
.get(format!("http://localhost:{port}/api/{route}"))
|
||||
.bearer_auth("MCPONLY_TOKEN")
|
||||
.send()
|
||||
.await?
|
||||
.status();
|
||||
assert_eq!(status, 403, "{route}");
|
||||
}
|
||||
|
||||
for (scopes, ok) in [
|
||||
(vec!["mcp:all", "scripts:read"], false),
|
||||
(vec!["mcp:all", "if_jobs:filter_tags:deno"], true),
|
||||
] {
|
||||
let status = client
|
||||
.post(format!("http://localhost:{port}/api/users/tokens/create"))
|
||||
.bearer_auth("SECRET_TOKEN")
|
||||
.json(&json!({"label": "mixed", "scopes": scopes}))
|
||||
.send()
|
||||
.await?
|
||||
.status();
|
||||
assert_eq!(status.is_success(), ok, "{scopes:?}: {status}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -638,6 +638,27 @@ pub fn ensure_scopes_within_caller(
|
||||
ensure_scopes_within(authed.scopes.as_deref(), requested_scopes)
|
||||
}
|
||||
|
||||
/// Whether scopes mix MCP access with access to the regular API. The job tag fence narrows both.
|
||||
pub fn mixes_mcp_scopes(scopes: Option<&[String]>) -> bool {
|
||||
let mut scopes = scopes
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter(|s| !s.starts_with("if_jobs:filter_tags:"))
|
||||
.map(|s| s.starts_with("mcp:"));
|
||||
scopes.next().is_some_and(|first| scopes.any(|s| s != first))
|
||||
}
|
||||
|
||||
/// Refuses giving a token MCP scopes next to regular ones: an MCP token calls tools only, and a
|
||||
/// regular scope on it opens routes its MCP access level does not limit.
|
||||
pub fn ensure_mcp_scopes_unmixed(scopes: Option<&[String]>) -> error::Result<()> {
|
||||
if mixes_mcp_scopes(scopes) {
|
||||
return Err(Error::BadRequest(
|
||||
"a token cannot mix MCP scopes with other scopes: create a token for each".to_string(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a credential holding `holder_scopes` covers `requested_scopes`, by the rules of
|
||||
/// [`ensure_scopes_within_caller`].
|
||||
pub fn ensure_scopes_within(
|
||||
|
||||
@@ -3613,6 +3613,7 @@ async fn create_token(
|
||||
token_config.admin = Some(token_config.admin.unwrap_or(false));
|
||||
|
||||
windmill_api_auth::ensure_scopes_within_caller(&authed, token_config.scopes.as_deref())?;
|
||||
windmill_api_auth::ensure_mcp_scopes_unmixed(token_config.scopes.as_deref())?;
|
||||
// Mirrors the MCP OAuth approve: a scoped token cannot mint superadmin access it may lack.
|
||||
if token_config.super_admin == Some(true)
|
||||
&& authed
|
||||
@@ -4593,6 +4594,10 @@ async fn update_token_scopes(
|
||||
"token {token_prefix} not found, not owned by user, or not rescopable"
|
||||
)));
|
||||
}
|
||||
// A token that mixes them already stays editable.
|
||||
if !windmill_api_auth::mixes_mcp_scopes(token.scopes.as_deref()) {
|
||||
windmill_api_auth::ensure_mcp_scopes_unmixed(req.scopes.as_deref())?;
|
||||
}
|
||||
let widens =
|
||||
windmill_api_auth::ensure_scopes_within(token.scopes.as_deref(), req.scopes.as_deref())
|
||||
.is_err();
|
||||
|
||||
@@ -91,11 +91,8 @@ pub(crate) async fn write_role_overrides(
|
||||
) -> Result<()> {
|
||||
let instance = instance_roles(db).await?;
|
||||
roles::validate_overrides(&instance, &overrides)?;
|
||||
roles::check_frozen_overrides(
|
||||
&instance,
|
||||
&roles::load_role_overrides(db, w_id).await?,
|
||||
&overrides,
|
||||
)?;
|
||||
let previous_overrides = load_role_overrides(db, w_id).await?;
|
||||
roles::check_frozen_overrides(&instance, &previous_overrides, &overrides)?;
|
||||
|
||||
let previous = roles::workspace_roles(db, w_id).await?;
|
||||
let removed: Vec<String> = previous
|
||||
@@ -161,6 +158,21 @@ pub(crate) async fn write_role_overrides(
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
roles::invalidate_workspace_roles_cache(w_id);
|
||||
roles::log_mcp_role_changes(
|
||||
previous_overrides
|
||||
.keys()
|
||||
.chain(
|
||||
overrides
|
||||
.keys()
|
||||
.filter(|n| !previous_overrides.contains_key(*n)),
|
||||
)
|
||||
.map(|n| {
|
||||
(
|
||||
previous_overrides.get(n).and_then(|o| o.mcp.as_ref()),
|
||||
overrides.get(n).and_then(|o| o.mcp.as_ref()),
|
||||
)
|
||||
}),
|
||||
);
|
||||
|
||||
handle_deployment_metadata(
|
||||
&authed.email,
|
||||
@@ -280,7 +292,7 @@ pub(crate) async fn update_operator_settings(
|
||||
|
||||
let entry = overrides.entry(OPERATOR_ROLE.to_string()).or_default();
|
||||
entry.capabilities = roles::diff_capabilities(&base, &target);
|
||||
if entry.label.is_none() && entry.capabilities == Default::default() {
|
||||
if *entry == Default::default() {
|
||||
overrides.remove(OPERATOR_ROLE);
|
||||
}
|
||||
|
||||
|
||||
@@ -42187,6 +42187,26 @@ components:
|
||||
additionalProperties:
|
||||
type: boolean
|
||||
|
||||
McpRoleSetting:
|
||||
type: object
|
||||
description: The most a role's members may do through MCP, whatever their token grants (EE). Unset falls through to the layer below.
|
||||
properties:
|
||||
access:
|
||||
type: string
|
||||
enum: [follow_role, read_run, read_only, runnables, "off"]
|
||||
description: "`follow_role` sets no limit, and lifts the instance's when a workspace states it. `runnables` offers the listed scripts and flows as tools and nothing else."
|
||||
scripts:
|
||||
type: array
|
||||
description: With `runnables`, script paths, `*` or an exact path or a `<prefix>/*` subtree.
|
||||
items:
|
||||
type: string
|
||||
flows:
|
||||
type: array
|
||||
description: With `runnables`, flow paths, as for scripts.
|
||||
items:
|
||||
type: string
|
||||
required: [access]
|
||||
|
||||
RoleDefinition:
|
||||
type: object
|
||||
description: One entry of the `workspace_roles` instance setting.
|
||||
@@ -42197,6 +42217,8 @@ components:
|
||||
type: string
|
||||
capabilities:
|
||||
$ref: "#/components/schemas/RoleCapabilitiesPatch"
|
||||
mcp:
|
||||
$ref: "#/components/schemas/McpRoleSetting"
|
||||
required: [name]
|
||||
|
||||
RoleOverride:
|
||||
@@ -42206,6 +42228,8 @@ components:
|
||||
type: string
|
||||
capabilities:
|
||||
$ref: "#/components/schemas/RoleCapabilitiesPatch"
|
||||
mcp:
|
||||
$ref: "#/components/schemas/McpRoleSetting"
|
||||
|
||||
RoleOverrides:
|
||||
type: object
|
||||
@@ -42222,6 +42246,8 @@ components:
|
||||
type: string
|
||||
capabilities:
|
||||
$ref: "#/components/schemas/RoleCapabilities"
|
||||
mcp:
|
||||
$ref: "#/components/schemas/McpRoleSetting"
|
||||
source:
|
||||
type: string
|
||||
enum: [instance, workspace]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -14,8 +14,8 @@ use windmill_mcp::common::types::{
|
||||
FlowInfo, HubScriptInfo, ResourceInfo, ResourceType, SchemaType, ScriptInfo, WorkspaceInfo,
|
||||
};
|
||||
use windmill_mcp::server::{
|
||||
BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend, McpRequest, PathFilter,
|
||||
RunOutcome, SessionAccess, Tool,
|
||||
admits, session_limit, BackendResult, CallToolResult, EndpointTool, ErrorData, McpBackend,
|
||||
McpLimit, McpRequest, PathFilter, RunOutcome, SessionAccess, Tool,
|
||||
};
|
||||
|
||||
use crate::auth::{AuthCache, Tokened};
|
||||
@@ -92,7 +92,11 @@ impl WindmillBackend {
|
||||
auth: &'a ApiAuthed,
|
||||
w_id: &'a str,
|
||||
access: SessionAccess,
|
||||
) -> session::Ctx<'a> {
|
||||
) -> BackendResult<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();
|
||||
@@ -109,7 +113,12 @@ impl WindmillBackend {
|
||||
} else {
|
||||
access
|
||||
};
|
||||
session::Ctx::new(auth, w_id, &self.base_internal_url, session::access(access))
|
||||
Ok(session::Ctx::new(
|
||||
auth,
|
||||
w_id,
|
||||
&self.base_internal_url,
|
||||
session::access(access),
|
||||
))
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
@@ -550,13 +559,30 @@ impl McpBackend for WindmillBackend {
|
||||
all_tools()
|
||||
}
|
||||
|
||||
async fn mcp_limit(
|
||||
&self,
|
||||
auth: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
) -> BackendResult<Option<McpLimit>> {
|
||||
super::role_access::mcp_limit(&self.db, auth, workspace_id).await
|
||||
}
|
||||
|
||||
async fn workspace_accesses(
|
||||
&self,
|
||||
auth: &ApiAuthed,
|
||||
workspaces: &[WorkspaceInfo],
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<HashMap<String, &'static str>> {
|
||||
super::role_access::workspace_accesses(&self.db, &auth.email, workspaces, access).await
|
||||
}
|
||||
|
||||
async fn session_instructions(
|
||||
&self,
|
||||
auth: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<String> {
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await?;
|
||||
let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await;
|
||||
Ok(session::session_instructions(&ctx, &profile).await)
|
||||
}
|
||||
@@ -570,10 +596,10 @@ impl McpBackend for WindmillBackend {
|
||||
auth: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> String {
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
) -> BackendResult<String> {
|
||||
let ctx = self.session_ctx_with(auth, workspace_id, access).await?;
|
||||
let profile = session::prompt_profile(&self.db, auth, workspace_id, ctx.access).await;
|
||||
session::workspace_context(&ctx, &profile, session::access(access)).await
|
||||
Ok(session::workspace_context(&ctx, &profile, session::access(access)).await)
|
||||
}
|
||||
|
||||
fn session_tools(&self, access: SessionAccess) -> Vec<Tool> {
|
||||
@@ -593,7 +619,7 @@ impl McpBackend for WindmillBackend {
|
||||
access: SessionAccess,
|
||||
origin: Option<&str>,
|
||||
) -> BackendResult<CallToolResult> {
|
||||
let mut ctx = self.session_ctx_with(auth, workspace_id, access).await;
|
||||
let mut ctx = self.session_ctx_with(auth, workspace_id, access).await?;
|
||||
ctx.origin = origin;
|
||||
session::call_session_tool(&ctx, name, args).await
|
||||
}
|
||||
@@ -621,6 +647,40 @@ fn serves_session_toolset(scopes: &[String]) -> bool {
|
||||
.any(|scope| [SESSION_SCOPE, "mcp:read_only", "mcp:read_run"].contains(&scope.as_str()))
|
||||
}
|
||||
|
||||
/// Whether the session server answers a request to one workspace, given what its URL and token
|
||||
/// say (`session`) and its member's role: a role limited to chosen scripts and flows is served
|
||||
/// them by the tools server whatever the token, and an `mcp:all` token under any other limit the
|
||||
/// session toolset, as endpoint tools are never served under one.
|
||||
async fn served_under_limit(
|
||||
db: &DB,
|
||||
extensions: &http::Extensions,
|
||||
session: bool,
|
||||
) -> Result<bool, Response> {
|
||||
let (Some(WorkspaceId(w_id)), Some(authed)) = (
|
||||
extensions.get::<WorkspaceId>(),
|
||||
extensions.get::<ApiAuthed>(),
|
||||
) else {
|
||||
return Ok(session);
|
||||
};
|
||||
let limit = super::role_access::mcp_limit(db, authed, w_id)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
e.message.into_owned(),
|
||||
)
|
||||
.into_response()
|
||||
})?;
|
||||
Ok(match limit {
|
||||
None => session,
|
||||
Some(McpLimit::Runnables { .. }) => false,
|
||||
Some(_) => {
|
||||
let scopes = authed.scopes.as_deref().unwrap_or_default();
|
||||
session || admits(scopes, scopes.iter().any(|s| s == "mcp:all"))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of a workspace-less MCP URL, when it is not the tools server's
|
||||
/// `/api/mcp/gateway`: each URL is its own OAuth protected resource.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -856,7 +916,7 @@ pub async fn setup_mcp_server(
|
||||
let cancellation_token = CancellationToken::new();
|
||||
let session_manager = Arc::new(LocalSessionManager::default());
|
||||
|
||||
let backend = WindmillBackend::new(db, user_db, base_internal_url, auth_cache);
|
||||
let backend = WindmillBackend::new(db.clone(), user_db, base_internal_url, auth_cache);
|
||||
let session_runner = SessionRunner::new(backend.clone());
|
||||
let runner = Runner::new(backend);
|
||||
|
||||
@@ -891,13 +951,20 @@ pub async fn setup_mcp_server(
|
||||
"/",
|
||||
axum::routing::any({
|
||||
let (service, session_service) = (service.clone(), session_service.clone());
|
||||
let db = db.clone();
|
||||
move |request: Request<axum::body::Body>| {
|
||||
let (service, session_service) = (service.clone(), session_service.clone());
|
||||
let db = db.clone();
|
||||
async move {
|
||||
use tower::ServiceExt;
|
||||
let session = request.extensions().get::<ApiAuthed>().is_some_and(|a| {
|
||||
serves_session_toolset(a.scopes.as_deref().unwrap_or_default())
|
||||
});
|
||||
let session = match served_under_limit(&db, request.extensions(), session).await
|
||||
{
|
||||
Ok(session) => session,
|
||||
Err(refused) => return refused,
|
||||
};
|
||||
let response = if session {
|
||||
session_service.oneshot(request).await
|
||||
} else {
|
||||
@@ -918,9 +985,15 @@ pub async fn setup_mcp_server(
|
||||
"/mcp",
|
||||
axum::routing::any(move |mut request: Request<axum::body::Body>| {
|
||||
let (service, session_service) = (service.clone(), session_service.clone());
|
||||
let db = db.clone();
|
||||
async move {
|
||||
use tower::ServiceExt;
|
||||
let response = if request.extensions().get::<McpSelection>().is_some() {
|
||||
let session = request.extensions().get::<McpSelection>().is_none();
|
||||
let session = match served_under_limit(&db, request.extensions(), session).await {
|
||||
Ok(session) => session,
|
||||
Err(refused) => return refused,
|
||||
};
|
||||
let response = if !session {
|
||||
request.extensions_mut().insert(NoEndpointTools);
|
||||
service.oneshot(request).await
|
||||
} else {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
mod auto_generated_endpoints;
|
||||
mod core;
|
||||
pub mod external_idp;
|
||||
mod role_access;
|
||||
mod session;
|
||||
mod utils;
|
||||
|
||||
|
||||
@@ -981,6 +981,7 @@ async fn oauth_approve_inner(
|
||||
if scopes.iter().any(|s| s == "mcp:all") && !scopes.iter().any(|s| s == SESSION_SCOPE) {
|
||||
scopes.push(SESSION_SCOPE.to_string());
|
||||
}
|
||||
windmill_api_auth::ensure_mcp_scopes_unmixed(Some(&scopes))?;
|
||||
|
||||
// The approver's own token bounds what it may grant: a scope-restricted MCP
|
||||
// token must not approve a broader one (e.g. mcp:scripts:f/x -> mcp:all). An
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! What a member's workspace role lets an MCP connection do. See `roles::McpRoleSetting`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use windmill_api_auth::ApiAuthed;
|
||||
use windmill_common::{
|
||||
roles::{self, McpRoleAccess, McpRoleSetting, RoleCapabilities},
|
||||
workspaces::ProtectionRules,
|
||||
DB,
|
||||
};
|
||||
use windmill_mcp::server::{BackendResult, ErrorData, McpLimit, SessionAccess, WorkspaceInfo};
|
||||
|
||||
fn limit_of(setting: &McpRoleSetting) -> Option<McpLimit> {
|
||||
match setting.access {
|
||||
McpRoleAccess::FollowRole => None,
|
||||
McpRoleAccess::ReadRun => Some(McpLimit::ReadAndRun),
|
||||
McpRoleAccess::ReadOnly => Some(McpLimit::ReadOnly),
|
||||
McpRoleAccess::Runnables => Some(McpLimit::Runnables {
|
||||
scripts: setting.scripts.clone(),
|
||||
flows: setting.flows.clone(),
|
||||
}),
|
||||
McpRoleAccess::Off => Some(McpLimit::Off),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuses on an error, unlike `can_run`: an unread limit is one the admin still relies on.
|
||||
pub(super) async fn mcp_limit(
|
||||
db: &DB,
|
||||
authed: &ApiAuthed,
|
||||
workspace_id: &str,
|
||||
) -> BackendResult<Option<McpLimit>> {
|
||||
roles::caller_mcp_limit(db, workspace_id, authed)
|
||||
.await
|
||||
.map(|s| s.as_ref().and_then(limit_of))
|
||||
.map_err(|e| {
|
||||
tracing::error!("reading the MCP access of a role in {workspace_id}: {e:#}");
|
||||
ErrorData::internal_error(
|
||||
format!(
|
||||
"The MCP access of your role in '{workspace_id}' could not be read. Try again."
|
||||
),
|
||||
None,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// What a connection with `access` gets in each workspace, in three queries however many there
|
||||
/// are. Community, where no role limits anything, queries nothing and lists none.
|
||||
pub(super) async fn workspace_accesses(
|
||||
db: &DB,
|
||||
email: &str,
|
||||
workspaces: &[WorkspaceInfo],
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<HashMap<String, &'static str>> {
|
||||
if !cfg!(feature = "enterprise") {
|
||||
return Ok(HashMap::new());
|
||||
}
|
||||
accesses(db, email, workspaces, access)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.to_string(), None))
|
||||
}
|
||||
|
||||
async fn accesses(
|
||||
db: &DB,
|
||||
email: &str,
|
||||
workspaces: &[WorkspaceInfo],
|
||||
access: SessionAccess,
|
||||
) -> windmill_common::error::Result<HashMap<String, &'static str>> {
|
||||
let ids: Vec<String> = workspaces.iter().map(|w| w.id.clone()).collect();
|
||||
let members = sqlx::query!(
|
||||
"SELECT workspace_id, is_admin, operator, workspace_role FROM usr
|
||||
WHERE email = $1 AND workspace_id = ANY($2) AND disabled = false",
|
||||
email,
|
||||
&ids
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let mut overrides: HashMap<String, roles::RoleOverrides> = sqlx::query!(
|
||||
"SELECT workspace_id, role_overrides FROM workspace_settings
|
||||
WHERE workspace_id = ANY($1) AND role_overrides IS NOT NULL",
|
||||
&ids
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
Some((
|
||||
r.workspace_id,
|
||||
serde_json::from_value(r.role_overrides?).ok()?,
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
let locked: Vec<String> = sqlx::query_scalar!(
|
||||
"SELECT DISTINCT workspace_id FROM workspace_protection_rule
|
||||
WHERE workspace_id = ANY($1) AND rules & $2 <> 0",
|
||||
&ids,
|
||||
ProtectionRules::DISABLE_DIRECT_DEPLOYMENT.bits()
|
||||
)
|
||||
.fetch_all(db)
|
||||
.await?;
|
||||
let instance = roles::instance_roles(db).await?;
|
||||
|
||||
let mut out = HashMap::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
let mut access = access;
|
||||
let mut builds = true;
|
||||
if let Some(m) = members.iter().find(|m| m.workspace_id == id) {
|
||||
let roles =
|
||||
roles::effective_roles(&instance, &overrides.remove(&id).unwrap_or_default())?;
|
||||
let name = roles::resolve_role_name(m.workspace_role.clone(), m.operator);
|
||||
let role = roles.iter().find(|r| r.name == name);
|
||||
let limited = roles.iter().any(|r| r.mcp_limit().is_some());
|
||||
let limit = match role {
|
||||
Some(role) => role.mcp_limit().and_then(limit_of),
|
||||
None => limited.then_some(McpLimit::Off),
|
||||
};
|
||||
match limit {
|
||||
None => {}
|
||||
Some(McpLimit::ReadAndRun) => access = access.min(SessionAccess::ReadAndRun),
|
||||
Some(McpLimit::ReadOnly) => access = SessionAccess::ReadOnly,
|
||||
Some(McpLimit::Runnables { .. }) => {
|
||||
out.insert(
|
||||
id,
|
||||
"scripts and flows as tools, on this workspace's own MCP URL",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
Some(McpLimit::Off) => {
|
||||
out.insert(id, "off");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !m.is_admin {
|
||||
let caps = role.map_or(RoleCapabilities::NONE, |r| r.capabilities);
|
||||
if !caps.run {
|
||||
access = SessionAccess::ReadOnly;
|
||||
}
|
||||
builds = caps.is_author();
|
||||
}
|
||||
}
|
||||
if access == SessionAccess::Full && (!builds || locked.contains(&id)) {
|
||||
access = SessionAccess::ReadAndRun;
|
||||
}
|
||||
out.insert(
|
||||
id,
|
||||
match access {
|
||||
SessionAccess::ReadOnly => "read only",
|
||||
SessionAccess::ReadAndRun => "read and run",
|
||||
SessionAccess::Full => "build and run",
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -342,6 +342,67 @@ pub fn legacy_operator_settings(c: &RoleCapabilities) -> serde_json::Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// What a role's members may do through MCP.
|
||||
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpRoleAccess {
|
||||
/// Whatever the role can do in Windmill. Stored explicitly by a workspace lifting the
|
||||
/// instance's limit: an unset setting falls through instead.
|
||||
#[default]
|
||||
FollowRole,
|
||||
ReadRun,
|
||||
ReadOnly,
|
||||
/// The scripts and flows of the setting, one tool each, and nothing else.
|
||||
Runnables,
|
||||
Off,
|
||||
}
|
||||
|
||||
/// A role's MCP setting: a maximum for every connection of its members, workspace admins holding
|
||||
/// the role included. Apart from [`RoleCapabilities`], which it must not affect: seats and every
|
||||
/// authoring gate read those. EE only, see [`custom_roles_built`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct McpRoleSetting {
|
||||
pub access: McpRoleAccess,
|
||||
/// Paths as an `mcp:scripts:` scope names them: `*`, an exact path or a `<prefix>/*` subtree.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub scripts: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub flows: Vec<String>,
|
||||
}
|
||||
|
||||
impl McpRoleSetting {
|
||||
fn off() -> Self {
|
||||
Self { access: McpRoleAccess::Off, ..Default::default() }
|
||||
}
|
||||
|
||||
pub fn validate(&self, role: &str) -> Result<()> {
|
||||
let runnables = self.access == McpRoleAccess::Runnables;
|
||||
if runnables == (self.scripts.is_empty() && self.flows.is_empty()) {
|
||||
return Err(Error::BadRequest(if runnables {
|
||||
format!("role `{role}`: choose at least one script or flow to offer over MCP")
|
||||
} else {
|
||||
format!(
|
||||
"role `{role}`: MCP scripts and flows are only set with the `runnables` access"
|
||||
)
|
||||
}));
|
||||
}
|
||||
for path in self.scripts.iter().chain(&self.flows) {
|
||||
let base = path.strip_suffix("/*").unwrap_or(path);
|
||||
let usable = path == "*"
|
||||
|| (!base.contains(['*', ',', ' '])
|
||||
&& ["u/", "f/", "g/"]
|
||||
.iter()
|
||||
.any(|p| base.len() > p.len() && base.starts_with(p)));
|
||||
if !usable {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"role `{role}`: `{path}` is not a script or flow path: use `*`, a path, or `<folder path>/*`"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry of the instance's [`WORKSPACE_ROLES_SETTING`].
|
||||
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RoleDefinition {
|
||||
@@ -350,6 +411,9 @@ pub struct RoleDefinition {
|
||||
pub label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub capabilities: RoleCapabilitiesPatch,
|
||||
/// Unset falls through to the layer below.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp: Option<McpRoleSetting>,
|
||||
}
|
||||
|
||||
/// One entry of `workspace_settings.role_overrides`, keyed by role name. Naming a role the
|
||||
@@ -360,6 +424,9 @@ pub struct RoleOverride {
|
||||
pub label: Option<String>,
|
||||
#[serde(default)]
|
||||
pub capabilities: RoleCapabilitiesPatch,
|
||||
/// Unset falls through to the layer below.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp: Option<McpRoleSetting>,
|
||||
}
|
||||
|
||||
pub type RoleOverrides = HashMap<String, RoleOverride>;
|
||||
@@ -377,11 +444,22 @@ pub struct EffectiveRole {
|
||||
pub name: String,
|
||||
pub label: String,
|
||||
pub capabilities: RoleCapabilities,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp: Option<McpRoleSetting>,
|
||||
pub source: RoleSource,
|
||||
/// Whether the workspace overrides this role.
|
||||
pub overridden: bool,
|
||||
}
|
||||
|
||||
impl EffectiveRole {
|
||||
/// The role's MCP setting when it limits anything.
|
||||
pub fn mcp_limit(&self) -> Option<&McpRoleSetting> {
|
||||
self.mcp
|
||||
.as_ref()
|
||||
.filter(|m| m.access != McpRoleAccess::FollowRole)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether stored instance roles and workspace-only roles apply: on any EE build. A CE build has
|
||||
/// `developer` and `operator`, which a workspace may still override.
|
||||
fn custom_roles_built() -> bool {
|
||||
@@ -409,11 +487,13 @@ pub fn default_instance_roles() -> Vec<RoleDefinition> {
|
||||
name: DEVELOPER_ROLE.to_string(),
|
||||
label: Some("Developer".to_string()),
|
||||
capabilities: RoleCapabilitiesPatch::default(),
|
||||
mcp: None,
|
||||
},
|
||||
RoleDefinition {
|
||||
name: OPERATOR_ROLE.to_string(),
|
||||
label: Some("Operator".to_string()),
|
||||
capabilities: RoleCapabilitiesPatch::default(),
|
||||
mcp: None,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -453,6 +533,9 @@ pub fn parse_instance_roles(value: &serde_json::Value) -> Result<Vec<RoleDefinit
|
||||
return Err(Error::BadRequest(format!("duplicate role `{}`", r.name)));
|
||||
}
|
||||
RoleCapabilities::resolve(&r.name, &[&r.capabilities]).validate(&r.name)?;
|
||||
if let Some(mcp) = &r.mcp {
|
||||
mcp.validate(&r.name)?;
|
||||
}
|
||||
}
|
||||
Ok(roles)
|
||||
}
|
||||
@@ -476,6 +559,11 @@ pub fn effective_roles(
|
||||
.unwrap_or_else(|| def.name.clone()),
|
||||
name: def.name.clone(),
|
||||
capabilities: caps,
|
||||
mcp: ovr
|
||||
.and_then(|o| o.mcp.as_ref())
|
||||
.or(def.mcp.as_ref())
|
||||
.filter(|_| custom_roles_built())
|
||||
.cloned(),
|
||||
source: RoleSource::Instance,
|
||||
overridden: ovr.is_some(),
|
||||
});
|
||||
@@ -492,6 +580,7 @@ pub fn effective_roles(
|
||||
name: name.clone(),
|
||||
label: o.label.clone().unwrap_or_else(|| name.clone()),
|
||||
capabilities: caps,
|
||||
mcp: o.mcp.clone(),
|
||||
source: RoleSource::Workspace,
|
||||
overridden: true,
|
||||
});
|
||||
@@ -510,6 +599,11 @@ pub fn validate_overrides(instance: &[RoleDefinition], overrides: &RoleOverrides
|
||||
)));
|
||||
}
|
||||
}
|
||||
for (name, o) in overrides {
|
||||
if let Some(mcp) = &o.mcp {
|
||||
mcp.validate(name)?;
|
||||
}
|
||||
}
|
||||
for r in effective_roles(instance, overrides)? {
|
||||
r.capabilities.validate(&r.name)?;
|
||||
}
|
||||
@@ -517,7 +611,8 @@ pub fn validate_overrides(instance: &[RoleDefinition], overrides: &RoleOverrides
|
||||
}
|
||||
|
||||
/// Refuses, while [`custom_roles_enabled`] is false, a `role_overrides` write that adds, edits or
|
||||
/// relabels a workspace-only role. Removing one, and overriding instance roles, stay allowed.
|
||||
/// relabels a workspace-only role, or that sets an MCP setting. Removing either, and overriding
|
||||
/// the capabilities of instance roles, stay allowed.
|
||||
pub fn check_frozen_overrides(
|
||||
instance: &[RoleDefinition],
|
||||
previous: &RoleOverrides,
|
||||
@@ -532,6 +627,11 @@ pub fn check_frozen_overrides(
|
||||
"changing workspace role `{name}` requires a valid Windmill Enterprise Edition license"
|
||||
)));
|
||||
}
|
||||
if o.mcp.is_some() && previous.get(name).map(|p| &p.mcp) != Some(&o.mcp) {
|
||||
return Err(Error::BadRequest(format!(
|
||||
"changing the MCP access of role `{name}` requires a valid Windmill Enterprise Edition license"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -782,6 +882,37 @@ pub async fn caller_capabilities<A: Authable + ?Sized>(
|
||||
}
|
||||
}
|
||||
|
||||
/// The MCP setting limiting the caller in `workspace_id`, `None` when nothing does. An error means
|
||||
/// the limit is unknown: refuse, since an unread limit is one the admin still relies on.
|
||||
///
|
||||
/// Reads the member's role only where some role carries a limit, so an unconfigured workspace
|
||||
/// costs the cached [`workspace_roles`] and Community nothing. Workspace admins are held to the
|
||||
/// role they carry; a superadmin who is no member carries none.
|
||||
pub async fn caller_mcp_limit<A: Authable + ?Sized>(
|
||||
db: &DB,
|
||||
workspace_id: &str,
|
||||
authed: &A,
|
||||
) -> Result<Option<McpRoleSetting>> {
|
||||
if !custom_roles_built() {
|
||||
return Ok(None);
|
||||
}
|
||||
let roles = workspace_roles(db, workspace_id).await?;
|
||||
if !roles.iter().any(|r| r.mcp_limit().is_some()) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(
|
||||
match member_role(db, workspace_id, authed.username()).await? {
|
||||
Some(name) => match roles.iter().find(|r| r.name == name) {
|
||||
Some(role) => role.mcp_limit().cloned(),
|
||||
// A role no longer defined fails closed, as its capabilities do.
|
||||
None => Some(McpRoleSetting::off()),
|
||||
},
|
||||
None if authed.is_admin() => None,
|
||||
None => Some(McpRoleSetting::off()),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the caller's role in `workspace_id` holds [`RoleCapabilities::fork`]. Read from the role
|
||||
/// even for an unrestricted caller, since withdrawing `fork` alone leaves a role unrestricted. A
|
||||
/// caller with no membership is left to the fork routes' other gates.
|
||||
@@ -918,6 +1049,14 @@ pub async fn ensure_role_unused(db: &DB, w_id: Option<&str>, name: &str) -> Resu
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether `next` is `current` itself, or with some roles' MCP settings removed.
|
||||
fn only_removes_mcp(current: &[RoleDefinition], next: &[RoleDefinition]) -> bool {
|
||||
current.len() == next.len()
|
||||
&& current.iter().zip(next).all(|(c, n)| {
|
||||
c == n || (n.mcp.is_none() && RoleDefinition { mcp: None, ..c.clone() } == *n)
|
||||
})
|
||||
}
|
||||
|
||||
/// Checks a write of the `workspace_roles` setting (`None` or null resets to the defaults) before
|
||||
/// it is stored. Every writer of the setting must call it, the declarative config sync included.
|
||||
pub async fn validate_instance_roles_write(
|
||||
@@ -929,8 +1068,12 @@ pub async fn validate_instance_roles_write(
|
||||
None | Some(serde_json::Value::Null) => default_instance_roles(),
|
||||
Some(v) => parse_instance_roles(v)?,
|
||||
};
|
||||
// Resetting stays open so a downgraded instance can always drop the setting.
|
||||
if !custom_roles_enabled() && *current != next && next != default_instance_roles() {
|
||||
// Resetting stays open so a downgraded instance can always drop the setting, and so does
|
||||
// removing an MCP setting.
|
||||
if !custom_roles_enabled()
|
||||
&& !only_removes_mcp(¤t, &next)
|
||||
&& next != default_instance_roles()
|
||||
{
|
||||
return Err(Error::BadRequest(
|
||||
"changing workspace roles requires a valid Windmill Enterprise Edition license"
|
||||
.to_string(),
|
||||
@@ -958,9 +1101,34 @@ pub async fn validate_instance_roles_write(
|
||||
))
|
||||
})?;
|
||||
}
|
||||
log_mcp_role_changes(next.iter().map(|r| {
|
||||
let before = current.iter().find(|c| c.name == r.name);
|
||||
(before.and_then(|c| c.mcp.as_ref()), r.mcp.as_ref())
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Counts the MCP settings a role write changes, as `(before, after)` per role.
|
||||
pub fn log_mcp_role_changes<'a>(
|
||||
changes: impl Iterator<Item = (Option<&'a McpRoleSetting>, Option<&'a McpRoleSetting>)>,
|
||||
) {
|
||||
for (before, after) in changes {
|
||||
let access = after.map(|m| m.access);
|
||||
if access == before.map(|m| m.access) {
|
||||
continue;
|
||||
}
|
||||
let key = match access {
|
||||
None => "unset",
|
||||
Some(McpRoleAccess::FollowRole) => "follow_role",
|
||||
Some(McpRoleAccess::ReadRun) => "read_run",
|
||||
Some(McpRoleAccess::ReadOnly) => "read_only",
|
||||
Some(McpRoleAccess::Runnables) => "runnables",
|
||||
Some(McpRoleAccess::Off) => "off",
|
||||
};
|
||||
crate::feature_usage::log_feature_usage("mcp", "role_access", key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Side effects of a stored `workspace_roles` write, owed by every writer. The seat table is read
|
||||
/// by billing on every replica, so it is rebuilt here rather than on the notify that drops the
|
||||
/// role caches.
|
||||
|
||||
@@ -7,7 +7,7 @@ use sqlx::{Pool, Postgres};
|
||||
use windmill_common::ee_oss::LICENSE_KEY_VALID;
|
||||
use windmill_common::roles::{
|
||||
self, check_frozen_overrides, instance_roles, load_role_overrides,
|
||||
validate_instance_roles_write, RoleOverrides,
|
||||
validate_instance_roles_write, McpRoleAccess, McpRoleSetting, RoleOverride, RoleOverrides,
|
||||
};
|
||||
|
||||
/// A lapsed license freezes the configured roles: falling back to the defaults would give a
|
||||
@@ -51,6 +51,15 @@ async fn lapsed_license_freezes_roles(db: Pool<Postgres>) {
|
||||
validate_instance_roles_write(&db, Some(&restricted))
|
||||
.await
|
||||
.expect("resaving the stored roles is a no-op");
|
||||
validate_instance_roles_write(
|
||||
&db,
|
||||
Some(&serde_json::json!([
|
||||
{"name": "developer", "capabilities": {"code": false, "flows": "none", "apps": "none"},
|
||||
"mcp": {"access": "follow_role"}}
|
||||
])),
|
||||
)
|
||||
.await
|
||||
.expect_err("adding an instance MCP setting needs a license");
|
||||
validate_instance_roles_write(&db, None)
|
||||
.await
|
||||
.expect("resetting to the defaults stays open");
|
||||
@@ -65,6 +74,31 @@ async fn lapsed_license_freezes_roles(db: Pool<Postgres>) {
|
||||
check_frozen_overrides(&instance, &previous, &RoleOverrides::new())
|
||||
.expect("removing a workspace-only role stays open");
|
||||
|
||||
let mcp = |access: McpRoleAccess| {
|
||||
RoleOverrides::from([(
|
||||
"developer".to_string(),
|
||||
RoleOverride {
|
||||
mcp: Some(McpRoleSetting { access, ..Default::default() }),
|
||||
..Default::default()
|
||||
},
|
||||
)])
|
||||
};
|
||||
let capped = mcp(McpRoleAccess::ReadOnly);
|
||||
check_frozen_overrides(&instance, &capped, &mcp(McpRoleAccess::FollowRole))
|
||||
.expect_err("changing an MCP setting needs a license");
|
||||
check_frozen_overrides(&instance, &RoleOverrides::new(), &capped)
|
||||
.expect_err("adding an MCP setting needs a license");
|
||||
check_frozen_overrides(&instance, &capped, &capped).expect("an unchanged MCP setting passes");
|
||||
check_frozen_overrides(&instance, &capped, &RoleOverrides::new())
|
||||
.expect("removing an MCP setting stays open");
|
||||
assert!(
|
||||
roles::effective_roles(&instance, &capped)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| r.name == "developer" && r.mcp_limit().is_some()),
|
||||
"a configured MCP limit keeps applying"
|
||||
);
|
||||
|
||||
LICENSE_KEY_VALID.store(true, Ordering::Relaxed);
|
||||
check_frozen_overrides(&instance, &previous, &relabelled).expect("licensed again");
|
||||
}
|
||||
|
||||
@@ -33,6 +33,19 @@ pub struct McpScopeConfig {
|
||||
pub no_endpoints: bool,
|
||||
}
|
||||
|
||||
/// The most a member's workspace role lets an MCP connection do, whatever its token grants.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum McpLimit {
|
||||
ReadAndRun,
|
||||
ReadOnly,
|
||||
/// These scripts and flows, one tool each, and nothing else.
|
||||
Runnables {
|
||||
scripts: Vec<String>,
|
||||
flows: Vec<String>,
|
||||
},
|
||||
Off,
|
||||
}
|
||||
|
||||
impl McpScopeConfig {
|
||||
/// How the token came to have endpoint tools, as a closed set of telemetry keys.
|
||||
pub fn endpoint_shape(&self) -> &'static str {
|
||||
@@ -49,6 +62,31 @@ impl McpScopeConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// This token's grant held to a role's limit. A limited role gets no endpoint tools; a
|
||||
/// selection intersects with the token's own, so each runnable left is one both allow.
|
||||
pub fn limited_by(mut self, limit: &McpLimit) -> Self {
|
||||
self.no_endpoints = true;
|
||||
self.endpoints.clear();
|
||||
match limit {
|
||||
McpLimit::ReadAndRun => {}
|
||||
McpLimit::ReadOnly | McpLimit::Off => self.read_only = true,
|
||||
McpLimit::Runnables { scripts, flows } => {
|
||||
// Favorites name no path: the listing's favorites join keeps narrowing them.
|
||||
if self.favorites && !self.all {
|
||||
self.scripts = scripts.clone();
|
||||
self.flows = flows.clone();
|
||||
} else {
|
||||
self.scripts = intersect_patterns(&self.scripts, scripts);
|
||||
self.flows = intersect_patterns(&self.flows, flows);
|
||||
}
|
||||
self.all = false;
|
||||
self.granular = true;
|
||||
self.hub_apps = None;
|
||||
}
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub fn allows_workspace(&self, workspace_id: &str) -> bool {
|
||||
self.workspaces
|
||||
.as_ref()
|
||||
@@ -153,6 +191,27 @@ fn resource_list_covers(caller: &[String], requested: &[String]) -> bool {
|
||||
.all(|req| caller.iter().any(|c| pattern_covers(c, req)))
|
||||
}
|
||||
|
||||
/// The patterns matching exactly the paths both lists match: two patterns are nested or disjoint,
|
||||
/// so the narrower of each nested pair.
|
||||
fn intersect_patterns(a: &[String], b: &[String]) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for x in a {
|
||||
for y in b {
|
||||
let narrower = if pattern_covers(x, y) {
|
||||
y
|
||||
} else if pattern_covers(y, x) {
|
||||
x
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if !out.contains(narrower) {
|
||||
out.push(narrower.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Directional: does the single caller pattern cover `requested`? `caller` may
|
||||
/// be `*`, an exact path/name, or a `<prefix>/*` subtree; `requested` may itself
|
||||
/// be a subtree wildcard, in which case the whole requested subtree must fall
|
||||
@@ -346,6 +405,33 @@ fn resource_matches_pattern(resource_path: &str, pattern: &str) -> bool {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_role_limit_narrows_and_never_widens() {
|
||||
let parse = |scopes: &[&str]| {
|
||||
parse_mcp_scopes(&scopes.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
|
||||
};
|
||||
let limit = McpLimit::Runnables {
|
||||
scripts: vec!["f/ops/*".to_string(), "f/a/x".to_string()],
|
||||
flows: vec![],
|
||||
};
|
||||
let all = parse(&["mcp:all"]).limited_by(&limit);
|
||||
assert!(all.is_allowed("script", "f/ops/check") && all.is_allowed("script", "f/a/x"));
|
||||
assert!(!all.is_allowed("script", "f/b/x") && !all.is_allowed("flow", "f/ops/check"));
|
||||
assert!(!all.is_allowed("endpoint", "listJobs") && all.no_endpoints && !all.all);
|
||||
|
||||
let selection = parse(&["mcp:scripts:f/ops/sub/*,f/b/x,f/a/*", "mcp:flows:*"]);
|
||||
let both = selection.limited_by(&limit);
|
||||
assert_eq!(both.scripts, ["f/ops/sub/*", "f/a/x"]);
|
||||
assert!(both.flows.is_empty());
|
||||
|
||||
let favorites = parse(&["mcp:favorites"]).limited_by(&limit);
|
||||
assert!(favorites.favorites && favorites.granular);
|
||||
assert!(!favorites.is_allowed("script", "f/b/x"));
|
||||
assert!(parse(&["mcp:endpoints:*"]).limited_by(&limit).scripts.is_empty());
|
||||
assert!(parse(&["mcp:all", "mcp:hub:slack"]).limited_by(&limit).hub_apps.is_none());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_parse_legacy_scopes() {
|
||||
let scopes = vec!["mcp:all".to_string()];
|
||||
|
||||
@@ -9,6 +9,7 @@ use rmcp::ErrorData;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::common::scope::McpLimit;
|
||||
use crate::common::types::{
|
||||
FlowInfo, HubScriptInfo, McpToken, ResourceInfo, ResourceType, SchemaType, ScriptInfo,
|
||||
WorkspaceInfo,
|
||||
@@ -31,7 +32,8 @@ pub enum RunOutcome {
|
||||
|
||||
/// What a v2 token may do: read, read and run deployed scripts, flows and agents
|
||||
/// (`mcp:read_run`), or everything its owner can.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
/// Ordered, narrowest first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum SessionAccess {
|
||||
ReadOnly,
|
||||
ReadAndRun,
|
||||
@@ -276,6 +278,23 @@ pub trait McpBackend: Send + Sync + Clone + 'static {
|
||||
// Workspace server (`SessionRunner`): the AI-session toolset
|
||||
// ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// The limit the caller's role sets on MCP in `workspace_id`, `None` when it sets none. `auth`
|
||||
/// is the caller's in that workspace. An error must refuse: the limit is unknown.
|
||||
async fn mcp_limit(
|
||||
&self,
|
||||
auth: &Self::Auth,
|
||||
workspace_id: &str,
|
||||
) -> BackendResult<Option<McpLimit>>;
|
||||
|
||||
/// What a connection with this access gets in each workspace, by id, for `list_workspaces`.
|
||||
/// A workspace left out says nothing.
|
||||
async fn workspace_accesses(
|
||||
&self,
|
||||
auth: &Self::Auth,
|
||||
workspaces: &[WorkspaceInfo],
|
||||
access: SessionAccess,
|
||||
) -> BackendResult<HashMap<String, &'static str>>;
|
||||
|
||||
/// The instructions a client reaching one workspace receives on connecting, built for
|
||||
/// this user and what the token lets them do.
|
||||
async fn session_instructions(
|
||||
@@ -294,7 +313,7 @@ pub trait McpBackend: Send + Sync + Clone + 'static {
|
||||
auth: &Self::Auth,
|
||||
workspace_id: &str,
|
||||
access: SessionAccess,
|
||||
) -> String;
|
||||
) -> BackendResult<String>;
|
||||
|
||||
/// The tools a token with this access is offered.
|
||||
fn session_tools(&self, access: SessionAccess) -> Vec<Tool>;
|
||||
|
||||
@@ -13,6 +13,7 @@ mod session;
|
||||
pub mod tools;
|
||||
|
||||
// Re-export main types
|
||||
pub use crate::common::scope::McpLimit;
|
||||
pub use crate::common::types::{McpToken, MultiWorkspaceMcp, NoEndpointTools, WorkspaceInfo};
|
||||
pub use backend::{
|
||||
BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess,
|
||||
@@ -22,7 +23,7 @@ pub use endpoints::{
|
||||
list_workspaces_tool, non_empty_body_fields, with_workspace_id_arg, EndpointTool,
|
||||
};
|
||||
pub use runner::{has_endpoint_path_policy, Runner, MAX_TOOL_RESULT_BYTES};
|
||||
pub use session::SessionRunner;
|
||||
pub use session::{admits, session_limit, SessionRunner};
|
||||
pub use tools::create_tool_from_item;
|
||||
|
||||
// Re-export rmcp types for convenience
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! and delegates to a McpBackend for actual functionality.
|
||||
|
||||
use crate::common::schema::extract_resource_types_from_schema;
|
||||
use crate::common::scope::parse_mcp_scopes;
|
||||
use crate::common::scope::{parse_mcp_scopes, McpLimit};
|
||||
use crate::common::transform::{
|
||||
assign_tool_names, extract_hub_version_id_from_hashed, extract_path_prefix_from_hashed,
|
||||
is_encoded_tool_name, parse_tool_prefix, reverse_transform, reverse_transform_key,
|
||||
@@ -19,6 +19,7 @@ use crate::server::endpoints::{
|
||||
endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, list_workspaces_tool, EndpointTool,
|
||||
};
|
||||
use crate::server::list_changes::ListChanges;
|
||||
use crate::server::session::limit_refusal;
|
||||
use crate::server::tools::create_tool_from_item;
|
||||
use rmcp::handler::server::ServerHandler;
|
||||
use rmcp::model::{
|
||||
@@ -647,6 +648,13 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
|
||||
scope_config.no_endpoints |= no_endpoints;
|
||||
|
||||
// v1 has no read-and-run access: such a token reads only.
|
||||
// Multi-workspace mode lists before any workspace is named: a role's limit refuses there
|
||||
// at call time.
|
||||
if let McpMode::Single(workspace_id) = &mode {
|
||||
if let Some(limit) = self.backend.mcp_limit(&auth, workspace_id).await? {
|
||||
scope_config = scope_config.limited_by(&limit);
|
||||
}
|
||||
}
|
||||
let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only;
|
||||
|
||||
match mode {
|
||||
@@ -675,6 +683,14 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
|
||||
let mut scope_config =
|
||||
parse_mcp_scopes(scopes).map_err(|e| ErrorData::internal_error(e, None))?;
|
||||
scope_config.no_endpoints |= no_endpoints;
|
||||
if let McpMode::Single(workspace_id) = &mode {
|
||||
if let Some(limit) = self.backend.mcp_limit(&auth, workspace_id).await? {
|
||||
if matches!(limit, McpLimit::Off | McpLimit::ReadOnly) {
|
||||
return Err(limit_refusal(workspace_id, &limit));
|
||||
}
|
||||
scope_config = scope_config.limited_by(&limit);
|
||||
}
|
||||
}
|
||||
let read_only = auth.read_only() || scope_config.read_run || scope_config.read_only;
|
||||
|
||||
let args = request.arguments.map(Value::Object).unwrap_or(Value::Null);
|
||||
@@ -1294,6 +1310,10 @@ impl<B: McpBackend> Runner<B> {
|
||||
.resolve_workspace_auth(token, &workspace_id)
|
||||
.await
|
||||
.map_err(|e| ErrorData::internal_error(e.message, None))?;
|
||||
// Endpoint tools, the only ones here, are never served under a role's limit.
|
||||
if let Some(limit) = self.backend.mcp_limit(&resolved, &workspace_id).await? {
|
||||
return Err(limit_refusal(&workspace_id, &limit));
|
||||
}
|
||||
(workspace_id, resolved)
|
||||
} else {
|
||||
(String::new(), base_auth.clone())
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Every tool takes the workspace it acts in, whether the token reaches one workspace or
|
||||
//! several, so a client's tool schemas do not change with the token it signed in with.
|
||||
|
||||
use crate::common::scope::{parse_mcp_scopes, McpScopeConfig};
|
||||
use crate::common::scope::{parse_mcp_scopes, McpLimit, McpScopeConfig};
|
||||
use crate::common::types::WorkspaceInfo;
|
||||
use crate::server::backend::{McpAuth, McpBackend, SessionAccess};
|
||||
use crate::server::endpoints::{list_workspaces_tool, with_workspace_id_arg};
|
||||
@@ -30,7 +30,7 @@ use std::sync::Arc;
|
||||
/// `mcp:all`, and no scope from outside `mcp:` that confines the token to some routes
|
||||
/// or paths (`variables:read:f/x/*`): the tools call the API without a route scope, so
|
||||
/// that confinement would be lost here. The job tag fence is carried through instead.
|
||||
fn admits(scopes: &[String], all: bool) -> bool {
|
||||
pub fn admits(scopes: &[String], all: bool) -> bool {
|
||||
all && scopes
|
||||
.iter()
|
||||
.all(|s| s.starts_with("mcp:") || s.starts_with("if_jobs:filter_tags:"))
|
||||
@@ -46,6 +46,34 @@ fn access<A: McpAuth>(auth: &A, scope: &McpScopeConfig) -> SessionAccess {
|
||||
}
|
||||
}
|
||||
|
||||
/// The access a role's limit leaves the session toolset, or why it leaves none.
|
||||
pub fn session_limit(workspace_id: &str, limit: &McpLimit) -> Result<SessionAccess, ErrorData> {
|
||||
match limit {
|
||||
McpLimit::ReadAndRun => Ok(SessionAccess::ReadAndRun),
|
||||
McpLimit::ReadOnly => Ok(SessionAccess::ReadOnly),
|
||||
McpLimit::Runnables { .. } | McpLimit::Off => Err(limit_refusal(workspace_id, limit)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Says what is allowed there instead, so the model does not retry.
|
||||
pub(super) fn limit_refusal(workspace_id: &str, limit: &McpLimit) -> ErrorData {
|
||||
let allowed = match limit {
|
||||
McpLimit::Off => "your role has no MCP access there".to_string(),
|
||||
McpLimit::Runnables { .. } => format!(
|
||||
"your role is limited there to chosen scripts and flows as tools, which a connection \
|
||||
to that workspace's own MCP URL (/api/mcp/w/{workspace_id}/mcp) serves"
|
||||
),
|
||||
McpLimit::ReadOnly => "your role is limited there to reading, through /api/mcp".to_string(),
|
||||
McpLimit::ReadAndRun => {
|
||||
"your role is limited there to reading and running, through /api/mcp".to_string()
|
||||
}
|
||||
};
|
||||
ErrorData::invalid_params(
|
||||
format!("Not available in workspace '{workspace_id}': {allowed}"),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
const GET_WORKSPACE_CONTEXT: &str = "get_workspace_context";
|
||||
|
||||
/// The MIME type of an MCP Apps view (the `io.modelcontextprotocol/ui` extension).
|
||||
@@ -196,9 +224,19 @@ impl<B: McpBackend> SessionRunner<B> {
|
||||
"Every tool takes a `workspace_id`: pass `{}`, the workspace this connection \
|
||||
works in.\n\n{}",
|
||||
only.id,
|
||||
self.backend
|
||||
.session_instructions(&auth, &only.id, access(&auth, &caller.scope))
|
||||
.await?
|
||||
match self.backend.mcp_limit(&auth, &only.id).await? {
|
||||
// Connecting succeeds so the client shows why no tool works there.
|
||||
Some(limit @ (McpLimit::Off | McpLimit::Runnables { .. })) =>
|
||||
limit_refusal(&only.id, &limit).message.into_owned(),
|
||||
_ =>
|
||||
self.backend
|
||||
.session_instructions(
|
||||
&auth,
|
||||
&only.id,
|
||||
access(&auth, &caller.scope),
|
||||
)
|
||||
.await?,
|
||||
}
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
@@ -288,6 +326,17 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
|
||||
// A bound token's one workspace decides its toolset as it decides its instructions:
|
||||
// a role there that cannot run gets the read-only tools.
|
||||
if let McpMode::Single(bound) = &caller.mode {
|
||||
match self.backend.mcp_limit(&caller.auth, bound).await? {
|
||||
Some(limit) => match session_limit(bound, &limit) {
|
||||
Ok(most) => access = access.min(most),
|
||||
Err(_) => {
|
||||
return Ok(ListToolsResult::with_all_items(tools)
|
||||
.with_ttl_ms(LIST_TTL_MS)
|
||||
.with_cache_scope(LIST_CACHE_SCOPE))
|
||||
}
|
||||
},
|
||||
None => {}
|
||||
}
|
||||
if access != SessionAccess::ReadOnly
|
||||
&& !self
|
||||
.backend
|
||||
@@ -371,8 +420,26 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
|
||||
let caller = Self::caller(&context)?;
|
||||
if request.name == "list_workspaces" {
|
||||
let workspaces = self.workspaces(&caller).await?;
|
||||
let accesses = self
|
||||
.backend
|
||||
.workspace_accesses(
|
||||
&caller.auth,
|
||||
&workspaces,
|
||||
access(&caller.auth, &caller.scope),
|
||||
)
|
||||
.await?;
|
||||
let listed: Vec<Value> = workspaces
|
||||
.iter()
|
||||
.map(|w| {
|
||||
let mut entry = serde_json::json!({ "id": w.id, "name": w.name });
|
||||
if let Some(access) = accesses.get(&w.id) {
|
||||
entry["access"] = (*access).into();
|
||||
}
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
return Ok(CallToolResult::success(vec![ContentBlock::text(
|
||||
serde_json::to_string_pretty(&workspaces).unwrap_or_default(),
|
||||
serde_json::to_string_pretty(&listed).unwrap_or_default(),
|
||||
)])
|
||||
.into());
|
||||
}
|
||||
@@ -391,7 +458,7 @@ impl<B: McpBackend> ServerHandler for SessionRunner<B> {
|
||||
let text = self
|
||||
.backend
|
||||
.workspace_context(&auth, &workspace_id, access(&auth, &caller.scope))
|
||||
.await;
|
||||
.await?;
|
||||
return Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into());
|
||||
}
|
||||
let result = self
|
||||
|
||||
Generated
+1
-1
@@ -8666,7 +8666,7 @@ write a secret you were not given: keep the placeholder.
|
||||
| \`default_app\` | Path of the app shown as the workspace home. |
|
||||
| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. |
|
||||
| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. |
|
||||
| \`role_overrides\` | \`{ <role>: { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. |
|
||||
| \`role_overrides\` | \`{ <role>: { label?, capabilities, mcp?, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. \`mcp\` (Enterprise) caps what the role's members may do through MCP: \`{ access: follow_role \\| read_run \\| read_only \\| runnables \\| off, scripts?, flows? }\`, the paths only with \`runnables\`. |
|
||||
| \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. |
|
||||
| \`mute_critical_alerts\` | Mute the workspace's critical alerts. |
|
||||
| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. |
|
||||
|
||||
@@ -57,6 +57,27 @@ Unlike `fork`, withdrawing `run` makes a role restricted: it is an enforced gate
|
||||
and the fast path is what spares every unrestricted caller a role lookup on each run. It does not
|
||||
change seats: a role is a full seat by what it authors, not by whether it runs.
|
||||
|
||||
## MCP access
|
||||
|
||||
A role may carry an MCP setting beside its capabilities (`McpRoleSetting`, EE): `follow_role`,
|
||||
`read_run`, `read_only`, `runnables` (listed scripts and flows as tools, nothing else) or `off`. It
|
||||
is a maximum for every MCP connection of the role's members, whatever the token and whenever it was
|
||||
made, and never widens one; the in-app chat does not read it. Layers fall through as capabilities
|
||||
do, so `follow_role` is stored by a workspace lifting the instance's limit. It is not a capability:
|
||||
it must not restrict a role, cost a seat or reach an authoring gate.
|
||||
|
||||
- Workspace admins are held to the setting of the role they carry, as `DisableDirectDeployment`
|
||||
holds them. A superadmin who is no member carries no role.
|
||||
- `caller_mcp_limit` reads the member's role only where some role carries a limit. An error or a
|
||||
role no longer defined refuses, unlike `can_run`, which fails open.
|
||||
- A connection to one workspace is served by the role, not the URL (`served_under_limit`):
|
||||
`runnables` gets the tools server whatever the token, and an `mcp:all` token under another limit
|
||||
the session toolset, since endpoint tools are never served under one. Where a connection covers
|
||||
several workspaces the list is one for all, so the limit refuses at call time.
|
||||
- A selection intersects with the token's own (`McpScopeConfig::limited_by`).
|
||||
- A lapsed license freezes it as it does roles: it keeps applying and can be removed, not changed.
|
||||
On Community it is ignored and refused at write.
|
||||
|
||||
## Forks
|
||||
|
||||
A member's role carries into a fork: the forker, and every member `copy_members` or
|
||||
|
||||
@@ -4,7 +4,13 @@
|
||||
import { Alert, Badge, Button } from '../common'
|
||||
import TextInput from '../text_input/TextInput.svelte'
|
||||
import RoleCapabilitiesEditor from '../settings/RoleCapabilitiesEditor.svelte'
|
||||
import type { RoleCapabilities, RoleCapabilitiesPatch, RoleDefinition } from '$lib/gen'
|
||||
import RoleMcpAccessEditor from '../settings/RoleMcpAccessEditor.svelte'
|
||||
import type {
|
||||
McpRoleSetting,
|
||||
RoleCapabilities,
|
||||
RoleCapabilitiesPatch,
|
||||
RoleDefinition
|
||||
} from '$lib/gen'
|
||||
import {
|
||||
resolveCapabilities,
|
||||
authorLevelLabel,
|
||||
@@ -36,6 +42,7 @@
|
||||
name: string
|
||||
label: string
|
||||
capabilities: RoleCapabilitiesPatch
|
||||
mcp: McpRoleSetting | undefined
|
||||
open: boolean
|
||||
}
|
||||
|
||||
@@ -52,6 +59,7 @@
|
||||
name: r.name ?? '',
|
||||
label: r.label ?? '',
|
||||
capabilities: structuredClone(r.capabilities ?? {}),
|
||||
mcp: structuredClone(r.mcp ?? undefined),
|
||||
open: false
|
||||
}))
|
||||
}
|
||||
@@ -60,7 +68,8 @@
|
||||
const list: RoleDefinition[] = rs.map((r) => ({
|
||||
name: r.name.trim(),
|
||||
...(r.label.trim() ? { label: r.label.trim() } : {}),
|
||||
...(isEmptyPatch(r.capabilities) ? {} : { capabilities: r.capabilities })
|
||||
...(isEmptyPatch(r.capabilities) ? {} : { capabilities: r.capabilities }),
|
||||
...(r.mcp ? { mcp: r.mcp } : {})
|
||||
}))
|
||||
return isDefaultInstanceRoles(list) ? undefined : list
|
||||
}
|
||||
@@ -78,7 +87,8 @@
|
||||
|
||||
$effect(() => {
|
||||
const next = serialize($state.snapshot(rows) as Row[])
|
||||
if (lastSynced === undefined || disabled) return
|
||||
// Not `disabled`: without a license, removing an MCP setting is still saved.
|
||||
if (lastSynced === undefined || loading) return
|
||||
const nextStr = JSON.stringify(next ?? null)
|
||||
// Compared with the stored value in serialized form, so one spelled differently (the
|
||||
// defaults written out, an empty `capabilities`, another key order) is not rewritten
|
||||
@@ -94,7 +104,7 @@
|
||||
const flipDurationMs = 200
|
||||
|
||||
function addRole() {
|
||||
rows = [...rows, { id: nextId++, name: '', label: '', capabilities: {}, open: true }]
|
||||
rows = [...rows, { id: nextId++, name: '', label: '', capabilities: {}, mcp: undefined, open: true }]
|
||||
}
|
||||
|
||||
function summary(caps: RoleCapabilities): string {
|
||||
@@ -115,7 +125,7 @@
|
||||
title="Changing workspace roles requires a valid Windmill Enterprise Edition license"
|
||||
>
|
||||
The roles below keep applying as they are. A workspace admin can still override what they
|
||||
allow in that workspace's settings.
|
||||
allow in that workspace's settings, and an MCP access set here can still be removed.
|
||||
{#if serialize(rows) !== undefined}
|
||||
<div class="mt-2">
|
||||
<Button
|
||||
@@ -234,6 +244,13 @@
|
||||
{disabled}
|
||||
onchange={(p) => (row.capabilities = p)}
|
||||
/>
|
||||
<RoleMcpAccessEditor
|
||||
setting={row.mcp}
|
||||
inheritedText="Default (follow the role)"
|
||||
frozen={unlicensed}
|
||||
disabled={loading}
|
||||
onchange={(mcp) => (row.mcp = mcp)}
|
||||
/>
|
||||
</div>
|
||||
{:else if errors[`${i}.capabilities`]}
|
||||
<span class="text-2xs text-red-600 dark:text-red-400 px-2 pb-2">
|
||||
|
||||
@@ -17,9 +17,12 @@
|
||||
workspaceId: string
|
||||
scope: string
|
||||
initialScope?: string
|
||||
/** Paths every member of a role shares: no favorites, which are each member's own, and no
|
||||
* hub scripts, which are no path. */
|
||||
pathsOnly?: boolean
|
||||
}
|
||||
|
||||
let { workspaceId, scope = $bindable(), initialScope }: Props = $props()
|
||||
let { workspaceId, scope = $bindable(), initialScope, pathsOnly = false }: Props = $props()
|
||||
|
||||
// Mirrors ITEMS_FETCH_MAX_LIMIT in backend/windmill-api/src/mcp/utils.rs: the
|
||||
// server exposes at most this many scripts and this many flows (per type) as
|
||||
@@ -29,7 +32,9 @@
|
||||
|
||||
const parsedInitial = parseInitialScope(initialScope)
|
||||
|
||||
let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>(parsedInitial.mode)
|
||||
let selectedMode = $state<'favorites' | 'all' | 'folder' | 'custom'>(
|
||||
pathsOnly && parsedInitial.mode === 'favorites' ? 'folder' : parsedInitial.mode
|
||||
)
|
||||
let selectedFolders = $state<string[]>(parsedInitial.folders)
|
||||
let allFolders = $state<string[]>([])
|
||||
let loadingFolders = $state(false)
|
||||
@@ -474,12 +479,14 @@
|
||||
<span class="block mb-1 text-emphasis text-xs font-semibold">Scope</span>
|
||||
<ToggleButtonGroup bind:selected={selectedMode} allowEmpty={false}>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="favorites"
|
||||
label="Favorites only"
|
||||
tooltip="Make only your favorite scripts and flows available as tools"
|
||||
/>
|
||||
{#if !pathsOnly}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="favorites"
|
||||
label="Favorites only"
|
||||
tooltip="Make only your favorite scripts and flows available as tools"
|
||||
/>
|
||||
{/if}
|
||||
<ToggleButton
|
||||
{item}
|
||||
value="all"
|
||||
@@ -523,7 +530,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div>
|
||||
<div class:hidden={pathsOnly}>
|
||||
<span class="block mb-1 text-emphasis text-xs font-semibold">Hub scripts (optional)</span>
|
||||
{#if loadingApps}
|
||||
<div>Loading...</div>
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
<script lang="ts">
|
||||
import Select from '$lib/components/select/Select.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import McpScopeSelector from '$lib/components/mcp/McpScopeSelector.svelte'
|
||||
import type { McpRoleSetting } from '$lib/gen'
|
||||
import { MCP_ROLE_ACCESS_LABELS, mcpSettingError } from '$lib/workspaceRoles'
|
||||
|
||||
type Access = McpRoleSetting['access']
|
||||
|
||||
interface Props {
|
||||
setting: McpRoleSetting | undefined
|
||||
/** The option leaving the setting to the layer below. */
|
||||
inheritedText: string
|
||||
/** Browses this workspace's scripts and flows; without one, paths are typed. */
|
||||
workspace?: string
|
||||
/** Without a valid license a stored setting keeps applying and can only be removed. */
|
||||
frozen?: boolean
|
||||
disabled?: boolean
|
||||
onchange: (setting: McpRoleSetting | undefined) => void
|
||||
}
|
||||
|
||||
let { setting, inheritedText, workspace, frozen = false, disabled = false, onchange }: Props =
|
||||
$props()
|
||||
|
||||
const INHERIT = 'inherit'
|
||||
|
||||
const items = $derived([
|
||||
{ value: INHERIT, label: inheritedText },
|
||||
...Object.entries(MCP_ROLE_ACCESS_LABELS)
|
||||
.filter(([value]) => !frozen || value === setting?.access)
|
||||
.map(([value, label]) => ({ value, label }))
|
||||
])
|
||||
|
||||
const error = $derived(mcpSettingError(setting))
|
||||
|
||||
function setAccess(value: string) {
|
||||
if (value === (setting?.access ?? INHERIT)) return
|
||||
if (value === INHERIT) return onchange(undefined)
|
||||
onchange({ access: value as Access })
|
||||
}
|
||||
|
||||
function setPaths(scripts: string[], flows: string[]) {
|
||||
// Compared as sets: the selector rewrites the order of the paths it was given.
|
||||
const key = (s: string[] | undefined) => JSON.stringify([...(s ?? [])].sort())
|
||||
if (key(scripts) === key(setting?.scripts) && key(flows) === key(setting?.flows)) return
|
||||
onchange({ access: 'runnables', scripts, flows })
|
||||
}
|
||||
|
||||
function parsePaths(text: string): string[] {
|
||||
return text
|
||||
.split(',')
|
||||
.map((p) => p.trim())
|
||||
.filter((p) => p.length > 0)
|
||||
}
|
||||
|
||||
function scopeOf(s: McpRoleSetting | undefined): string {
|
||||
return [
|
||||
...(s?.scripts?.length ? [`mcp:scripts:${s.scripts.join(',')}`] : []),
|
||||
...(s?.flows?.length ? [`mcp:flows:${s.flows.join(',')}`] : [])
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
function pathsOf(scope: string, kind: 'scripts' | 'flows'): string[] {
|
||||
const prefix = `mcp:${kind}:`
|
||||
const part = scope.split(' ').find((p) => p.startsWith(prefix))
|
||||
return part ? parsePaths(part.slice(prefix.length)) : []
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-4">
|
||||
<div class="flex flex-col grow min-w-0">
|
||||
<span class="text-xs font-semibold text-emphasis">MCP access</span>
|
||||
<span class="text-2xs text-secondary">
|
||||
The most an AI client may do for members of this role, admins holding it included, whatever
|
||||
they grant it. Does not affect the chat in Windmill.
|
||||
</span>
|
||||
</div>
|
||||
<div class="w-72 shrink-0">
|
||||
<Select
|
||||
size="sm"
|
||||
{items}
|
||||
disabled={disabled || (frozen && !setting)}
|
||||
bind:value={() => setting?.access ?? INHERIT, (v) => setAccess(v ?? INHERIT)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{#if setting?.access === 'runnables'}
|
||||
{#if frozen || disabled}
|
||||
<span class="text-2xs text-secondary font-mono break-all">
|
||||
{[...(setting.scripts ?? []), ...(setting.flows ?? [])].join(', ')}
|
||||
</span>
|
||||
{:else if workspace}
|
||||
<div class="rounded-md border p-3">
|
||||
<McpScopeSelector
|
||||
workspaceId={workspace}
|
||||
pathsOnly
|
||||
initialScope={scopeOf(setting)}
|
||||
bind:scope={
|
||||
() => scopeOf(setting),
|
||||
(scope) => setPaths(pathsOf(scope, 'scripts'), pathsOf(scope, 'flows'))
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
{#each ['scripts', 'flows'] as const as kind (kind)}
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-xs font-semibold text-emphasis w-24">
|
||||
{kind === 'scripts' ? 'Scripts' : 'Flows'}
|
||||
</span>
|
||||
<div class="grow">
|
||||
<TextInput
|
||||
size="sm"
|
||||
value={setting[kind]?.join(', ') ?? ''}
|
||||
inputProps={{
|
||||
placeholder: 'f/support/*, f/ops/check_order',
|
||||
'aria-label': kind === 'scripts' ? 'Script paths' : 'Flow paths',
|
||||
onchange: (e) => {
|
||||
const paths = parsePaths(e.currentTarget.value)
|
||||
setPaths(
|
||||
kind === 'scripts' ? paths : (setting?.scripts ?? []),
|
||||
kind === 'flows' ? paths : (setting?.flows ?? [])
|
||||
)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
<span class="text-2xs text-secondary">
|
||||
Paths separated by commas: an exact path, a folder as <code>f/support/*</code>, or
|
||||
<code>*</code> for all. Members get the ones they can run in each workspace.
|
||||
</span>
|
||||
{/if}
|
||||
{#if error}
|
||||
<span class="text-2xs text-red-600 dark:text-red-400">{error}</span>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
@@ -3,9 +3,11 @@
|
||||
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import RoleCapabilitiesEditor from './RoleCapabilitiesEditor.svelte'
|
||||
import RoleMcpAccessEditor from './RoleMcpAccessEditor.svelte'
|
||||
import {
|
||||
WorkspaceService,
|
||||
type EffectiveRole,
|
||||
type McpRoleSetting,
|
||||
type RoleCapabilities,
|
||||
type RoleOverride,
|
||||
type RoleOverrides,
|
||||
@@ -19,6 +21,8 @@
|
||||
forkLooksSet,
|
||||
resolveCapabilities,
|
||||
isEmptyPatch,
|
||||
MCP_ROLE_ACCESS_LABELS,
|
||||
mcpSettingError,
|
||||
roleNameError,
|
||||
VISIBILITY_KEYS
|
||||
} from '$lib/workspaceRoles'
|
||||
@@ -122,12 +126,13 @@
|
||||
for (const [name, v] of entries) {
|
||||
const label = v.label?.trim() || undefined
|
||||
const isInstance = instanceRoles.some((r) => r.name === name)
|
||||
if (isInstance && !label && isEmptyPatch(v.capabilities)) continue
|
||||
if (isInstance && !label && isEmptyPatch(v.capabilities) && !v.mcp) continue
|
||||
out.push([
|
||||
name,
|
||||
{
|
||||
...(label ? { label } : {}),
|
||||
capabilities: isEmptyPatch(v.capabilities) ? {} : v.capabilities
|
||||
capabilities: isEmptyPatch(v.capabilities) ? {} : v.capabilities,
|
||||
...(v.mcp ? { mcp: v.mcp } : {})
|
||||
}
|
||||
])
|
||||
}
|
||||
@@ -144,9 +149,10 @@
|
||||
const errors = $derived.by(() => {
|
||||
const e: Record<string, string> = Object.create(null)
|
||||
for (const name of [...instanceRoles.map((r) => r.name), ...workspaceOnlyNames]) {
|
||||
// Left to the server, which knows the instance value.
|
||||
if (authoringUnknown(name)) continue
|
||||
const err = capabilitiesError(effectiveFor(name))
|
||||
const err =
|
||||
// Authoring left to the server, which knows the instance value.
|
||||
(authoringUnknown(name) ? undefined : capabilitiesError(effectiveFor(name))) ??
|
||||
mcpSettingError(draft.get(name)?.mcp)
|
||||
if (err) e[name] = err
|
||||
}
|
||||
return e
|
||||
@@ -169,6 +175,19 @@
|
||||
draft.set(name, { ...(draft.get(name) ?? {}), capabilities })
|
||||
}
|
||||
|
||||
function setMcp(name: string, mcp: McpRoleSetting | undefined) {
|
||||
const { mcp: _, ...rest } = draft.get(name) ?? {}
|
||||
draft.set(name, mcp ? { ...rest, mcp } : rest)
|
||||
}
|
||||
|
||||
/** The instance's own setting shows only while this workspace states none. */
|
||||
function inheritedMcpText(role: EffectiveRole | undefined): string {
|
||||
const stored = role && data?.overrides[role.name]?.mcp
|
||||
if (!role) return 'Default (follow the role)'
|
||||
if (stored) return 'From instance, shown after saving'
|
||||
return `From instance (${MCP_ROLE_ACCESS_LABELS[role.mcp?.access ?? 'follow_role'].toLowerCase()})`
|
||||
}
|
||||
|
||||
function setLabel(name: string, label: string) {
|
||||
draft.set(name, { ...(draft.get(name) ?? {}), label })
|
||||
}
|
||||
@@ -305,6 +324,15 @@
|
||||
disabled={frozen}
|
||||
onchange={(p) => setPatch(name, p)}
|
||||
/>
|
||||
{#if data?.custom_roles_enabled || role?.mcp || draft.get(name)?.mcp}
|
||||
<RoleMcpAccessEditor
|
||||
setting={draft.get(name)?.mcp}
|
||||
inheritedText={inheritedMcpText(role)}
|
||||
{workspace}
|
||||
frozen={!data?.custom_roles_enabled}
|
||||
onchange={(mcp) => setMcp(name, mcp)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
WorkspaceService,
|
||||
type AuthorLevel,
|
||||
type EffectiveRole,
|
||||
type McpRoleSetting,
|
||||
type RoleCapabilities,
|
||||
type RoleCapabilitiesPatch,
|
||||
type RoleDefinition,
|
||||
@@ -174,9 +175,10 @@ export function workspaceRolesErrors(value: unknown): Record<string, string> {
|
||||
if (nameError) errors[`${i}.name`] = nameError
|
||||
else if (seen.has(r.name)) errors[`${i}.name`] = 'Another role has this name'
|
||||
seen.add(r?.name)
|
||||
const capsError = capabilitiesError(
|
||||
applyCapabilitiesPatch(baseCapabilitiesFor(r?.name ?? ''), r?.capabilities)
|
||||
)
|
||||
const capsError =
|
||||
capabilitiesError(
|
||||
applyCapabilitiesPatch(baseCapabilitiesFor(r?.name ?? ''), r?.capabilities)
|
||||
) ?? mcpSettingError(r?.mcp)
|
||||
if (capsError) errors[`${i}.capabilities`] = capsError
|
||||
})
|
||||
return errors
|
||||
@@ -190,11 +192,27 @@ export function isDefaultInstanceRoles(roles: RoleDefinition[]): boolean {
|
||||
(r, i) =>
|
||||
r.name === DEFAULT_INSTANCE_ROLES[i].name &&
|
||||
(r.label ?? '') === DEFAULT_INSTANCE_ROLES[i].label &&
|
||||
isEmptyPatch(r.capabilities)
|
||||
isEmptyPatch(r.capabilities) &&
|
||||
r.mcp == null
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/** What the server would refuse in a role's MCP setting. */
|
||||
export function mcpSettingError(setting: McpRoleSetting | undefined): string | undefined {
|
||||
return setting?.access === 'runnables' && !setting.scripts?.length && !setting.flows?.length
|
||||
? 'Choose at least one script or flow to offer over MCP.'
|
||||
: undefined
|
||||
}
|
||||
|
||||
export const MCP_ROLE_ACCESS_LABELS: Record<McpRoleSetting['access'], string> = {
|
||||
follow_role: 'Follow the role',
|
||||
read_run: 'Read and run',
|
||||
read_only: 'Read only',
|
||||
runnables: 'Specific scripts and flows as tools',
|
||||
off: 'Off'
|
||||
}
|
||||
|
||||
export function authorLevelLabel(level: AuthorLevel): string {
|
||||
return level === 'none' ? 'None' : level === 'compose' ? 'Compose' : 'Full'
|
||||
}
|
||||
|
||||
@@ -1640,7 +1640,7 @@ write a secret you were not given: keep the placeholder.
|
||||
| \`default_app\` | Path of the app shown as the workspace home. |
|
||||
| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. |
|
||||
| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. |
|
||||
| \`role_overrides\` | \`{ <role>: { label?, capabilities, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. |
|
||||
| \`role_overrides\` | \`{ <role>: { label?, capabilities, mcp?, workspace_only? } }\`: the workspace's overrides of the instance's roles, and with \`workspace_only: true\` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in \`role_overrides.operator\`. \`mcp\` (Enterprise) caps what the role's members may do through MCP: \`{ access: follow_role \\| read_run \\| read_only \\| runnables \\| off, scripts?, flows? }\`, the paths only with \`runnables\`. |
|
||||
| \`operator_settings\` | Legacy view of the \`operator\` role, kept for older servers: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). Not applied when the document also states \`role_overrides\`. |
|
||||
| \`mute_critical_alerts\` | Mute the workspace's critical alerts. |
|
||||
| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. |
|
||||
|
||||
@@ -53,7 +53,7 @@ write a secret you were not given: keep the placeholder.
|
||||
| `default_app` | Path of the app shown as the workspace home. |
|
||||
| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |
|
||||
| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |
|
||||
| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |
|
||||
| `role_overrides` | `{ <role>: { label?, capabilities, mcp?, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. `mcp` (Enterprise) caps what the role's members may do through MCP: `{ access: follow_role \| read_run \| read_only \| runnables \| off, scripts?, flows? }`, the paths only with `runnables`. |
|
||||
| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |
|
||||
| `mute_critical_alerts` | Mute the workspace's critical alerts. |
|
||||
| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |
|
||||
|
||||
@@ -48,7 +48,7 @@ write a secret you were not given: keep the placeholder.
|
||||
| `default_app` | Path of the app shown as the workspace home. |
|
||||
| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. |
|
||||
| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. |
|
||||
| `role_overrides` | `{ <role>: { label?, capabilities, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. |
|
||||
| `role_overrides` | `{ <role>: { label?, capabilities, mcp?, workspace_only? } }`: the workspace's overrides of the instance's roles, and with `workspace_only: true` a role of this workspace only (Enterprise). A role the value omits loses its override. Overriding a role the instance does not define is refused. Edit operator rights in `role_overrides.operator`. `mcp` (Enterprise) caps what the role's members may do through MCP: `{ access: follow_role \| read_run \| read_only \| runnables \| off, scripts?, flows? }`, the paths only with `runnables`. |
|
||||
| `operator_settings` | Legacy view of the `operator` role, kept for older servers: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). Not applied when the document also states `role_overrides`. |
|
||||
| `mute_critical_alerts` | Mute the workspace's critical alerts. |
|
||||
| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. |
|
||||
|
||||
Reference in New Issue
Block a user