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>
This commit is contained in:
hugocasa
2026-12-03 10:09:08 +01:00
co-authored by Claude Opus 5.5
parent 0acfdb938d
commit 8485bf250a
11 changed files with 210 additions and 46 deletions
+17
View File
@@ -140,6 +140,23 @@ 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/mcp/gateway/oauth/server/runnable_tools?workspace_id=test-workspace"
))
.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}");
let call = |url: &'static str, token: &'static str, name: &'static str, args: Value| async move {
mcp(
port,
+34
View File
@@ -29923,6 +29923,40 @@ paths:
items:
$ref: "#/components/schemas/McpWorkspaceAccess"
/mcp/gateway/oauth/server/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.
operationId: listMcpRunnableTools
tags:
- mcp_oauth
parameters:
- name: workspace_id
in: query
required: true
schema:
type: string
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
+18 -6
View File
@@ -906,6 +906,21 @@ pub async fn add_www_authenticate_header_gateway(
}
}
/// The tools server's runner, for the consent page to list what a connection would get. Set
/// once the MCP server is set up; unset in a process that serves no MCP.
pub(crate) static PREVIEW_RUNNER: std::sync::OnceLock<Runner<WindmillBackend>> =
std::sync::OnceLock::new();
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,
@@ -919,6 +934,7 @@ pub async fn setup_mcp_server(
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);
let _ = PREVIEW_RUNNER.set(runner.clone());
let service_config = StreamableHttpServerConfig::default()
.with_sse_keep_alive(Some(Duration::from_secs(15)))
@@ -1026,7 +1042,7 @@ struct ToolsetQuery {
}
#[derive(serde::Serialize)]
struct ToolsetEntry {
pub(crate) struct ToolsetEntry {
name: String,
description: String,
/// The JSON Schema of its arguments.
@@ -1046,11 +1062,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(),
parameters: serde_json::Value::Object((*tool.input_schema).clone()),
})
.map(ToolsetEntry::from)
.collect(),
))
}
@@ -1301,6 +1301,10 @@ pub fn gateway_authed_service() -> Router {
"/workspace_access",
get(super::role_access::list_workspace_access),
)
.route(
"/runnable_tools",
get(super::role_access::list_runnable_tools),
)
}
#[cfg(test)]
@@ -320,6 +320,57 @@ pub async fn list_workspace_access(
Ok(Json(out))
}
#[derive(Deserialize)]
pub struct RunnableToolsQuery {
workspace_id: String,
}
/// GET /api/mcp/gateway/oauth/server/runnable_tools: the scripts and flows a sign-in bound to a
/// workspace would list where the caller's role offers them as tools, with their arguments.
pub async fn list_runnable_tools(
Extension(db): Extension<DB>,
authed: ApiAuthed,
Query(query): Query<RunnableToolsQuery>,
) -> 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(),
));
}
let w_id = query.workspace_id;
let username = accesses(
&db,
&authed.email,
vec![w_id.clone()],
SessionAccess::Full,
false,
)
.await?
.remove(&w_id)
.and_then(|m| m.username)
.ok_or_else(|| Error::NotFound(format!("You are not a member of '{w_id}'")))?;
let runner = super::core::PREVIEW_RUNNER
.get()
.ok_or_else(|| Error::BadRequest("This server does not serve MCP".to_string()))?;
let there: ApiAuthed = windmill_common::auth::fetch_authed_from_permissioned_as(
&format!("u/{username}"),
&authed.email,
&w_id,
&db,
)
.await?
.into();
let tools = runner
.role_runnable_tools(&there, &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,
+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,
@@ -1,12 +1,23 @@
<script lang="ts">
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
import AssistantToolsSection from '$lib/components/copilot/chat/AssistantToolsSection.svelte'
import { toolset, type ToolsetLevel } from './toolsets.svelte'
import { runnableToolset, toolset, type ToolsetLevel } from './toolsets.svelte'
let { open = $bindable(false), level }: { open: boolean; level: ToolsetLevel } = $props()
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 ? toolset(level) : undefined)
const tools = $derived(
!open ? undefined : workspace ? runnableToolset(workspace) : level ? toolset(level) : []
)
const summaries = $derived(
(tools ?? [])
.map((t) => ({
@@ -20,7 +31,7 @@
<Modal2
bind:isOpen={open}
title="Tools the client gets"
title="What the client can call"
fixedWidth="md"
fixedHeight="lg"
closeOnOutsideClick={!blocksClose}
@@ -33,7 +44,9 @@
providerTools={[]}
active={open}
bind:blocksClose
description="What the AI client can call on this connection. Where a workspace's role allows less, the call is refused there."
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>
@@ -2,7 +2,6 @@
import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte'
import type { McpWorkspaceAccess } from '$lib/gen'
import type { McpAccess } from './McpAccessPicker.svelte'
import Popover from '$lib/components/Popover.svelte'
import Tooltip from '$lib/components/Tooltip.svelte'
import { Badge } from '$lib/components/common'
import {
@@ -40,16 +39,11 @@
<div class="flex items-center justify-between gap-2">
<span class="text-xs text-emphasis truncate">{workspace.name}</span>
<span class="flex shrink-0 items-center gap-1.5 text-xs text-secondary">
{accessLabel(workspace, access)}{separate ? ', connect separately' : ''}
{#if restricted}
<Popover notClickable>
{#snippet text()}
<div class="text-xs max-w-xs">{restricted}</div>
{/snippet}
<Badge color="gray" small>Restricted</Badge>
</Popover>
<Badge color="gray" small>Restricted</Badge>
{/if}
<Tooltip small>{accessHint(workspace, access)}</Tooltip>
{accessLabel(workspace, access)}{separate ? ', connect separately' : ''}
<Tooltip small>{restricted ?? accessHint(workspace, access)}</Tooltip>
</span>
</div>
{#if separate}
@@ -8,19 +8,31 @@ export type ToolsetEntry = {
}
export type ToolsetLevel = 'read' | 'read_run' | 'full'
const toolsets = new SvelteMap<ToolsetLevel, ToolsetEntry[]>()
const loading = new Set<ToolsetLevel>()
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 {
if (!toolsets.has(level) && !loading.has(level)) {
loading.add(level)
fetch(`/api/mcp/toolset?access=${level}`)
.then((r) => (r.ok ? r.json() : []))
.then((tools: ToolsetEntry[]) => toolsets.set(level, tools))
.catch(() => toolsets.set(level, []))
.finally(() => loading.delete(level))
}
return toolsets.get(level)
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/mcp/gateway/oauth/server/runnable_tools?workspace_id=${encodeURIComponent(workspace)}`
)
}
@@ -60,7 +60,8 @@ export function restriction(workspace: McpWorkspaceAccess, picked: McpAccess): s
const edits = workspace.edits ?? []
const last = edits.at(-1)
const listed = edits.length > 1 ? `${edits.slice(0, -1).join(', ')} and ${last}` : last
return `Your role writes no scripts, flows or apps. The client runs them${listed ? ` and edits ${listed}` : ''}.`
const set = workspace.limited ? ' Set by your role.' : ''
return `Your role writes no scripts, flows or apps. The client runs them${listed ? ` and edits ${listed}` : ''}.${set}`
}
/** The covered workspaces a connection serves. One set to scripts and flows as tools is served
@@ -11,7 +11,6 @@
import Select from '$lib/components/select/Select.svelte'
import Toggle from '$lib/components/Toggle.svelte'
import Tooltip from '$lib/components/Tooltip.svelte'
import Popover from '$lib/components/Popover.svelte'
import McpAccessPicker, {
ACCESS_SCOPES,
MCP_SESSION,
@@ -202,6 +201,12 @@
// A role limit settles the access; a narrower one the client asked for stays editable.
const editable = $derived(served.every((w) => !w.limited) || access !== 'full')
// One tool list per connection: the picked level's, or what a bound workspace leaves.
// 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(
served.some((w) => givesAnything(w, access)) ? connectionToolset(access, bound) : undefined
)
@@ -587,7 +592,7 @@
{/if}
{/snippet}
{#snippet toolsToggle()}
{#if connectionTools}
{#if connectionTools || runnablesHere}
<Button
variant="subtle"
unifiedSize="xs"
@@ -604,24 +609,18 @@
<p class="text-xs font-semibold text-emphasis">Access</p>
{#if !same}
{@render pen()}
{@render toolsToggle()}
{/if}
{@render toolsToggle()}
</div>
{#if same}
{@const restricted = restriction(first, access)}
<div class="flex flex-wrap items-center gap-x-1.5">
<span class="text-xs text-primary">{accessLabel(first, access)}</span>
{#if restricted}
<Popover notClickable>
{#snippet text()}
<div class="text-xs max-w-xs">{restricted}</div>
{/snippet}
<Badge color="gray" small>Restricted</Badge>
</Popover>
<Badge color="gray" small>Restricted</Badge>
{/if}
<Tooltip small>{accessHint(first, access)}</Tooltip>
<Tooltip small>{restricted ?? accessHint(first, access)}</Tooltip>
{@render pen()}
{@render toolsToggle()}
</div>
{:else if served.length > 0}
<McpWorkspaceAccessList
@@ -651,7 +650,13 @@
>
{one ? 'Workspace' : 'Workspaces'}
{leftOut.map((w) => w.name).join(', ')}
{one ? 'connects on its own' : 'connect on their own'}
{toolsOnly
? one
? 'connects on its own'
: 'connect on their own'
: one
? 'is not included'
: 'are not included'}
</Button>
{#if leftOutOpen}
<p class="text-xs text-primary">
@@ -683,8 +688,8 @@
</div>
{/if}
{#if connectionTools}
<McpToolsModal bind:open={toolsOpen} level={connectionTools} />
{#if connectionTools || runnablesHere}
<McpToolsModal bind:open={toolsOpen} level={connectionTools} workspace={runnablesHere} />
{/if}
<Modal