feat: add object storage file tools to the AI session

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-26 00:20:11 -08:00
co-authored by Claude Opus 5.5
parent 97dcc1a78b
commit 92eb08d4e0
7 changed files with 546 additions and 6 deletions
@@ -91,7 +91,7 @@ fn role_arg(args: &Value) -> Result<Option<&str>, String> {
}
/// `path?k=v&...` over the parameters that are set.
fn with_query(path: String, params: &[(&str, Option<&str>)]) -> String {
pub(super) fn with_query(path: String, params: &[(&str, Option<&str>)]) -> String {
let query: Vec<String> = params
.iter()
.filter_map(|(k, v)| v.map(|v| format!("{k}={}", enc(v))))
@@ -2675,6 +2675,107 @@
},
"read_only": true
},
{
"name": "list_s3_files",
"description": "List one folder of the workspace's object storage (S3, Azure Blob or GCS): its subfolders, and its files with size and last modified time. Call again with a subfolder as `prefix` to go deeper, and with `next_page_token` for the rest of a long folder. A call at the root also returns `storages`, the names of the workspace's secondary storages. Each file is an S3 object `{ s3, storage? }`, the shape a script or flow takes as an S3 file input. Only what the user may list is returned, as in the workspace's S3 file browser.",
"parameters": {
"type": "object",
"properties": {
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
},
"prefix": {
"description": "Folder to list, e.g. `charts/` or `charts/2026/`. Omit for the root.",
"type": "string"
},
"page_token": {
"description": "The `next_page_token` of a previous call, for the rest of the same folder.",
"type": "string"
},
"max_keys": {
"description": "Max number of folders and files to return. Defaults to 100.",
"type": "integer",
"minimum": 1,
"maximum": 500
}
},
"additionalProperties": false,
"required": []
},
"read_only": true
},
{
"name": "read_s3_file",
"description": "Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, or the first rows of a Parquet file. Other files, such as images, return their metadata only.",
"parameters": {
"type": "object",
"properties": {
"s3": {
"description": "Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.",
"type": "string"
},
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
}
},
"required": [
"s3"
],
"additionalProperties": false
},
"read_only": true
},
{
"name": "delete_s3_file",
"description": "Delete one file from the workspace's object storage. It cannot be undone: call it only when the user asked for that file to be deleted.",
"parameters": {
"type": "object",
"properties": {
"s3": {
"description": "Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.",
"type": "string"
},
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
}
},
"required": [
"s3"
],
"additionalProperties": false
},
"read_only": false
},
{
"name": "move_s3_file",
"description": "Move or rename one file within one storage of the workspace's object storage: it is copied to `dest_s3`, then the original is deleted. A file already at `dest_s3` is replaced.",
"parameters": {
"type": "object",
"properties": {
"s3": {
"description": "Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.",
"type": "string"
},
"dest_s3": {
"description": "New key of the file, in the same storage.",
"type": "string"
},
"storage": {
"description": "Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage.",
"type": "string"
}
},
"required": [
"s3",
"dest_s3"
],
"additionalProperties": false
},
"read_only": false
},
{
"name": "search_files",
"description": "Search the user-attached files with a regular expression and return matching lines with their line numbers. Use this to locate content before reading a specific window with read_file.",
@@ -71,6 +71,7 @@ mod misc;
mod runs;
mod secrets;
mod settings;
mod storage;
mod views;
mod workspace;
@@ -165,12 +166,15 @@ const DESTRUCTIVE: &[&str] = &[
"rebase_draft",
"delete_app_file",
"delete_app_runnable",
"delete_s3_file",
"move_s3_file",
];
/// Tools that reach a system outside Windmill on the workspace's behalf: running code can
/// reach any system the workspace can, and `get_db_schema` connects to a resource's
/// database, and `search_npm_packages` queries the npm registry, which Windmill does not
/// control. Reading Windmill's own hub and docs does not count.
/// reach any system the workspace can, `get_db_schema` connects to a resource's database,
/// the storage tools reach the workspace's object storage bucket, and `search_npm_packages`
/// queries the npm registry, which Windmill does not control. Reading Windmill's own hub
/// and docs does not count.
#[cfg(any(test, feature = "mcp"))]
const OPEN_WORLD: &[&str] = &[
"search_npm_packages",
@@ -184,6 +188,10 @@ const OPEN_WORLD: &[&str] = &[
"test_run_app_runnable",
"test_run_code",
"get_db_schema",
"list_s3_files",
"read_s3_file",
"delete_s3_file",
"move_s3_file",
];
/// Tools the session counts as reads that still start a job. A read-only token runs
@@ -218,7 +226,9 @@ macro_rules! groups {
}
};
}
groups!(guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings, secrets);
groups!(
guidance, workspace, items, misc, flows, apps, runs, deploy, data, settings, secrets, storage
);
/// A tool as a client lists it.
#[cfg(feature = "mcp")]
@@ -0,0 +1,279 @@
//! The workspace's object storage (its large file storage and secondary storages), through
//! the endpoints of the S3 file browser: what the caller may list, read, delete or move there
//! is exactly what the browser lets them do.
use serde_json::{Map, Value};
use super::data::with_query;
use super::workspace::path_enc;
use super::{array, opt_str_arg, pretty, str_arg, Ctx, ToolResult};
pub(super) const TOOLS: &[&str] = &[
"list_s3_files",
"read_s3_file",
"delete_s3_file",
"move_s3_file",
];
pub(super) async fn call(ctx: &Ctx<'_>, name: &str, args: &Value) -> ToolResult {
let result = match name {
"list_s3_files" => list_s3_files(ctx, args).await,
"read_s3_file" => read_s3_file(ctx, args).await,
"delete_s3_file" => delete_s3_file(ctx, args).await,
"move_s3_file" => move_s3_file(ctx, args).await,
_ => unreachable!("{name} is not a storage tool"),
};
// The object storage routes are mounted only on an Enterprise Edition server.
result.map_err(|e| {
if e == "404: Not Found" {
"Object storage browsing needs a Windmill Enterprise Edition instance.".to_string()
} else {
e
}
})
}
const DEFAULT_MAX_KEYS: u64 = 100;
const MAX_KEYS: u64 = 500;
/// Bytes of a text file handed to the model, under the MCP runner's result limit.
const PREVIEW_BYTES: u64 = 32 * 1024;
const PARQUET_PREVIEW_ROWS: &str = "50";
/// `None` for the primary storage, however it was named.
fn storage_arg(args: &Value) -> Option<&str> {
opt_str_arg(args, "storage").filter(|s| !s.is_empty() && *s != "_default_")
}
/// The listing endpoint takes a folder as empty or `/`-terminated.
fn folder_prefix(prefix: Option<&str>) -> String {
let prefix = prefix.unwrap_or_default().trim_start_matches('/');
if prefix.is_empty() || prefix.ends_with('/') {
prefix.to_string()
} else {
format!("{prefix}/")
}
}
/// An S3 object as scripts and flows take it: `{ s3, storage? }`.
fn s3_object(key: &Value, storage: Option<&str>) -> Map<String, Value> {
let mut object = Map::new();
object.insert("s3".into(), key.clone());
if let Some(storage) = storage {
object.insert("storage".into(), storage.into());
}
object
}
async fn list_s3_files(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let storage = storage_arg(args);
let prefix = folder_prefix(opt_str_arg(args, "prefix"));
let page_token = opt_str_arg(args, "page_token");
let max_keys = args
.get("max_keys")
.and_then(Value::as_u64)
.unwrap_or(DEFAULT_MAX_KEYS)
.clamp(1, MAX_KEYS)
.to_string();
let path = with_query(
ctx.ws("job_helpers/list_stored_files_paged"),
&[
("prefix", Some(&prefix)),
("max_keys", Some(&max_keys)),
("page_token", page_token),
("storage", storage),
],
);
let page = ctx.get(&path).await?;
let storages = if prefix.is_empty() && page_token.is_none() {
Some(
ctx.get(&ctx.ws("workspaces/get_secondary_storage_names"))
.await?,
)
} else {
None
};
Ok(pretty(&listing(
storage,
&prefix,
&page,
storages,
ctx.auth.is_admin,
)))
}
fn listing(
storage: Option<&str>,
prefix: &str,
page: &Value,
storages: Option<Value>,
is_admin: bool,
) -> Value {
let folders: Vec<Value> = array(page.get("folders"))
.iter()
.filter_map(|f| f.get("prefix").cloned())
.collect();
let files: Vec<Value> = array(page.get("files"))
.iter()
.map(|f| {
let mut file = s3_object(&f["key"], storage);
file.insert("size".into(), f["size"].clone());
file.insert("last_modified".into(), f["last_modified"].clone());
Value::Object(file)
})
.collect();
let empty = folders.is_empty() && files.is_empty();
let mut out = Map::new();
if let Some(storage) = storage {
out.insert("storage".into(), storage.into());
}
out.insert("prefix".into(), prefix.into());
out.insert("folders".into(), folders.into());
out.insert("files".into(), files.into());
if let Some(token) = page.get("next_page_token").filter(|t| t.is_string()) {
out.insert("next_page_token".into(), token.clone());
}
if let Some(storages) = storages {
out.insert("storages".into(), storages);
}
if empty {
// The browser drops what the user may not list, so an empty folder and a refused
// one look the same to anyone but an admin.
let note = if is_admin {
"Nothing here: the folder is empty or does not exist."
} else {
"Nothing listed: the folder is empty or does not exist, or this user may not list it. Listing needs workspace admin, storage set as public, or a storage permission rule granting it; tell the user that rather than concluding the storage is empty."
};
out.insert("note".into(), note.into());
}
Value::Object(out)
}
async fn read_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let key = str_arg(args, "s3")?;
let storage = storage_arg(args);
let meta = ctx
.get(&with_query(
ctx.ws("job_helpers/load_file_metadata"),
&[("file_key", Some(key)), ("storage", storage)],
))
.await?;
let size = meta["size_in_bytes"].as_u64().unwrap_or(0);
let mut out = s3_object(&key.into(), storage);
out.insert("size".into(), meta["size_in_bytes"].clone());
out.insert("last_modified".into(), meta["last_modified"].clone());
if key.to_lowercase().ends_with(".parquet") {
let rows = ctx
.get(&with_query(
ctx.ws(&format!(
"job_helpers/load_parquet_preview/{}",
path_enc(key)
)),
&[("limit", Some(PARQUET_PREVIEW_ROWS)), ("storage", storage)],
))
.await?;
for field in ["columns", "column_types", "rows"] {
out.insert(field.into(), rows[field].clone());
}
out.insert(
"note".into(),
format!("At most the first {PARQUET_PREVIEW_ROWS} rows.").into(),
);
} else {
let length = size.min(PREVIEW_BYTES).to_string();
let preview = ctx
.get(&with_query(
ctx.ws("job_helpers/load_file_preview"),
&[
("file_key", Some(key)),
("storage", storage),
("file_size_in_bytes", Some(&size.to_string())),
("read_bytes_from", Some("0")),
("read_bytes_length", Some(&length)),
],
))
.await?;
match preview["content"].as_str() {
Some(content) => {
out.insert("content_type".into(), preview["content_type"].clone());
out.insert("preview".into(), content.into());
if size > PREVIEW_BYTES {
out.insert(
"note".into(),
format!("Only the first {PREVIEW_BYTES} bytes.").into(),
);
}
}
None => {
out.insert("preview_unavailable".into(), preview["msg"].clone());
}
}
}
Ok(pretty(&Value::Object(out)))
}
fn in_storage(storage: Option<&str>) -> String {
storage
.map(|s| format!(" in storage `{s}`"))
.unwrap_or_default()
}
async fn delete_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let key = str_arg(args, "s3")?;
let storage = storage_arg(args);
ctx.delete(&with_query(
ctx.ws("job_helpers/delete_s3_file"),
&[("file_key", Some(key)), ("storage", storage)],
))
.await?;
Ok(format!("Deleted `{key}`{}.", in_storage(storage)))
}
async fn move_s3_file(ctx: &Ctx<'_>, args: &Value) -> ToolResult {
let key = str_arg(args, "s3")?;
let dest = str_arg(args, "dest_s3")?;
if key == dest {
return Err("`dest_s3` is the file's current key: nothing to move".to_string());
}
let storage = storage_arg(args);
// A GET on the browser's own route, which writes.
ctx.get(&with_query(
ctx.ws("job_helpers/move_s3_file"),
&[
("src_file_key", Some(key)),
("dest_file_key", Some(dest)),
("storage", storage),
],
))
.await?;
Ok(format!("Moved `{key}` to `{dest}`{}.", in_storage(storage)))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// Each listed file must stay an S3 object the session's other tools take as is.
#[test]
fn listing_returns_s3_objects() {
let page = json!({
"restricted_access": false,
"folders": [{ "prefix": "charts/2026/", "name": "2026" }],
"files": [{ "key": "charts/a.csv", "name": "a.csv", "size": 34, "last_modified": "2026-11-25T15:11:58Z" }],
"next_page_token": "sealed"
});
assert_eq!(
listing(Some("archive"), "charts/", &page, None, false),
json!({
"storage": "archive",
"prefix": "charts/",
"folders": ["charts/2026/"],
"files": [{ "s3": "charts/a.csv", "storage": "archive", "size": 34, "last_modified": "2026-11-25T15:11:58Z" }],
"next_page_token": "sealed"
})
);
assert_eq!(folder_prefix(Some("/charts")), "charts/");
assert_eq!(folder_prefix(Some("/")), "");
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ fn tool_title(name: &str) -> String {
let words: Vec<String> = name
.split('_')
.map(|word| match word {
"db" | "sql" | "json" => word.to_uppercase(),
"db" | "sql" | "json" | "s3" => word.to_uppercase(),
_ => word.to_string(),
})
.collect();
@@ -130,6 +130,7 @@ import { isMentionContext, isUserContextPath, type ContextElement } from '../con
import { getDatatableTools } from '../datatableTools'
import { getDatatableMigrationTools } from '../datatableMigrationTools'
import { getDucklakeTools } from '../ducklakeTools'
import { getStorageTools } from '../storageTools'
import { fileTools } from '../files/fileTools'
import type { AttachedFilesStore } from '../files/attachedFiles.svelte'
import { artifactTools } from '../artifacts/artifactTools'
@@ -4851,6 +4852,8 @@ export const globalTools: SessionTool<{}>[] = [
...getDatatableMigrationTools(),
// Workspace DuckLake: pipeline storage prerequisite, and declared measures
...getDucklakeTools(),
// Workspace object storage, as the S3 file browser reaches it
...getStorageTools(),
// Read-only tools over files the user attached to the conversation
...fileTools,
...workspaceSettingsTools
@@ -0,0 +1,147 @@
import { z } from 'zod'
import { createToolDef } from './shared'
import { NONE, type SessionTool } from './sessionCapabilities'
import { runOnServer } from './global/backendSessionTools'
/**
* The workspace's object storage (its large file storage and secondary storages), through the
* endpoints of the S3 file browser, so the session sees and changes exactly what the user could
* there. Run on the server, as every GLOBAL tool is, so MCP clients get the same tools.
*/
const storageArg = z
.string()
.optional()
.describe(
"Name of a secondary storage, as list_s3_files returns them in `storages`. Omit for the workspace's primary storage."
)
const listS3FilesSchema = z.object({
storage: storageArg,
prefix: z
.string()
.optional()
.describe('Folder to list, e.g. `charts/` or `charts/2026/`. Omit for the root.'),
page_token: z
.string()
.optional()
.describe('The `next_page_token` of a previous call, for the rest of the same folder.'),
max_keys: z
.number()
.int()
.min(1)
.max(500)
.optional()
.describe('Max number of folders and files to return. Defaults to 100.')
})
const s3KeyArg = z
.string()
.describe('Key of the file, as list_s3_files returns it in `s3`, e.g. `charts/sales.csv`.')
const readS3FileSchema = z.object({ s3: s3KeyArg, storage: storageArg })
const deleteS3FileSchema = z.object({ s3: s3KeyArg, storage: storageArg })
const moveS3FileSchema = z.object({
s3: s3KeyArg,
dest_s3: z.string().describe('New key of the file, in the same storage.'),
storage: storageArg
})
const listS3FilesToolDef = createToolDef(
listS3FilesSchema,
'list_s3_files',
"List one folder of the workspace's object storage (S3, Azure Blob or GCS): its subfolders, and its files with size and last modified time. Call again with a subfolder as `prefix` to go deeper, and with `next_page_token` for the rest of a long folder. A call at the root also returns `storages`, the names of the workspace's secondary storages. Each file is an S3 object `{ s3, storage? }`, the shape a script or flow takes as an S3 file input. Only what the user may list is returned, as in the workspace's S3 file browser."
)
const readS3FileToolDef = createToolDef(
readS3FileSchema,
'read_s3_file',
"Read a file in the workspace's object storage: its size and last modified time, and a preview of its content: the start of a text, JSON or CSV file, or the first rows of a Parquet file. Other files, such as images, return their metadata only."
)
const deleteS3FileToolDef = createToolDef(
deleteS3FileSchema,
'delete_s3_file',
"Delete one file from the workspace's object storage. It cannot be undone: call it only when the user asked for that file to be deleted."
)
const moveS3FileToolDef = createToolDef(
moveS3FileSchema,
'move_s3_file',
"Move or rename one file within one storage of the workspace's object storage: it is copied to `dest_s3`, then the original is deleted. A file already at `dest_s3` is replaced."
)
function storageLabel(storage: string | undefined) {
return storage ? ` in ${storage}` : ''
}
/** The workspace object storage tools, for registration in global mode. */
export function getStorageTools(): SessionTool<{}>[] {
return [
{
requires: NONE,
def: listS3FilesToolDef,
planModeSafe: true,
lookup: true,
showDetails: true,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const { prefix, storage } = listS3FilesSchema.parse(args)
const where = (prefix || 'the root') + storageLabel(storage)
toolCallbacks.setToolStatus(toolId, { content: `Listing ${where}...` })
const { text } = await runOnServer('list_s3_files', workspace, args)
const listed = JSON.parse(text)
toolCallbacks.setToolStatus(toolId, {
content: `Listed ${listed.folders.length} folder(s), ${listed.files.length} file(s) in ${where}`,
result: listed
})
return text
}
},
{
requires: NONE,
def: readS3FileToolDef,
planModeSafe: true,
lookup: true,
showDetails: true,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const { s3, storage } = readS3FileSchema.parse(args)
toolCallbacks.setToolStatus(toolId, { content: `Reading ${s3}${storageLabel(storage)}...` })
const { text } = await runOnServer('read_s3_file', workspace, args)
toolCallbacks.setToolStatus(toolId, {
content: `Read ${s3}${storageLabel(storage)}`,
result: JSON.parse(text)
})
return text
}
},
{
requires: NONE,
def: deleteS3FileToolDef,
requiresConfirmation: true,
confirmAction: 'delete',
confirmationMessage: (args: any) =>
`Delete ${args?.s3 ?? 'file'}${storageLabel(args?.storage)} from object storage`,
queuedLabel: (args) => `Delete ${args?.s3 ?? 'file'}`,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const { s3, storage } = deleteS3FileSchema.parse(args)
toolCallbacks.setToolStatus(toolId, { content: `Deleting ${s3}...` })
const { text } = await runOnServer('delete_s3_file', workspace, args)
toolCallbacks.setToolStatus(toolId, { content: `Deleted ${s3}${storageLabel(storage)}` })
return text
}
},
{
requires: NONE,
def: moveS3FileToolDef,
requiresConfirmation: true,
confirmAction: 'apply',
confirmationMessage: (args: any) =>
`Move ${args?.s3 ?? 'file'} to ${args?.dest_s3 ?? '…'}${storageLabel(args?.storage)}`,
queuedLabel: (args) => `Move ${args?.s3 ?? 'file'}`,
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
const { s3, dest_s3 } = moveS3FileSchema.parse(args)
toolCallbacks.setToolStatus(toolId, { content: `Moving ${s3}...` })
const { text } = await runOnServer('move_s3_file', workspace, args)
toolCallbacks.setToolStatus(toolId, { content: `Moved ${s3} to ${dest_s3}` })
return text
}
}
]
}