feat(asset-read): expose read_asset on MCP and the CLI

Enable the mcp and cli surfaces for read_asset and get_asset_render.

- MCP: add per-Operation tool extensions. The read presenter attaches up
  to 8 images (2 MB each) inline, lists image links, supports
  inlineImages: false, and tells the model to call get_asset_render when
  a render is pending. Storage keys are stripped from the result.
- CLI: generated commands can flatten object inputs into prefixed flags
  (cli.flatten) and omit fields (cli.omit); add per-command extensions.
  New `read` and `render` commands print image links, download them with
  --out, and support --no-wait with a printed `render <taskId>` hint.
- Round frame timestamps in labels to 3 decimals.
This commit is contained in:
yiling
2026-10-26 15:33:37 +08:00
parent 4581058e0d
commit 4fc8476b0f
26 changed files with 1158 additions and 46 deletions
+6 -2
View File
@@ -234,7 +234,11 @@ An **Operation** is a capability agents can use, defined once and exposed automa
- **Register** the definition in `packages/operations/src/registry.ts` and the implementation in `packages/core/src/operations/registry.ts`. A definition without an implementation fails typecheck.
- **Run** Operations only through `runOperation(op, { userId, via, agentId? }, input)`. `via` (`api`, `agent`, `mcp`, `cli`) is recorded in audit logs.
- **Tests**: real-database tests per Operation covering success, permission denial (no side effects), and audit entries.
- **Agent presentation**: by default an agent tool returns the Operation output as JSON. To add agent-only parameters or render output differently (e.g. image blocks), register an `AgentToolExtension` in `packages/agent/src/operation-extensions/`.
- **CLI spec**: object input fields must be listed in `cli.flatten` (one flag per sub-field, e.g. `{ videoConfig: 'video' }` → `--video-start`) or in `cli.omit` (optional fields the CLI doesn't expose).
- **Surface presentation**: by default each surface shows the Operation output as JSON. To add surface-only parameters or render output differently, add an extension for that surface:
- agent: `AgentToolExtension` in `packages/agent/src/operation-extensions/` (e.g. image blocks);
- MCP: `McpToolExtension` in `packages/api/src/mcp-extensions/` (`structuredContent` must still match the output schema);
- CLI: `CliCommandExtension` in `apps/cli/src/operations/extensions/` (local I/O such as downloads).
### Asset Readers
@@ -245,7 +249,7 @@ To add a reader:
1. Add its kind to `READER_KINDS` and its options to `readerOptionSchemas` in `packages/operations/src/asset/read-asset.ts` (one optional `<name>Config` field on `read_asset`).
2. Implement `AssetReader` (`matches`, synchronous `validate`, `plan`, and `collect` if `plan` can return `render`), and add it to `readers` in `packages/core/src/asset-read/registry.ts`. Order matters: the first matching reader wins. A declared kind without a reader fails typecheck.
3. `plan` returns either `ready` with the result, or `render` with a workflow task spec and optional `context`. The pipeline stores the request on the task payload (`assetRead`), so `collect` and `get_asset_render` work across restarts and instances.
4. Use `badRequest(...)` for invalid input. Return storage keys in `ReadResult`; the pipeline turns them into short-lived links (and only gives keys to Shumai's built-in agent).
4. Use `badRequest(...)` for invalid input. Return storage keys in `ReadResult`; the pipeline turns them into short-lived links. Keys only go to server-side presenters (agent, MCP), which must not pass them on to clients.
5. Add reader unit tests (`readers.test.ts`), pipeline cases in `asset-read.test.ts`, and a workflow E2E case if it renders.
## Frontend Architecture
+2
View File
@@ -10,6 +10,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
* **mcp**: Shumai now has a built-in MCP server, so external AI agents such as Claude Code, Cursor, or Kiro can browse projects and create, rename, move, or delete folders and files with your API token and permissions
* **agent**: The built-in agent can now list the projects you have access to, so it can find a project's root folder on its own. Team owners can turn this off per agent like other tools
* **mcp**: External AI agents connected to Shumai's MCP server can now look at your files: images, video frames, PDF pages, 3D model views, and text files. Images are attached so the AI can see them, along with links that stay valid for about an hour
* **cli**: New `shumai-cli read` command shows an image, video frames, PDF pages, a 3D model view, or the text of a file, and `--out` downloads the images into a folder. If rendering takes a while, `shumai-cli render <taskId>` picks up the result later
### Fixed
+34 -2
View File
@@ -2,7 +2,7 @@
A Command Line Interface (CLI) tool for interacting with your Shumai instance.
The CLI allows you to view projects, list folder contents, create folders, upload files and directories, and create new versions of existing files directly from the terminal.
The CLI allows you to view projects, list folder contents, create folders, upload files and directories, create new versions of existing files, and look at images, video frames, and document pages directly from the terminal.
---
@@ -135,6 +135,38 @@ shumai-cli delete <assetId>
shumai-cli rm <assetId>
```
#### 9. Read an Asset
Look at a file: an image, video frames, PDF pages, a 3D model view, or the text of a text file. Prints a summary and a link to each image (links are valid for about an hour), or the file's text.
```bash
# An image, or the 4-view overview of a 3D model
shumai-cli read <assetId>
# 5 evenly spaced frames between 0s and 30s of a video, downloaded into ./frames
shumai-cli read <assetId> --video-start 0 --video-end 30 --video-count 5 --out frames
# Pages 1 to 3 of a PDF, or the text of a text file
shumai-cli read <assetId> --doc-mode pages --doc-start-page 1 --doc-end-page 3
shumai-cli read <assetId> --doc-mode text
# A 3D model at 90°
shumai-cli read <assetId> --degree 90
```
- **Options:**
- `--video-start <s>`, `--video-end <s>`, `--video-count <n>`: Video frames to extract (up to 20).
- `--doc-mode <pages|text>`, `--doc-start-page <n>`, `--doc-end-page <n>`: PDF pages to render (up to 20), or `text` to read a text file.
- `--degree <deg>`: 3D model angle (0, 15, 30, ..., 345).
- `--annotation-id <id>`: Draw a comment's markup on the image, frame, or page.
- `-o`, `--out <dir>`: Download the images into a folder and print their paths. With `--json`, each image also gets a `path`.
- `--max-wait-seconds <s>`, `--no-wait`: Rendering frames or pages can take a while. `read` waits up to 2 minutes; use these to wait less or return right away. If the render isn't done, `read` prints the `render` command to run next.
#### 10. Get a Render
Get the result of a `read` that was still rendering. Takes the same `--out`, `--max-wait-seconds`, and `--no-wait` options as `read`.
```bash
shumai-cli render <taskId> --out frames
```
---
## Development
@@ -147,4 +179,4 @@ bun run apps/cli/src/index.ts project ls
### Adding Commands
Most commands are generated from the shared Operation definitions in `packages/operations` (see "Operations" in `AGENTS.md`). An Operation with the `cli` surface and a `cli` spec becomes a command automatically, with arguments, options, and help text derived from its input schema. It is also available to Shumai's built-in agent and MCP server. Only commands that stream local files (`upload`, `create-version`) are written by hand in `src/program.ts`.
Most commands are generated from the shared Operation definitions in `packages/operations` (see "Operations" in `AGENTS.md`). An Operation with the `cli` surface and a `cli` spec becomes a command automatically, with arguments, options, and help text derived from its input schema. It is also available to Shumai's built-in agent and MCP server. Behavior that needs the local machine, such as downloading files, goes in a CLI extension in `src/operations/extensions/` (extra options, input mapping, and output). Only commands that stream local files (`upload`, `create-version`) are written by hand in `src/program.ts`.
@@ -0,0 +1,8 @@
import type { CliCommandExtension } from '../generate'
import { getAssetRenderExtension, readAssetExtension } from './read-asset'
/** CLI-specific behavior for generated commands, by Operation name. */
export const cliExtensions: ReadonlyMap<string, CliCommandExtension> = new Map([
['read_asset', readAssetExtension],
['get_asset_render', getAssetRenderExtension],
])
@@ -0,0 +1,98 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import * as path from 'node:path'
import type { AssetReadOutput } from '@shumai/operations'
import { CliError } from '../errors'
import { downloadImages, imageFileName, readAssetExtension } from './read-asset'
const output: AssetReadOutput = {
status: 'ready',
summary: 'Rendered 2 page(s) of "deck.pdf" (Pages 1 to 2):',
asset: { id: 'doc-1', name: 'deck.pdf', kind: 'document', mediaType: 'application/pdf' },
details: [],
images: [
{ label: 'Page 1', mimeType: 'image/webp', url: 'https://files.example/p1' },
{ label: 'Page 2', mimeType: 'image/png', url: 'https://files.example/p2' },
],
}
describe('read / render CLI extension', () => {
let dir: string
let written: string
beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), 'shumai-cli-read-'))
written = ''
vi.stubGlobal(
'fetch',
vi.fn(async (url: string) => new Response(`bytes of ${url}`, { status: 200 })),
)
})
afterEach(async () => {
vi.unstubAllGlobals()
await rm(dir, { recursive: true, force: true })
})
const o = () => ({ out: { write: (s: string) => void (written += s) }, isTty: true, columns: 80 })
it('names files after the asset, position, and label', () => {
expect(imageFileName('vid-1', 0, { label: 'Frame at 2.5s', mimeType: 'image/webp' })).toBe(
'vid-1-1-frame-at-2.5s.webp',
)
expect(imageFileName('m-1', 3, { label: 'View at 90°', mimeType: 'image/jpeg' })).toBe(
'm-1-4-view-at-90.jpg',
)
})
it('downloads every image with --out and prints the saved paths', async () => {
const out = path.join(dir, 'pages')
await readAssetExtension.present(output, { opts: { out }, json: false, output: o() })
const first = path.join(out, 'doc-1-1-page-1.webp')
const second = path.join(out, 'doc-1-2-page-2.png')
expect(await readFile(first, 'utf8')).toBe('bytes of https://files.example/p1')
expect(await readFile(second, 'utf8')).toBe('bytes of https://files.example/p2')
expect(written).toBe(`${output.summary}\n- Page 1: ${first}\n- Page 2: ${second}\n`)
})
it('adds the saved path to each image in --json mode', async () => {
await readAssetExtension.present(output, { opts: { out: dir }, json: true, output: o() })
const printed = JSON.parse(written) as { images: Array<{ path: string }> }
expect(printed.images.map((i) => i.path)).toEqual([
path.join(dir, 'doc-1-1-page-1.webp'),
path.join(dir, 'doc-1-2-page-2.png'),
])
})
it('fails clearly when a download fails', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('gone', { status: 403 })),
)
await expect(downloadImages(output, dir)).rejects.toThrow(
new CliError('Failed to download "Page 1" (status 403).'),
)
})
it('does not download anything for a pending render', async () => {
await readAssetExtension.present(
{ ...output, status: 'pending', images: [], taskId: 't-1', retryAfterSeconds: 5 },
{ opts: { out: dir }, json: false, output: o() },
)
expect(fetch).not.toHaveBeenCalled()
expect(written).toContain(`shumai-cli render t-1 --out ${JSON.stringify(dir)}`)
})
it('maps --no-wait to maxWaitSeconds 0', () => {
expect(readAssetExtension.toInput!({ assetId: 'a' }, { wait: false })).toEqual({
assetId: 'a',
maxWaitSeconds: 0,
})
expect(readAssetExtension.toInput!({ assetId: 'a' }, { wait: true })).toEqual({
assetId: 'a',
})
})
})
@@ -0,0 +1,126 @@
import { mkdir, writeFile } from 'node:fs/promises'
import * as path from 'node:path'
import { Option } from 'commander'
import type { AssetReadOutput } from '@shumai/operations'
import { CliError } from '../errors'
import type { CliCommandExtension } from '../generate'
import type { Output } from '../render'
const EXTENSIONS: Record<string, string> = {
'image/webp': 'webp',
'image/png': 'png',
'image/jpeg': 'jpg',
'image/gif': 'gif',
'image/avif': 'avif',
}
function slug(value: string): string {
return (
value
.toLowerCase()
.replace(/[^a-z0-9.]+/g, '-')
.replace(/^-+|-+$/g, '') || 'image'
)
}
/** File name for the n-th image of a read, e.g. `01ABC-1-frame-at-2s.webp`. */
export function imageFileName(
assetId: string,
index: number,
image: AssetReadOutput['images'][number],
): string {
const ext = EXTENSIONS[image.mimeType] ?? image.mimeType.split('/')[1] ?? 'bin'
return `${assetId}-${index + 1}-${slug(image.label).replace(/\.+$/, '')}.${ext}`
}
/** Downloads every image of a ready read into `dir`; returns the saved paths in order. */
export async function downloadImages(output: AssetReadOutput, dir: string): Promise<string[]> {
await mkdir(dir, { recursive: true })
const saved: string[] = []
for (const [index, image] of output.images.entries()) {
if (!image.url) {
throw new CliError(`No download link was returned for "${image.label}".`)
}
let res: Response
try {
res = await fetch(image.url)
} catch (err) {
throw new CliError(
`Failed to download "${image.label}": ${err instanceof Error ? err.message : String(err)}`,
)
}
if (!res.ok) {
throw new CliError(`Failed to download "${image.label}" (status ${res.status}).`)
}
const filePath = path.join(dir, imageFileName(output.asset.id, index, image))
await writeFile(filePath, Buffer.from(await res.arrayBuffer()))
saved.push(filePath)
}
return saved
}
function renderCommand(taskId: string, out: unknown): string {
const outArg = typeof out === 'string' ? ` --out ${JSON.stringify(out)}` : ''
return `shumai-cli render ${taskId}${outArg}`
}
function writeReady(output: AssetReadOutput, paths: string[] | null, o: Output): void {
const lines = [output.summary, ...output.details]
output.images.forEach((image, i) => {
lines.push(`- ${image.label}: ${paths ? paths[i] : (image.url ?? '')}`)
})
o.out.write(`${lines.join('\n')}\n`)
if (output.text) {
o.out.write(`\n${output.text.content}`)
if (!output.text.content.endsWith('\n')) o.out.write('\n')
if (output.text.truncated) {
o.out.write(
`\n[Content truncated: showing the first part of a ${output.text.size}-byte file.]\n`,
)
}
}
}
/**
* `read` and `render`: images are printed as links (valid for about an hour) or downloaded
* with `--out`; a render that takes longer than the wait prints the `render` command to run.
*/
function readExtension(noWaitHelp: string): CliCommandExtension {
return {
options: () => [
new Option('-o, --out <dir>', 'Download the images into this folder and print their paths.'),
new Option('--no-wait', noWaitHelp),
],
toInput: (input, opts) => (opts.wait === false ? { ...input, maxWaitSeconds: 0 } : input),
async present(raw, { opts, json, output: o }) {
const output = raw as AssetReadOutput
if (output.status === 'pending') {
if (json) {
o.out.write(`${JSON.stringify(output, null, 2)}\n`)
return
}
o.out.write(
`${output.summary}\nRun this to get the result: ${renderCommand(output.taskId ?? '', opts.out)}\n`,
)
return
}
const paths = typeof opts.out === 'string' ? await downloadImages(output, opts.out) : null
if (json) {
const images = output.images.map((image, i) =>
paths ? { ...image, path: paths[i] } : image,
)
o.out.write(`${JSON.stringify({ ...output, images }, null, 2)}\n`)
return
}
writeReady(output, paths, o)
},
}
}
export const readAssetExtension = readExtension(
'Return right away with a task ID if the asset needs rendering.',
)
export const getAssetRenderExtension = readExtension(
'Check once and return right away if the render is still running.',
)
+105 -15
View File
@@ -5,11 +5,29 @@ import type { CallOperation } from './call-operation'
import { CliError } from './errors'
import { renderOutput, type Output } from './render'
/**
* CLI-specific behavior for one Operation's command, for things a definition can't describe
* (it must stay free of I/O): extra options, input mapping, and output that downloads files.
*/
export interface CliCommandExtension {
/** Extra options only the CLI has; their values are passed to `toInput` and `present`. */
options?(): Option[]
/** Adjust the Operation input using the command's options. */
toInput?(input: Record<string, unknown>, opts: Record<string, unknown>): Record<string, unknown>
/** Writes the output, including in `--json` mode. Replaces the default rendering. */
present(
output: unknown,
ctx: { opts: Record<string, unknown>; json: boolean; output: Output },
): Promise<void>
}
export interface GenerateDeps {
callOperation: CallOperation
output: Output
/** Whether destructive Operations are allowed (SHUMAI_ALLOW_DELETE). */
allowDestructive: () => boolean
/** CLI extensions by Operation name. */
extensions?: ReadonlyMap<string, CliCommandExtension>
}
type FieldKind =
@@ -40,7 +58,14 @@ function unwrap(schema: z.ZodType): z.ZodType {
}
function describeField(definition: AnyOperationDefinition, name: string): FieldInfo {
const schema = definition.input.shape[name] as z.ZodType
return describeSchema(definition, name, definition.input.shape[name] as z.ZodType)
}
function describeSchema(
definition: AnyOperationDefinition,
name: string,
schema: z.ZodType,
): FieldInfo {
const base = unwrap(schema)
let kind: FieldKind
if (base instanceof z.ZodNumber) kind = { type: 'number' }
@@ -59,6 +84,28 @@ function describeField(definition: AnyOperationDefinition, name: string): FieldI
}
}
/**
* Input errors name the input path (e.g. `videoConfig.end`). For flattened fields, name the
* flag the user typed instead (e.g. `--video-end`).
*/
function formatInputError(
error: z.ZodError,
options: ReadonlyArray<{ path: [string] | [string, string]; option: Option }>,
): string {
const flagFor = (path: PropertyKey[]): string | undefined =>
options.find((o) => o.path.length === 2 && o.path[0] === path[0] && o.path[1] === path[1])
?.option.long
if (!error.issues.some((issue) => flagFor(issue.path))) {
return z.prettifyError(error)
}
return error.issues
.map((issue) => {
const flag = flagFor(issue.path)
return flag ? `✖ ${flag}: ${issue.message}` : z.prettifyError(new z.ZodError([issue]))
})
.join('\n')
}
function parseNumber(value: string): number {
const parsed = Number(value)
if (value.trim() === '' || Number.isNaN(parsed)) {
@@ -105,27 +152,59 @@ export function registerOperationCommands(
}
const positionalNames = new Set(positional.map((f) => f.name))
const options: Array<{ field: FieldInfo; option: Option }> = []
for (const name of Object.keys(definition.input.shape)) {
if (positionalNames.has(name)) continue
const field = describeField(definition, name)
const spellings = cli.flags?.[name] ?? [`--${kebab(name)}`]
const omitted = new Set<string>(cli.omit ?? [])
const flatten = (cli.flatten ?? {}) as Record<string, string | undefined>
// `path` is where the value goes in the input: `[field]` or `[field, subField]`.
const options: Array<{ path: [string] | [string, string]; option: Option }> = []
const addOption = (
path: [string] | [string, string],
field: FieldInfo,
spellings: readonly string[],
) => {
const valueHint =
field.kind.type === 'boolean'
? ''
: field.kind.type === 'array'
? ` <${name}...>`
: ` <${name}>`
? ` <${field.name}...>`
: ` <${field.name}>`
const option = new Option(`${spellings.join(', ')}${valueHint}`, field.description)
if (field.kind.type === 'number') option.argParser(parseNumber)
if (field.kind.type === 'enum') option.choices(field.kind.values)
if (field.required) option.makeOptionMandatory()
cmd.addOption(option)
options.push({ path, option })
return option
}
for (const name of Object.keys(definition.input.shape)) {
if (positionalNames.has(name) || omitted.has(name)) continue
const prefix = flatten[name]
if (prefix !== undefined) {
const schema = definition.input.shape[name] as z.ZodType
const base = unwrap(schema)
if (!(base instanceof z.ZodObject)) {
throw new Error(`${definition.name}.${name}: only object fields can be flattened`)
}
const parentRequired = !schema.safeParse(undefined).success
for (const [subName, subSchema] of Object.entries(base.shape)) {
const field = describeSchema(definition, `${name}.${subName}`, subSchema as z.ZodType)
field.name = subName
// Sub-fields are only mandatory when the object itself is.
field.required = parentRequired && field.required
const flag = prefix ? `--${prefix}-${kebab(subName)}` : `--${kebab(subName)}`
addOption([name, subName], field, [flag])
}
continue
}
const field = describeField(definition, name)
const option = addOption([name], field, cli.flags?.[name] ?? [`--${kebab(name)}`])
const cliDefault = (cli.defaults as Record<string, unknown> | undefined)?.[name]
if (cliDefault !== undefined) option.default(cliDefault)
cmd.addOption(option)
options.push({ field, option })
}
const extension = deps.extensions?.get(definition.name)
for (const option of extension?.options?.() ?? []) cmd.addOption(option)
cmd.action(async (...args: unknown[]) => {
const command = args[args.length - 1] as Command
const input: Record<string, unknown> = { ...cli.defaults }
@@ -133,9 +212,15 @@ export function registerOperationCommands(
if (args[i] !== undefined) input[field.name] = args[i]
})
const opts = command.opts()
for (const { field, option } of options) {
for (const { path, option } of options) {
const value = opts[option.attributeName()]
if (value !== undefined) input[field.name] = value
if (value === undefined) continue
if (path.length === 1) {
input[path[0]] = value
} else {
const parent = (input[path[0]] ?? {}) as Record<string, unknown>
input[path[0]] = { ...parent, [path[1]]: value }
}
}
if (definition.annotations.destructive && !deps.allowDestructive()) {
@@ -144,13 +229,18 @@ export function registerOperationCommands(
)
}
const parsed = definition.input.safeParse(input)
const parsed = definition.input.safeParse(
extension?.toInput ? extension.toInput(input, opts) : input,
)
if (!parsed.success) {
throw new CliError(z.prettifyError(parsed.error))
throw new CliError(formatInputError(parsed.error, options))
}
const output = await deps.callOperation(definition, parsed.data)
if (command.optsWithGlobals().json) {
const json = Boolean(command.optsWithGlobals().json)
if (extension) {
await extension.present(output, { opts, json, output: deps.output })
} else if (json) {
deps.output.out.write(`${JSON.stringify(output, null, 2)}\n`)
} else {
renderOutput(definition, output, deps.output)
+194
View File
@@ -3,6 +3,8 @@ import type { Command } from 'commander'
import {
createFolder,
deleteAsset,
getAssetRender,
readAsset,
listAssets,
listProjects,
moveAssets,
@@ -39,6 +41,27 @@ function setup() {
const folder = { id: 'f-1', name: 'Renders', type: 'folder', size: 0, projectId: 'p-1' }
const frames = {
status: 'ready',
summary: 'Extracted 2 frame(s) from "clip.mp4" (0s - 4s):',
asset: { id: 'vid-1', name: 'clip.mp4', kind: 'video', mediaType: 'video/mp4' },
details: [],
images: [
{ label: 'Frame at 0s', mimeType: 'image/webp', url: 'https://files.example/0.webp' },
{ label: 'Frame at 4s', mimeType: 'image/webp', url: 'https://files.example/4.webp' },
],
}
const pendingRead = {
status: 'pending',
summary: 'Rendering is still in progress for "clip.mp4".',
asset: frames.asset,
details: [],
images: [],
taskId: 'task-1',
retryAfterSeconds: 5,
}
describe('shumai-cli', () => {
const originalAllowDelete = process.env.SHUMAI_ALLOW_DELETE
@@ -251,6 +274,151 @@ describe('shumai-cli', () => {
})
})
describe('read', () => {
it('maps flattened reader flags onto the config objects and prints image links', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue(frames)
await cli.run(
'read',
'vid-1',
'--video-start',
'0',
'--video-end',
'4',
'--video-count',
'2',
'--annotation-id',
'c-1',
)
expect(cli.callOperation).toHaveBeenCalledWith(readAsset, {
assetId: 'vid-1',
annotationId: 'c-1',
videoConfig: { start: 0, end: 4, count: 2 },
})
expect(cli.stdout()).toBe(
[
'Extracted 2 frame(s) from "clip.mp4" (0s - 4s):',
'- Frame at 0s: https://files.example/0.webp',
'- Frame at 4s: https://files.example/4.webp',
'',
].join('\n'),
)
})
it.each([
[
['--doc-mode', 'pages', '--doc-start-page', '1', '--doc-end-page', '3'],
{ docConfig: { mode: 'pages', startPage: 1, endPage: 3 } },
],
[['--doc-mode', 'text'], { docConfig: { mode: 'text' } }],
[['--degree', '90'], { config3d: { degree: 90 } }],
[[], {}],
])('reads with %j', async (flags, config) => {
const cli = setup()
cli.callOperation.mockResolvedValue({ ...frames, images: [] })
await cli.run('read', 'a-1', ...flags)
expect(cli.callOperation).toHaveBeenCalledWith(readAsset, { assetId: 'a-1', ...config })
})
it('names the flag that is missing from a reader config', async () => {
const cli = setup()
const error = await cli
.run('read', 'vid-1', '--video-start', '0', '--video-count', '2')
.catch((err: unknown) => err)
expect(formatCliError(error)).toContain('--video-end')
expect(cli.callOperation).not.toHaveBeenCalled()
})
it('prints text content after the summary', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue({
...frames,
summary: 'Document "notes.md" (ID: d-1):',
images: [],
text: {
content: '# Notes\nhello',
truncated: true,
size: 90000,
mimeType: 'text/markdown',
},
})
await cli.run('read', 'd-1', '--doc-mode', 'text')
expect(cli.stdout()).toBe(
'Document "notes.md" (ID: d-1):\n\n# Notes\nhello\n\n[Content truncated: showing the first part of a 90000-byte file.]\n',
)
})
it('returns right away with --no-wait and prints the render command', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue(pendingRead)
await cli.run(
'read',
'vid-1',
'--video-start',
'0',
'--video-end',
'4',
'--video-count',
'2',
'--no-wait',
'--out',
'frames',
)
expect(cli.callOperation).toHaveBeenCalledWith(readAsset, {
assetId: 'vid-1',
videoConfig: { start: 0, end: 4, count: 2 },
maxWaitSeconds: 0,
})
expect(cli.stdout()).toBe(
'Rendering is still in progress for "clip.mp4".\nRun this to get the result: shumai-cli render task-1 --out "frames"\n',
)
})
it('prints the raw output with --json', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue(frames)
await cli.run('--json', 'read', 'vid-1')
expect(JSON.parse(cli.stdout())).toEqual(frames)
})
})
describe('render', () => {
it('fetches a pending render by task ID', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue(frames)
await cli.run('render', 'task-1')
expect(cli.callOperation).toHaveBeenCalledWith(getAssetRender, { taskId: 'task-1' })
expect(cli.stdout()).toContain('- Frame at 4s: https://files.example/4.webp')
})
it('checks once with --no-wait', async () => {
const cli = setup()
cli.callOperation.mockResolvedValue(pendingRead)
await cli.run('render', 'task-1', '--no-wait')
expect(cli.callOperation).toHaveBeenCalledWith(getAssetRender, {
taskId: 'task-1',
maxWaitSeconds: 0,
})
expect(cli.stdout()).toContain('Run this to get the result: shumai-cli render task-1\n')
})
})
describe('--json', () => {
it('prints the raw Operation output', async () => {
const cli = setup()
@@ -312,6 +480,8 @@ describe('shumai-cli', () => {
'rename',
'move|mv',
'delete|rm',
'read',
'render',
'upload',
'create-version',
]) {
@@ -333,6 +503,30 @@ describe('shumai-cli', () => {
expect(help).toContain('(default: 200)')
expect(help).toContain('List the files and folders inside a parent folder.')
})
it('documents flattened reader options for read', async () => {
const cli = setup()
await expect(cli.run('read', '--help')).rejects.toThrow()
const help = cli.stdout()
for (const flag of [
'--video-start <start>',
'--video-end <end>',
'--video-count <count>',
'--doc-mode <mode>',
'--doc-start-page <startPage>',
'--doc-end-page <endPage>',
'--degree <degree>',
'--annotation-id <annotationId>',
'-o, --out <dir>',
'--no-wait',
]) {
expect(help).toContain(flag)
}
expect(help).not.toContain('--include-content')
expect(help).not.toContain('--image')
})
})
})
+3 -1
View File
@@ -3,6 +3,7 @@ import { operationDefinitions } from '@shumai/operations'
import { createVersion } from './commands/create-version'
import { upload } from './commands/upload'
import { callOperation, type CallOperation } from './operations/call-operation'
import { cliExtensions } from './operations/extensions'
import { registerOperationCommands } from './operations/generate'
import type { Output } from './operations/render'
@@ -18,7 +19,7 @@ function isDeleteAllowed(): boolean {
/**
* Builds the `shumai-cli` program. Operation commands (ls, mkdir, rename, move, delete,
* project ls, ...) are generated from `@shumai/operations`; upload and create-version stream
* read, render, project ls, ...) are generated from `@shumai/operations`; upload and create-version stream
* local files and are defined here.
*/
export function createProgram(options: ProgramOptions = {}): Command {
@@ -37,6 +38,7 @@ export function createProgram(options: ProgramOptions = {}): Command {
columns: process.stdout.columns || 80,
},
allowDestructive: isDeleteAllowed,
extensions: cliExtensions,
})
program
+17 -9
View File
@@ -3,7 +3,7 @@ title: Shumai MCP Server
description: Let external AI agents such as Claude Code, Cursor, or Kiro work with your Shumai projects.
---
Shumai includes a built-in [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. Any MCP-compatible agent can connect to it and browse projects, create folders, and organize assets on your behalf, using the same tools as Shumai's built-in agent.
Shumai includes a built-in [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server. Any MCP-compatible agent can connect to it and browse projects, look at images, videos, and documents, create folders, and organize assets on your behalf, using the same tools as Shumai's built-in agent.
<Note>
This page is about connecting **external agents to Shumai**. To connect Shumai's own agents to
@@ -58,14 +58,22 @@ claude mcp add --transport http shumai https://<your-shumai-host>/api/mcp \
## Available Tools
| Tool | What it does |
| --------------- | ----------------------------------------------------------------------------------------------------- |
| `list_projects` | Lists the projects you can access, with each project's root folder. |
| `list_assets` | Lists files and folders in a folder, page by page. |
| `create_folder` | Creates a folder. |
| `rename_asset` | Renames a file or folder. |
| `move_assets` | Moves files or folders into another folder. |
| `delete_asset` | Moves a file or folder to the project trash. Marked as destructive so clients can ask you to confirm. |
| Tool | What it does |
| ------------------ | ----------------------------------------------------------------------------------------------------- |
| `list_projects` | Lists the projects you can access, with each project's root folder. |
| `list_assets` | Lists files and folders in a folder, page by page. |
| `create_folder` | Creates a folder. |
| `rename_asset` | Renames a file or folder. |
| `move_assets` | Moves files or folders into another folder. |
| `delete_asset` | Moves a file or folder to the project trash. Marked as destructive so clients can ask you to confirm. |
| `read_asset` | Looks at a file: an image, video frames, PDF pages, a 3D model view, or the text of a text file. |
| `get_asset_render` | Gets the result of a `read_asset` call that was still rendering. |
### Reading Files
`read_asset` attaches the images to the result so the AI model can see them: up to 8 images per call, each up to 2 MB. Any other images are listed as links only. Every result also includes a link to each image, valid for about an hour. Pass `inlineImages: false` to get links only, for example when your client can't show images.
Rendering video frames or PDF pages can take a while. If it takes longer than about 20 seconds, `read_asset` returns `status: "pending"` with a `taskId`, and the model calls `get_asset_render` with that `taskId` to get the result. Only the user who started the read can get its result.
Every call runs with your permissions: for example, a **Reviewer** can list assets but cannot create or rename them. Actions are recorded in the team audit log and attributed to you, marked as coming from MCP.
+10
View File
@@ -0,0 +1,10 @@
import { getAssetRenderMcpExtension, readAssetMcpExtension } from './read-asset'
import type { McpToolExtension } from './types'
export type { McpToolExtension } from './types'
/** MCP-specific presentation for Operations, by Operation name. */
export const mcpExtensions: ReadonlyMap<string, McpToolExtension> = new Map([
['read_asset', readAssetMcpExtension],
['get_asset_render', getAssetRenderMcpExtension],
])
@@ -0,0 +1,116 @@
import { z } from 'zod'
import type { CallToolResult, ImageContent } from '@modelcontextprotocol/server'
import type { AssetReadOutput } from '@shumai/operations'
import { storageBucket } from '@shumai/core/src/asset-read'
import { logger } from '@shumai/core/src/logger'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
import type { McpToolExtension } from './types'
/** Most images attached inline to one result; the rest are links only. */
export const MAX_INLINE_IMAGES = 8
/** Largest image attached inline; bigger ones are links only. */
export const MAX_INLINE_IMAGE_BYTES = 2 * 1024 * 1024
const extraInput = z.object({
inlineImages: z
.boolean()
.optional()
.describe(
`Attach images to the result so you can see them (default true, at most ${MAX_INLINE_IMAGES} images of up to 2 MB). Set to false to only get links.`,
),
})
/**
* Removes storage keys and the source file link: the Operation returns keys to server-side
* presenters so they can attach image bytes, but MCP clients only get image links.
*/
export function toClientOutput(output: AssetReadOutput): AssetReadOutput {
const images = output.images.map(({ label, mimeType, url }) => ({ label, mimeType, url }))
if (!output.text) return { ...output, images }
const { content, truncated, size, mimeType } = output.text
return { ...output, images, text: { content, truncated, size, mimeType } }
}
async function loadImage(key: string, fallbackMime: string): Promise<ImageContent | 'too_large'> {
const bucket = storageBucket()
const size = await s3Service.getObjectSize(bucket, key)
if (size > MAX_INLINE_IMAGE_BYTES) return 'too_large'
const { buffer, contentType } = await s3Service.getObject(bucket, key)
const mimeType =
contentType && contentType !== 'application/octet-stream'
? contentType
: getFileMimeType(buffer, key, fallbackMime)
return { type: 'image', data: buffer.toString('base64'), mimeType }
}
/** Renders a `read_asset` / `get_asset_render` output as MCP content: text, then images. */
export async function presentReadForMcp(
raw: unknown,
extra: Record<string, unknown>,
): Promise<CallToolResult> {
const output = raw as AssetReadOutput
const client = toClientOutput(output)
const structuredContent = client as unknown as Record<string, unknown>
if (output.status === 'pending') {
const retry = output.retryAfterSeconds ?? 5
return {
content: [
{
type: 'text',
text: `${output.summary} Call get_asset_render with taskId "${output.taskId}" in about ${retry} seconds to get the result.`,
},
],
structuredContent,
}
}
const inline = extra.inlineImages !== false
const images: ImageContent[] = []
const lines = [output.summary, ...output.details]
for (const [index, image] of output.images.entries()) {
let note = ''
if (inline) {
if (index >= MAX_INLINE_IMAGES) {
note = ` (not attached: only the first ${MAX_INLINE_IMAGES} images are attached)`
} else if (image.key) {
try {
const loaded = await loadImage(image.key, image.mimeType)
if (loaded === 'too_large') {
note = ' (not attached: larger than 2 MB)'
} else {
images.push(loaded)
note = ` (attached as image ${images.length})`
}
} catch (err) {
logger.warn({ err, key: image.key }, 'Failed to attach image to MCP read result')
note = ' (not attached: could not load the image)'
}
}
}
lines.push(`- ${image.label}${note}: ${image.url ?? ''}`)
}
if (output.images.length > 0) {
lines.push('Image links expire in about an hour.')
}
let text = lines.join('\n')
if (output.text) {
text += `\n\n${output.text.content}`
if (output.text.truncated) {
text += `\n\n[Content truncated: showing the first part of a ${output.text.size}-byte file.]`
}
}
return { content: [{ type: 'text', text }, ...images], structuredContent }
}
export const readAssetMcpExtension: McpToolExtension = {
extraInput,
present: presentReadForMcp,
}
export const getAssetRenderMcpExtension: McpToolExtension = {
extraInput,
present: presentReadForMcp,
}
+14
View File
@@ -0,0 +1,14 @@
import type { z } from 'zod'
import type { CallToolResult } from '@modelcontextprotocol/server'
/**
* MCP-specific presentation for an Operation. By default an MCP tool returns the output as
* JSON text plus `structuredContent`; an extension can add MCP-only arguments and build the
* result content itself (e.g. image blocks). `structuredContent` must still match the
* Operation's output schema.
*/
export interface McpToolExtension {
/** Extra arguments only MCP clients see; they are removed before the Operation runs. */
extraInput?: z.ZodObject
present(output: unknown, extra: Record<string, unknown>): Promise<CallToolResult>
}
+110 -1
View File
@@ -1,8 +1,12 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { prisma, type User } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { projectService } from '@shumai/core/src/project/project'
import { s3Service } from '@shumai/core/src/s3/s3'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import app from './index'
@@ -158,4 +162,109 @@ describe('MCP server and /api/ops (integration)', () => {
expect(res.status).toBe(401)
})
describe('read_asset', () => {
const bucket = 'shumai-test-mcp-read'
const originalBucket = process.env.S3_BUCKET
const png = fs.readFileSync(
path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../e2e/fixtures/small.png'),
)
let imageId: string
beforeAll(() => {
process.env.S3_BUCKET = bucket
})
afterAll(async () => {
if (originalBucket === undefined) delete process.env.S3_BUCKET
else process.env.S3_BUCKET = originalBucket
await s3Service.deletePrefix(bucket, '').catch(() => undefined)
})
beforeEach(async () => {
const key = `projects/${projectId}/photo.png`
await s3Service.putObject(bucket, key, png, png.length, 'image/png')
const storageKey = await prisma.storageKey.create({ data: { key } })
imageId = (
await prisma.asset.create({
data: {
name: 'photo.png',
type: 'file',
status: 'uploaded',
mediaType: 'image/png',
projectId,
parentId: rootFolderId,
storageKeyId: storageKey.id,
media: { proxyType: 'image' } as unknown as PrismaJson.MediaInfo,
},
})
).id
})
it('shows a reviewer the image inline, with links but no storage keys', async () => {
const client = await connect(reviewerToken)
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: imageId } })
expect(result.isError).toBeFalsy()
const content = result.content as Array<{ type: string; data?: string; text?: string }>
expect(content[0].text).toContain(`Image asset "photo.png" (ID: ${imageId}):`)
expect(content[1]).toEqual({
type: 'image',
data: png.toString('base64'),
mimeType: 'image/png',
})
const output = result.structuredContent as { images: Array<Record<string, unknown>> }
expect(output.images).toEqual([
{ label: 'Image', mimeType: 'image/png', url: expect.any(String) },
])
expect(JSON.stringify(result)).not.toContain('"key"')
})
it('serves read and render to the CLI with links only', async () => {
const headers = {
Authorization: `Bearer ${reviewerToken}`,
'Content-Type': 'application/json',
'x-shumai-client': 'cli',
}
const read = await app.request('/api/ops/read_asset', {
method: 'POST',
headers,
body: JSON.stringify({ assetId: imageId }),
})
expect(read.status).toBe(200)
const output = (await read.json()) as { status: string; images: Array<{ url: string }> }
expect(output.status).toBe('ready')
expect(output.images).toEqual([
{ label: 'Image', mimeType: 'image/png', url: expect.any(String) },
])
// The link is served by the API itself with local storage
const link = new URL(output.images[0].url)
const image = await app.request(link.pathname + link.search)
expect(image.status).toBe(200)
expect(Buffer.from(await image.arrayBuffer()).equals(png)).toBe(true)
const render = await app.request('/api/ops/get_asset_render', {
method: 'POST',
headers,
body: JSON.stringify({ taskId: 'not-a-task' }),
})
expect(render.status).toBe(404)
expect(await render.json()).toEqual({ error: 'Render not found' })
})
it('does not let users outside the project read', async () => {
const outsider = await prisma.user.create({
data: { name: 'Outsider', email: 'mcp-outsider@test.com', password: 'pw' },
})
const token = (await apiTokenService.createToken(outsider.id, 'mcp')).token
const client = await connect(token)
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: imageId } })
expect(result.isError).toBe(true)
})
})
})
+197 -2
View File
@@ -3,7 +3,9 @@ import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { teamService } from '@shumai/core/src/team/team'
import { createFolderOp, runOperation } from '@shumai/core/src/operations'
import { s3Service } from '@shumai/core/src/s3/s3'
import { createFolderOp, readAssetOp, runOperation } from '@shumai/core/src/operations'
import { MAX_INLINE_IMAGE_BYTES, MAX_INLINE_IMAGES } from './mcp-extensions/read-asset'
import mcpServerRoute, { MCP_SERVER_INSTRUCTIONS } from './mcp-server'
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
@@ -53,9 +55,11 @@ describe('MCP server', () => {
expect(tools.map((t) => t.name).sort()).toEqual([
'create_folder',
'delete_asset',
'get_asset_render',
'list_assets',
'list_projects',
'move_assets',
'read_asset',
'rename_asset',
])
@@ -83,7 +87,7 @@ describe('MCP server', () => {
it('does not expose agent-only capabilities', async () => {
const names = (await client.listTools()).tools.map((t) => t.name)
for (const agentOnly of ['bash', 'read_skill', 'read_asset', 'download_asset', 'mcp']) {
for (const agentOnly of ['bash', 'read_skill', 'download_asset', 'mcp']) {
expect(names).not.toContain(agentOnly)
}
})
@@ -141,4 +145,195 @@ describe('MCP server', () => {
expect(result.content).toEqual([{ type: 'text', text: 'System is in read-only mode' }])
expect(runOperation).not.toHaveBeenCalled()
})
describe('read_asset', () => {
const frame = (n: number) => ({
label: `Frame at ${n}s`,
mimeType: 'image/webp',
url: `https://files.example/${n}.webp`,
key: `shots/${n}.webp`,
})
const ready = (count: number) => ({
status: 'ready',
summary: `Extracted ${count} frame(s) from "clip.mp4" (0s - 10s):`,
asset: { id: 'vid-1', name: 'clip.mp4', kind: 'video', mediaType: 'video/mp4' },
details: [],
images: Array.from({ length: count }, (_, i) => frame(i)),
})
beforeEach(() => {
vi.spyOn(s3Service, 'getObjectSize').mockResolvedValue(1000)
vi.spyOn(s3Service, 'getObject').mockImplementation(async (_bucket, key) => ({
buffer: Buffer.from(`bytes of ${key}`),
contentType: 'image/webp',
}))
})
it('advertises inlineImages and keeps it out of the Operation input', async () => {
const { tools } = await client.listTools()
const read = tools.find((t) => t.name === 'read_asset')!
expect(read.inputSchema.properties).toHaveProperty('inlineImages')
expect(read.inputSchema.properties).toHaveProperty('videoConfig')
expect(read.annotations).toMatchObject({ readOnlyHint: true, destructiveHint: false })
expect(
tools.find((t) => t.name === 'get_asset_render')!.inputSchema.properties,
).toHaveProperty('inlineImages')
vi.mocked(runOperation).mockResolvedValue(ready(1))
await client.callTool({
name: 'read_asset',
arguments: {
assetId: 'vid-1',
videoConfig: { start: 0, end: 10, count: 1 },
inlineImages: true,
},
})
expect(runOperation).toHaveBeenCalledWith(
readAssetOp,
{ userId: 'user1', via: 'mcp' },
{ assetId: 'vid-1', videoConfig: { start: 0, end: 10, count: 1 } },
)
})
it('attaches images inline and returns links without storage keys', async () => {
vi.mocked(runOperation).mockResolvedValue(ready(2))
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: 'vid-1' } })
expect(result.isError).toBeFalsy()
expect(result.content).toEqual([
{
type: 'text',
text: [
'Extracted 2 frame(s) from "clip.mp4" (0s - 10s):',
'- Frame at 0s (attached as image 1): https://files.example/0.webp',
'- Frame at 1s (attached as image 2): https://files.example/1.webp',
'Image links expire in about an hour.',
].join('\n'),
},
{
type: 'image',
data: Buffer.from('bytes of shots/0.webp').toString('base64'),
mimeType: 'image/webp',
},
{
type: 'image',
data: Buffer.from('bytes of shots/1.webp').toString('base64'),
mimeType: 'image/webp',
},
])
expect(result.structuredContent).toEqual({
...ready(2),
images: [0, 1].map((n) => ({
label: `Frame at ${n}s`,
mimeType: 'image/webp',
url: `https://files.example/${n}.webp`,
})),
})
expect(JSON.stringify(result)).not.toContain('shots/0.webp"')
})
it(`attaches at most ${MAX_INLINE_IMAGES} images and skips large ones`, async () => {
vi.mocked(runOperation).mockResolvedValue(ready(10))
vi.mocked(s3Service.getObjectSize).mockImplementation(async (_bucket, key) =>
key === 'shots/2.webp' ? MAX_INLINE_IMAGE_BYTES + 1 : 1000,
)
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: 'vid-1' } })
const content = result.content as Array<{ type: string; text?: string }>
expect(content.filter((c) => c.type === 'image')).toHaveLength(MAX_INLINE_IMAGES - 1)
const text = content[0].text!
expect(text).toContain(
'- Frame at 2s (not attached: larger than 2 MB): https://files.example/2.webp',
)
expect(text).toContain(
`- Frame at 8s (not attached: only the first ${MAX_INLINE_IMAGES} images are attached)`,
)
expect(s3Service.getObject).not.toHaveBeenCalledWith(expect.anything(), 'shots/2.webp')
expect(s3Service.getObject).not.toHaveBeenCalledWith(expect.anything(), 'shots/8.webp')
})
it('returns links only with inlineImages false', async () => {
vi.mocked(runOperation).mockResolvedValue(ready(2))
const result = await client.callTool({
name: 'read_asset',
arguments: { assetId: 'vid-1', inlineImages: false },
})
expect(result.content).toEqual([
{
type: 'text',
text: [
'Extracted 2 frame(s) from "clip.mp4" (0s - 10s):',
'- Frame at 0s: https://files.example/0.webp',
'- Frame at 1s: https://files.example/1.webp',
'Image links expire in about an hour.',
].join('\n'),
},
])
expect(s3Service.getObject).not.toHaveBeenCalled()
})
it('includes text content without the source storage key', async () => {
vi.mocked(runOperation).mockResolvedValue({
...ready(0),
summary: 'Document "notes.md" (ID: d-1):',
text: {
content: '# Notes',
truncated: false,
size: 7,
mimeType: 'text/markdown',
key: 'raw/notes.md',
url: 'https://files.example/notes.md?download',
},
})
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: 'd-1' } })
expect(result.content).toEqual([
{ type: 'text', text: 'Document "notes.md" (ID: d-1):\n\n# Notes' },
])
expect(result.structuredContent).toMatchObject({
text: { content: '# Notes', truncated: false, size: 7, mimeType: 'text/markdown' },
})
expect((result.structuredContent as { text: object }).text).not.toHaveProperty('key')
expect((result.structuredContent as { text: object }).text).not.toHaveProperty('url')
})
it('tells the model to call get_asset_render when rendering is pending', async () => {
vi.mocked(runOperation).mockResolvedValue({
...ready(0),
status: 'pending',
summary: 'Rendering is still in progress for "clip.mp4".',
taskId: 'task-1',
retryAfterSeconds: 5,
})
const result = await client.callTool({
name: 'read_asset',
arguments: { assetId: 'vid-1', videoConfig: { start: 0, end: 10, count: 5 } },
})
expect(result.content).toEqual([
{
type: 'text',
text: 'Rendering is still in progress for "clip.mp4". Call get_asset_render with taskId "task-1" in about 5 seconds to get the result.',
},
])
expect(result.structuredContent).toMatchObject({ status: 'pending', taskId: 'task-1' })
})
it('reports read errors as tool errors', async () => {
vi.mocked(runOperation).mockRejectedValue(
new HTTPException(400, { message: 'videoConfig with start, end, and count is required' }),
)
const result = await client.callTool({ name: 'read_asset', arguments: { assetId: 'vid-1' } })
expect(result.isError).toBe(true)
expect(result.content).toEqual([
{ type: 'text', text: 'videoConfig with start, end, and count is required' },
])
})
})
})
+33 -2
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import { createMcpHandler, McpServer, type CallToolResult } from '@modelcontextprotocol/server'
import type { Prisma } from '@shumai/db'
import { getOperationsForSurface, runOperation, type Operation } from '@shumai/core/src/operations'
import { mcpExtensions, type McpToolExtension } from './mcp-extensions'
import { assertWritableInDemoMode, describeOperationError } from './operation-support'
type User = Prisma.UserGetPayload<Record<string, never>>
@@ -14,16 +15,43 @@ export const MCP_SERVER_INSTRUCTIONS = [
'Start with list_projects to find a project and its rootFolderId, then pass folder IDs as',
'`parent` to list_assets and create_folder. list_assets is paginated: when',
'pageInfo.hasNextPage is true, call it again with after = pageInfo.endCursor.',
'Use read_asset to look at a file (image, video frames, PDF pages, 3D views, or text);',
'if it returns status "pending", call get_asset_render with its taskId.',
].join(' ')
/** Separate MCP-only arguments (declared by an extension) from the Operation input. */
function splitArgs(
extension: McpToolExtension | undefined,
args: unknown,
): { input: unknown; extra: Record<string, unknown> } {
if (!extension?.extraInput || !args || typeof args !== 'object') {
return { input: args, extra: {} }
}
const extraKeys = new Set(Object.keys(extension.extraInput.shape))
const input: Record<string, unknown> = {}
const extra: Record<string, unknown> = {}
for (const [key, value] of Object.entries(args)) {
;(extraKeys.has(key) ? extra : input)[key] = value
}
return { input, extra }
}
async function callOperation(
op: Operation,
userId: string,
args: unknown,
): Promise<CallToolResult> {
const extension = mcpExtensions.get(op.definition.name)
try {
await assertWritableInDemoMode(op, userId)
const output = (await runOperation(op, { userId, via: 'mcp' }, args)) as Record<string, unknown>
const { input, extra } = splitArgs(extension, args)
const output = (await runOperation(op, { userId, via: 'mcp' }, input)) as Record<
string,
unknown
>
if (extension) {
return await extension.present(output, extra)
}
return {
content: [{ type: 'text', text: JSON.stringify(output) }],
structuredContent: output,
@@ -44,12 +72,15 @@ export function buildMcpServer(userId: string): McpServer {
)
for (const op of getOperationsForSurface('mcp')) {
const { definition } = op
const extension = mcpExtensions.get(definition.name)
server.registerTool(
definition.name,
{
title: definition.title,
description: definition.description,
inputSchema: definition.input,
inputSchema: extension?.extraInput
? definition.input.extend(extension.extraInput.shape)
: definition.input,
outputSchema: definition.output,
annotations: {
title: definition.title,
@@ -547,7 +547,8 @@ describe('read_asset and get_asset_render Operations', () => {
it.each([
['agent', true],
['mcp', false],
// The MCP presenter attaches image bytes, then strips the keys (packages/api)
['mcp', true],
['cli', false],
['api', false],
] as const)('via %s includes storage keys: %s', async (via, includesKey) => {
+2 -2
View File
@@ -265,8 +265,8 @@ export class AssetReadService {
export const assetReadService = new AssetReadService()
/**
* Converts a read outcome into the Operation output. Storage keys are included only for
* Shumai's built-in agent; every image gets a short-lived link.
* Converts a read outcome into the Operation output. Every image gets a short-lived link;
* storage keys (and the source file link) only when the result is presented server-side.
*/
export async function toAssetReadOutput(
outcome: ReadOutcome,
+1
View File
@@ -10,4 +10,5 @@ export {
export { resolveAnnotationsById } from './annotations'
export { findReader, getReader, readers } from './registry'
export { isPlainTextAsset, MAX_TEXT_BYTES, MAX_TEXT_LINES } from './readers/document'
export { storageBucket } from './types'
export type { AssetReader, ReadableAsset, ReadImage, ReadPlan, ReadResult } from './types'
@@ -122,6 +122,16 @@ describe('videoReader', () => {
})
})
it('rounds frame timestamps in labels', () => {
const result = videoReader.collect!(
video,
{ start: 0, end: 8, count: 3 },
{ screenshots: [{ key: 's/1.webp', timestamp: 2.6666666666666665 }] },
{},
)
expect(result.images[0].label).toBe('Frame at 2.667s')
})
it('fails when the render produced no frames', () => {
expect(() =>
videoReader.collect!(video, { start: 0, end: 1, count: 1 }, { screenshots: [] }, {}),
@@ -67,7 +67,8 @@ export const videoReader: AssetReader<'video'> = {
details: [],
images: screenshots.map((shot) => ({
key: shot.key,
label: `Frame at ${shot.timestamp}s`,
// Evenly spaced timestamps can be long fractions (2.6666666666666665)
label: `Frame at ${Number(shot.timestamp.toFixed(3))}s`,
mimeType: getFileMimeType(null, shot.key, 'image/webp'),
})),
}
@@ -13,6 +13,13 @@ export const READ_WAIT_BUDGET_MS: Record<Via, number> = {
api: 20_000,
}
/**
* Surfaces whose results are presented on the server (agent tools, MCP tool results). They get
* storage keys so the presenter can attach image bytes; the MCP presenter strips the keys
* before anything leaves the server. CLI and REST callers only get links.
*/
const SERVER_PRESENTED: ReadonlySet<Via> = new Set(['agent', 'mcp'])
/** `maxWaitSeconds` can only shorten the surface budget. */
export function waitBudgetMs(via: Via, maxWaitSeconds: number | undefined): number {
const budget = READ_WAIT_BUDGET_MS[via]
@@ -27,7 +34,7 @@ export const readAssetOp = implementOperation(readAsset, {
const outcome = await assetReadService.read({ kind: 'user', userId: ctx.userId }, request, {
waitBudgetMs: waitBudgetMs(ctx.via, maxWaitSeconds),
})
return toAssetReadOutput(outcome, { includeKeys: ctx.via === 'agent' })
return toAssetReadOutput(outcome, { includeKeys: SERVER_PRESENTED.has(ctx.via) })
},
})
@@ -38,6 +45,6 @@ export const getAssetRenderOp = implementOperation(getAssetRender, {
const outcome = await assetReadService.getRender(ctx.userId, input.taskId, {
waitBudgetMs: waitBudgetMs(ctx.via, input.maxWaitSeconds),
})
return toAssetReadOutput(outcome, { includeKeys: ctx.via === 'agent' })
return toAssetReadOutput(outcome, { includeKeys: SERVER_PRESENTED.has(ctx.via) })
},
})
+18 -3
View File
@@ -23,7 +23,7 @@ export const readerOptionSchemas = {
.nullable()
.optional()
.describe(
'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave null/omitted to view the 4-view composite overview.',
'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave it out to view the 4-view composite overview.',
),
})
.describe(
@@ -156,8 +156,18 @@ export const readAsset = defineOperation({
maxWaitSeconds,
}),
output: assetReadOutputSchema,
surfaces: ['agent'],
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: true, destructive: false },
cli: {
command: ['read'],
description:
'Read an asset: show an image, video frames, PDF pages, a 3D view, or the text of a text file. ' +
'Prints links to the images; use --out to download them.',
positional: ['assetId'],
flatten: { videoConfig: 'video', docConfig: 'doc', config3d: '', imageConfig: 'image' },
// Text content is cheap to print; describing without content is only useful to agents.
omit: ['includeContent'],
},
})
export const getAssetRender = defineOperation({
@@ -171,6 +181,11 @@ export const getAssetRender = defineOperation({
maxWaitSeconds,
}),
output: assetReadOutputSchema,
surfaces: ['agent'],
surfaces: ['agent', 'mcp', 'cli'],
annotations: { readOnly: true, destructive: false, idempotent: true },
cli: {
command: ['render'],
description: 'Get the result of a `read` that is still rendering, by its task ID.',
positional: ['taskId'],
},
})
+20
View File
@@ -81,4 +81,24 @@ describe('defineOperation', () => {
}),
).toThrow('unknown input "extra"')
})
it('validates flattened and omitted cli fields', () => {
const input = z.object({
id: z.string(),
config: z.object({ size: z.number() }).optional(),
verbose: z.boolean().optional(),
})
const withCli = (cli: Record<string, unknown>) =>
defineOperation({
...baseDefinition(),
input,
surfaces: ['cli'],
cli: { command: ['get'], ...cli },
} as OperationDefinition<string, typeof input>)
expect(() => withCli({ flatten: { config: 'config' }, omit: ['verbose'] })).not.toThrow()
expect(() => withCli({ flatten: { nope: 'n' } })).toThrow('unknown input "nope"')
expect(() => withCli({ omit: ['gone'] })).toThrow('unknown input "gone"')
expect(() => withCli({ omit: ['id'] })).toThrow('omits required input "id"')
})
})
+15
View File
@@ -37,6 +37,14 @@ export interface CliSpec<TInput, TOutput> {
positional?: readonly (keyof TInput & string)[]
/** Flag spellings for input fields, e.g. `{ parent: ['-p', '--parent'] }`. */
flags?: { readonly [K in keyof TInput & string]?: readonly string[] }
/**
* Object input fields exposed as one flag per sub-field, keyed by flag prefix: with
* `{ videoConfig: 'video' }`, `videoConfig.start` becomes `--video-start`. An empty prefix
* uses the sub-field name alone (`--degree`). Object fields must be flattened or omitted.
*/
flatten?: { readonly [K in keyof TInput & string]?: string }
/** Input fields the CLI does not expose. They must be optional. */
omit?: readonly (keyof TInput & string)[]
/** Input values the CLI uses when the user does not pass them (e.g. a larger page size). */
defaults?: { readonly [K in keyof TInput & string]?: TInput[K] }
/** Human-friendly rendering of the output; the CLI falls back to a generic renderer. */
@@ -101,12 +109,19 @@ export function defineOperation<
...(def.cli.positional ?? []),
...Object.keys(def.cli.flags ?? {}),
...Object.keys(def.cli.defaults ?? {}),
...Object.keys(def.cli.flatten ?? {}),
...(def.cli.omit ?? []),
]
for (const field of referenced) {
if (!fields.has(field)) {
throw new Error(`Operation "${def.name}" cli spec references unknown input "${field}"`)
}
}
for (const field of def.cli.omit ?? []) {
if (!(def.input.shape[field] as z.ZodType).safeParse(undefined).success) {
throw new Error(`Operation "${def.name}" cli spec omits required input "${field}"`)
}
}
}
return Object.freeze(def)
}
+6 -3
View File
@@ -36,6 +36,10 @@ describe('operation registry', () => {
it('filters definitions by surface', () => {
const cli = getOperationDefinitionsForSurface('cli').map((d) => d.name)
expect(cli).toContain('list_assets')
expect(cli).toContain('read_asset')
expect(getOperationDefinitionsForSurface('mcp').map((d) => d.name)).toContain(
'get_asset_render',
)
})
it('annotates only delete_asset as destructive', () => {
@@ -78,9 +82,8 @@ describe('operation registry', () => {
['rename_asset', ['rename']],
['move_assets', ['move', 'mv']],
['delete_asset', ['delete', 'rm']],
// CLI commands for reading assets arrive with the CLI surface
['read_asset', []],
['get_asset_render', []],
['read_asset', ['read']],
['get_asset_render', ['render']],
])
})