feat: optional run history in an MCP tool set

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
hugocasa
2026-11-13 18:13:00 +01:00
co-authored by Claude Opus 5.5
parent 3c4d177dd0
commit bbc9ba0aec
13 changed files with 243 additions and 20 deletions
+5
View File
@@ -39111,6 +39111,11 @@ components:
type: string
instructions:
type: string
run_history:
type: boolean
description: >-
Also serve list_runs and get_run, limited to the runs of the set's
scripts and flows.
DbtWarehouseConnection:
type: object
File diff suppressed because one or more lines are too long
@@ -11,6 +11,7 @@ use super::workspace::{
api_message, get_draft, infer_script_schema, load_flow, load_script_to_run, path_enc,
};
use super::{enc, js_head, js_len, js_tail, opt_str_arg, pretty, str_arg, truthy, Ctx, ToolResult};
use windmill_common::mcp_tool_sets::{tool_set_selection, ToolSetSelection};
pub(super) const TOOLS: &[&str] = &[
"test_run_script",
@@ -1826,13 +1827,32 @@ fn summarize_run(job: &Value) -> Map<String, Value> {
out
}
/// The tool set a caller signed in to, whose runs alone its run tools reach.
fn tool_set(ctx: &Ctx<'_>) -> Option<ToolSetSelection> {
tool_set_selection(ctx.auth.scopes.as_deref().unwrap_or_default())
}
async fn list_runs(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let set = tool_set(ctx);
let path = opt_str_arg(args, "path");
if let (Some(set), Some(path)) = (&set, path) {
if !set.allows("script", path) && !set.allows("flow", path) {
return Err(format!("{path} is not in this connection's tool set"));
}
}
let limit = args
.get("limit")
.and_then(Value::as_u64)
.unwrap_or(30)
.clamp(1, 100);
let mut query = format!("per_page={limit}");
if let Some(prefixes) = set
.as_ref()
.filter(|_| path.is_none())
.and_then(ToolSetSelection::path_prefixes)
{
query.push_str(&format!("&script_path_start={}", enc(&prefixes.join(","))));
}
for (param, arg) in [
("script_path_exact", "path"),
("created_by", "created_by"),
@@ -1852,6 +1872,8 @@ async fn list_runs(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
.as_array()
.into_iter()
.flatten()
// The prefixes match more than the set's patterns: `f/a/x` also starts `f/a/xy`.
.filter(|job| set.as_ref().is_none_or(|set| in_set(set, job)))
.map(|job| Value::Object(summarize_run(job)))
.collect();
Ok(pretty(&Value::Array(runs)))
@@ -2229,7 +2251,39 @@ fn stringify(value: &Value) -> String {
}
}
fn in_set(set: &ToolSetSelection, job: &Value) -> bool {
set.allows(
job["job_kind"].as_str().unwrap_or_default(),
job["script_path"].as_str().unwrap_or_default(),
)
}
/// A tool set's run tools read a run when it, or the flow run it is a step of, is in the set.
async fn require_run_in_set(ctx: &Ctx<'_>, set: &ToolSetSelection, id: &str) -> Result<(), String> {
let mut id = id.to_string();
// A flow nests a few levels deep at most; the bound keeps a cycle from looping.
for _ in 0..16 {
let job = ctx
.get(&ctx.ws(&format!(
"jobs_u/get/{}?no_logs=true&no_code=true",
enc(&id)
)))
.await?;
if in_set(set, &job) {
return Ok(());
}
match job["parent_job"].as_str() {
Some(parent) => id = parent.to_string(),
None => break,
}
}
Err("This run is not in this connection's tool set".to_string())
}
async fn get_run(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
if let Some(set) = tool_set(ctx) {
require_run_in_set(ctx, &set, str_arg(args, "id")?).await?;
}
read_run(ctx, args, false).await
}
+8 -2
View File
@@ -43,7 +43,7 @@ use windmill_common::mcp_tool_sets::{
use windmill_mcp::common::SESSION_SCOPE;
use windmill_mcp::server::{
LocalSessionManager, McpToken, MultiWorkspaceMcp, NoEndpointTools, Runner, SessionRunner,
StreamableHttpServerConfig, StreamableHttpService, ToolSetInstructions,
StreamableHttpServerConfig, StreamableHttpService, ToolSetInstructions, ToolSetRunHistory,
};
use windmill_mcp::WorkspaceId;
@@ -666,7 +666,13 @@ async fn expand_tool_set(db: &DB, request: &mut Request<axum::body::Body>) -> Re
let held = authed.scopes.take().unwrap_or_default();
authed.scopes = Some(expand_tool_set_scopes(&held, &name, set.as_ref()));
}
if let Some(instructions) = set.and_then(|s| s.instructions) {
let Some(set) = set else {
return Ok(());
};
if set.run_history {
request.extensions_mut().insert(ToolSetRunHistory);
}
if let Some(instructions) = set.instructions {
request
.extensions_mut()
.insert(ToolSetInstructions(instructions));
@@ -28,6 +28,62 @@ pub struct McpToolSet {
/// Added to the server's instructions for clients connected to this set.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
/// Also serve `list_runs` and `get_run`, confined to the runs of the set's scripts and flows.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub run_history: bool,
}
/// What a caller signed in to a tool set is confined to, read from its expanded scopes.
pub struct ToolSetSelection {
scripts: Vec<String>,
flows: Vec<String>,
}
/// `None` for a caller signed in to no tool set.
pub fn tool_set_selection(scopes: &[String]) -> Option<ToolSetSelection> {
tool_set_of(scopes)?;
let patterns = |prefix: &str| -> Vec<String> {
scopes
.iter()
.filter_map(|s| s.strip_prefix(prefix))
.flat_map(|list| list.split(','))
.filter(|p| !p.is_empty())
.map(str::to_string)
.collect()
};
Some(ToolSetSelection { scripts: patterns("mcp:scripts:"), flows: patterns("mcp:flows:") })
}
impl ToolSetSelection {
/// Whether a run of `kind` (`script` or `flow`, as jobs name them) at `path` is in the set.
pub fn allows(&self, kind: &str, path: &str) -> bool {
let patterns = match kind {
"script" => &self.scripts,
"flow" => &self.flows,
_ => return false,
};
patterns.iter().any(|p| {
p == "*"
|| p == path
|| p.strip_suffix("/*").is_some_and(|prefix| {
path.strip_prefix(prefix)
.is_some_and(|rest| rest.starts_with('/'))
})
})
}
/// Path prefixes covering the whole set, to narrow a runs query before `allows` filters it;
/// `None` when the set reaches every path.
pub fn path_prefixes(&self) -> Option<Vec<String>> {
let all = self.scripts.iter().chain(&self.flows);
if all.clone().any(|p| p == "*") {
return None;
}
Some(
all.map(|p| p.strip_suffix('*').unwrap_or(p).to_string())
.collect(),
)
}
}
/// By name, as stored in `workspace_settings.mcp_tool_sets`.
@@ -161,6 +217,7 @@ mod tests {
scripts: paths.iter().map(|p| p.to_string()).collect(),
flows: vec![],
instructions: None,
run_history: false,
},
)])
}
@@ -210,4 +267,24 @@ mod tests {
]
);
}
#[test]
fn run_tools_reach_only_the_sets_runs() {
let scopes: Vec<String> = [
"mcp:set:support",
"mcp:scripts:f/ops/*,f/a/x",
"mcp:flows:f/a/sync",
]
.map(String::from)
.to_vec();
let set = tool_set_selection(&scopes).unwrap();
assert!(set.allows("script", "f/ops/check"));
assert!(set.allows("flow", "f/a/sync"));
// The prefixes a runs query is narrowed by match these; `allows` must not.
assert!(!set.allows("script", "f/a/xy"));
assert!(!set.allows("script", "f/opsx/check"));
assert!(!set.allows("flow", "f/a/x"));
assert!(!set.allows("singlestepflow", "f/ops/check"));
assert!(tool_set_selection(&["mcp:scripts:f/ops/*".to_string()]).is_none());
}
}
+4
View File
@@ -32,6 +32,10 @@ pub struct NoEndpointTools;
#[derive(Clone, Debug)]
pub struct ToolSetInstructions(pub String);
/// Marker extension: the tool set a connection is signed in to also serves its run history.
#[derive(Clone, Debug)]
pub struct ToolSetRunHistory;
/// Raw bearer token wrapper for Axum extensions. In multi-workspace mode the
/// runner needs the raw token to re-resolve auth for each requested workspace.
#[derive(Clone, Debug)]
+2 -1
View File
@@ -14,7 +14,8 @@ pub mod tools;
// Re-export main types
pub use crate::common::types::{
McpToken, MultiWorkspaceMcp, NoEndpointTools, ToolSetInstructions, WorkspaceInfo,
McpToken, MultiWorkspaceMcp, NoEndpointTools, ToolSetInstructions, ToolSetRunHistory,
WorkspaceInfo,
};
pub use backend::{
BackendResult, McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess,
+50 -6
View File
@@ -12,9 +12,11 @@ use crate::common::transform::{
};
use crate::common::types::{
McpToken, MultiWorkspaceMcp, NoEndpointTools, ResourceInfo, SchemaType, ToolSetInstructions,
ToolableItem, WorkspaceId,
ToolSetRunHistory, ToolableItem, WorkspaceId,
};
use crate::server::backend::{
McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome, SessionAccess,
};
use crate::server::backend::{McpAuth, McpBackend, McpRequest, PathFilter, RunOutcome};
use crate::server::endpoints::{
endpoint_tool_to_mcp_tool, endpoint_tool_to_mcp_tool_multi, list_workspaces_tool, EndpointTool,
};
@@ -170,8 +172,14 @@ pub(super) struct McpContext<A> {
pub(super) headers: http::HeaderMap,
/// See `McpScopeConfig::no_endpoints`.
pub(super) no_endpoints: bool,
/// See `ToolSetRunHistory`.
pub(super) run_history: bool,
}
/// The session's run tools a tool set with run history serves; their handlers confine them to
/// the set's runs.
const RUN_HISTORY_TOOLS: &[&str] = &["list_runs", "get_run"];
impl<B: McpBackend> Runner<B> {
/// Create a new Runner with the given backend
pub fn new(backend: B) -> Self {
@@ -244,6 +252,7 @@ impl<B: McpBackend> Runner<B> {
mode,
headers: http_parts.headers.clone(),
no_endpoints: http_parts.extensions.get::<NoEndpointTools>().is_some(),
run_history: http_parts.extensions.get::<ToolSetRunHistory>().is_some(),
})
}
}
@@ -663,7 +672,8 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
_request: Option<PaginatedRequestParams>,
context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, ErrorData> {
let McpContext { auth, mode, no_endpoints, .. } = Self::extract_context(&context)?;
let McpContext { auth, mode, no_endpoints, run_history, .. } =
Self::extract_context(&context)?;
// Parse MCP scopes to determine what to expose
let scopes = auth.scopes().unwrap_or(&[]);
@@ -676,8 +686,20 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
match mode {
McpMode::Single(workspace_id) => {
self.list_tools_single(&auth, &workspace_id, &scope_config, read_only)
.await
let mut list = self
.list_tools_single(&auth, &workspace_id, &scope_config, read_only)
.await?;
if run_history {
list.tools
.retain(|t| !RUN_HISTORY_TOOLS.contains(&t.name.as_ref()));
list.tools.extend(
self.backend
.session_tools(SessionAccess::ReadOnly)
.into_iter()
.filter(|t| RUN_HISTORY_TOOLS.contains(&t.name.as_ref())),
);
}
Ok(list)
}
// Multi-workspace: expose the generic endpoint tools (each taking an
// explicit workspace_id) plus list_workspaces. Per-workspace scripts
@@ -693,7 +715,29 @@ impl<B: McpBackend> ServerHandler for Runner<B> {
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, ErrorData> {
let McpContext { auth, mode, headers, no_endpoints } = Self::extract_context(&context)?;
let McpContext { auth, mode, headers, no_endpoints, run_history } =
Self::extract_context(&context)?;
if let (true, McpMode::Single(workspace_id)) = (run_history, &mode) {
if RUN_HISTORY_TOOLS.contains(&request.name.as_ref()) {
let args = request.arguments.map(Value::Object).unwrap_or(Value::Null);
let result = self
.backend
.call_session_tool(
&auth,
workspace_id,
&request.name,
args,
SessionAccess::ReadOnly,
None,
)
.await;
let refusal = result.as_ref().err().map(|e| e.message.as_ref());
self.backend
.after_tool_call(&auth, workspace_id, &request.name, refusal)
.await;
return Ok(result?.into());
}
}
// Parse MCP scopes for authorization
let scopes = auth.scopes().unwrap_or(&[]);
+1 -1
View File
@@ -8527,7 +8527,7 @@ write a secret you were not given: keep the placeholder.
| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |
| \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. |
| \`dbt_warehouses\` | dbt warehouse connections. |
| \`mcp_tool_sets\` | \`{ <name>: { scripts?: [paths], flows?: [paths], instructions? } }\`: selections of scripts and flows, each served at \`/api/mcp/w/<workspace>/s/<name>/mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run. |
| \`mcp_tool_sets\` | \`{ <name>: { scripts?: [paths], flows?: [paths], instructions?, run_history? } }\`: selections of scripts and flows, each served at \`/api/mcp/w/<workspace>/s/<name>/mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run, and with \`run_history\` also \`list_runs\` and \`get_run\` over the set's runs. |
| \`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. |
@@ -2,10 +2,21 @@
import type { GetSettingsResponse } from '$lib/gen'
import { randomUUID } from '$lib/utils/uuid'
export type McpToolSetRow = { id: string; name: string; scope: string; instructions: string }
export type McpToolSetRow = {
id: string
name: string
scope: string
instructions: string
runHistory: boolean
}
export type McpToolSetsType = { sets: McpToolSetRow[] }
type StoredSet = { scripts?: string[]; flows?: string[]; instructions?: string }
type StoredSet = {
scripts?: string[]
flows?: string[]
instructions?: string
run_history?: boolean
}
export function convertMcpToolSetsFromBackend(
stored: GetSettingsResponse['mcp_tool_sets']
@@ -20,7 +31,8 @@
]
.filter(Boolean)
.join(' '),
instructions: set.instructions ?? ''
instructions: set.instructions ?? '',
runHistory: set.run_history ?? false
}))
}
}
@@ -52,7 +64,12 @@
}
}
if (scripts.length === 0 && flows.length === 0) throw `${name} selects no scripts or flows`
out[name] = { scripts, flows, instructions: row.instructions.trim() || undefined }
out[name] = {
scripts,
flows,
instructions: row.instructions.trim() || undefined,
run_history: row.runHistory || undefined
}
}
return out
}
@@ -65,6 +82,7 @@
import TextInput from '../text_input/TextInput.svelte'
import McpScopeSelector from '../mcp/McpScopeSelector.svelte'
import ClipboardPanel from '../details/ClipboardPanel.svelte'
import Toggle from '../Toggle.svelte'
import SettingsFooter from './SettingsFooter.svelte'
import SettingsPageHeader from '../settings/SettingsPageHeader.svelte'
import { WorkspaceService } from '$lib/gen'
@@ -85,7 +103,12 @@
} = $props()
const strip = (s: McpToolSetsType) =>
s.sets.map(({ name, scope, instructions }) => ({ name, scope, instructions }))
s.sets.map(({ name, scope, instructions, runHistory }) => ({
name,
scope,
instructions,
runHistory
}))
let hasUnsavedChanges = $derived(
JSON.stringify(strip(mcpToolSets)) !== JSON.stringify(strip(mcpToolSetsSaved))
)
@@ -161,6 +184,15 @@
}}
/>
</div>
<Toggle
bind:checked={set.runHistory}
options={{
right: 'Run history',
rightTooltip:
"Also offer list_runs and get_run, limited to the runs of this set's scripts and flows that the member can see."
}}
size="xs"
/>
<div class="flex flex-col gap-1">
<span class="text-xs font-semibold text-emphasis">URL</span>
<ClipboardPanel content={setUrl(set.name)} />
@@ -175,7 +207,7 @@
onclick={() => {
mcpToolSets.sets = [
...mcpToolSets.sets,
{ id: randomUUID(), name: '', scope: '', instructions: '' }
{ id: randomUUID(), name: '', scope: '', instructions: '', runHistory: false }
]
}}
>
+1 -1
View File
@@ -1634,7 +1634,7 @@ write a secret you were not given: keep the placeholder.
| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |
| \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. |
| \`dbt_warehouses\` | dbt warehouse connections. |
| \`mcp_tool_sets\` | \`{ <name>: { scripts?: [paths], flows?: [paths], instructions? } }\`: selections of scripts and flows, each served at \`/api/mcp/w/<workspace>/s/<name>/mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run. |
| \`mcp_tool_sets\` | \`{ <name>: { scripts?: [paths], flows?: [paths], instructions?, run_history? } }\`: selections of scripts and flows, each served at \`/api/mcp/w/<workspace>/s/<name>/mcp\`. Paths are exact or end in \`/*\`. A member signed in to a set gets the ones they can run, and with \`run_history\` also \`list_runs\` and \`get_run\` over the set's runs. |
| \`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. |
@@ -50,7 +50,7 @@ write a secret you were not given: keep the placeholder.
| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |
| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |
| `dbt_warehouses` | dbt warehouse connections. |
| `mcp_tool_sets` | `{ <name>: { scripts?: [paths], flows?: [paths], instructions? } }`: selections of scripts and flows, each served at `/api/mcp/w/<workspace>/s/<name>/mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run. |
| `mcp_tool_sets` | `{ <name>: { scripts?: [paths], flows?: [paths], instructions?, run_history? } }`: selections of scripts and flows, each served at `/api/mcp/w/<workspace>/s/<name>/mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run, and with `run_history` also `list_runs` and `get_run` over the set's runs. |
| `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. |
+1 -1
View File
@@ -45,7 +45,7 @@ write a secret you were not given: keep the placeholder.
| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...], fork_role_mapping?: { <role here>: <role in its forks> } } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. |
| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. |
| `dbt_warehouses` | dbt warehouse connections. |
| `mcp_tool_sets` | `{ <name>: { scripts?: [paths], flows?: [paths], instructions? } }`: selections of scripts and flows, each served at `/api/mcp/w/<workspace>/s/<name>/mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run. |
| `mcp_tool_sets` | `{ <name>: { scripts?: [paths], flows?: [paths], instructions?, run_history? } }`: selections of scripts and flows, each served at `/api/mcp/w/<workspace>/s/<name>/mcp`. Paths are exact or end in `/*`. A member signed in to a set gets the ones they can run, and with `run_history` also `list_runs` and `get_run` over the set's runs. |
| `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. |