mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-04 15:14:10 +00:00
feat: expose read_asset and download_asset on MCP and the CLI (#499)
* 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. * fix(mcp): make tool input schemas portable to single-type dialects Nullable inputs were emitted as `type: ["number", "null"]` (or a `null` anyOf branch), which clients that map tool schemas onto an OpenAPI-style subset (e.g. Gemini function declarations) may reject. - Make read_asset's startPage, endPage, and degree optional instead of nullable. - Move null handling into a shared dropNullOptionals helper in @shumai/operations that also strips nulls inside nested config objects. The agent uses it, and the MCP server applies it before the SDK validates arguments, so models that send null keep working. - Test that no Operation input schema (and no listed MCP tool) uses a nullable type. * feat(asset-download): share download_asset across agent, MCP and CLI Turn the agent-only download_asset tool into an Operation on all three surfaces. - download_asset takes up to 50 file or version stack IDs and returns presigned links. proxy (default true) picks the web preview when there is one, as the agent always did; proxy: false returns the original. Folders are rejected. Read is checked on every ID before anything runs. - Agent: an extension saves the files into the .pi sandbox and keeps the agent-only storage key mode (e.g. frames from read_asset). Agent tool extensions gain description, parameterOverrides and intercept. - CLI: `shumai-cli download <assetId...> [--out <dir>] [--original]` streams files to disk without overwriting existing names. - read_asset's unsupported-type error now names the right way to download on each surface (download_asset, or `shumai-cli download`). - Add the Download Asset toggle to agent settings.
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
import { z } from 'zod'
|
||||
import { defineOperation } from '../define'
|
||||
|
||||
/** Most assets one download call accepts. */
|
||||
export const MAX_DOWNLOAD_ASSETS = 50
|
||||
|
||||
const downloadFileSchema = z.object({
|
||||
assetId: z
|
||||
.string()
|
||||
.describe('The asset this file belongs to (the latest version for a version stack).'),
|
||||
name: z.string().describe('File name to save it as.'),
|
||||
kind: z
|
||||
.enum(['proxy', 'original'])
|
||||
.describe('"proxy" is the web preview version; "original" is the uploaded file.'),
|
||||
size: z.number().describe('Size in bytes.'),
|
||||
mimeType: z.string(),
|
||||
url: z.string().describe('Short-lived download link (about 1 hour).'),
|
||||
/** Storage key; only returned to Shumai's built-in agent. */
|
||||
key: z.string().optional(),
|
||||
})
|
||||
|
||||
export const downloadAssetOutputSchema = z.object({
|
||||
files: z.array(downloadFileSchema),
|
||||
})
|
||||
export type DownloadAssetOutput = z.infer<typeof downloadAssetOutputSchema>
|
||||
|
||||
export const downloadAsset = defineOperation({
|
||||
name: 'download_asset',
|
||||
title: 'Download Asset',
|
||||
description:
|
||||
`Gets download links for up to ${MAX_DOWNLOAD_ASSETS} files. ` +
|
||||
'By default it returns the web preview version (proxy) when there is one, e.g. the transcoded video or the web image, which is smaller and easier to process; set proxy to false for the original uploaded file. ' +
|
||||
'Files without a preview (e.g. audio, archives, text) always return the original. ' +
|
||||
'A version stack returns its latest version. Folders are not supported: download the files inside them instead. ' +
|
||||
'Links expire after about an hour.',
|
||||
input: z.object({
|
||||
assetIds: z
|
||||
.array(z.string().min(1))
|
||||
.min(1)
|
||||
.max(MAX_DOWNLOAD_ASSETS)
|
||||
.describe(`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}).`),
|
||||
proxy: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
'Download the web preview version when there is one (default true). Set to false for the original uploaded file.',
|
||||
),
|
||||
}),
|
||||
output: downloadAssetOutputSchema,
|
||||
surfaces: ['agent', 'mcp', 'cli'],
|
||||
annotations: { readOnly: true, destructive: false, idempotent: true },
|
||||
cli: {
|
||||
command: ['download'],
|
||||
description:
|
||||
'Download files into a folder (the current folder by default). Saves the web preview version when there is one; use --original for the uploaded file.',
|
||||
positional: ['assetIds'],
|
||||
// The CLI exposes `--original` instead of a `--proxy` flag that is on by default.
|
||||
omit: ['proxy'],
|
||||
},
|
||||
})
|
||||
@@ -20,10 +20,9 @@ export const readerOptionSchemas = {
|
||||
degree: z
|
||||
.number()
|
||||
.int()
|
||||
.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(
|
||||
@@ -57,12 +56,10 @@ export const readerOptionSchemas = {
|
||||
),
|
||||
startPage: z
|
||||
.number()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe('Start page number (1-based, required when mode="pages"; omit for "text").'),
|
||||
endPage: z
|
||||
.number()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
`End page number (1-based, max ${MAX_RENDER_ITEMS} pages per call, required when mode="pages"; omit for "text").`,
|
||||
@@ -156,8 +153,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 +178,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'],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -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"')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
export * from './define'
|
||||
export * from './schemas'
|
||||
export * from './registry'
|
||||
export { dropNullOptionals } from './null-optionals'
|
||||
export { createFolder } from './asset/create-folder'
|
||||
export { deleteAsset } from './asset/delete-asset'
|
||||
export { listAssets } from './asset/list-assets'
|
||||
export { moveAssets } from './asset/move-assets'
|
||||
export { renameAsset } from './asset/rename-asset'
|
||||
export * from './asset/read-asset'
|
||||
export * from './asset/download-asset'
|
||||
export { listProjects } from './project/list-projects'
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { z } from 'zod'
|
||||
import { dropNullOptionals } from './null-optionals'
|
||||
|
||||
const schema = z.object({
|
||||
id: z.string(),
|
||||
note: z.string().optional(),
|
||||
config: z
|
||||
.object({
|
||||
mode: z.enum(['a', 'b']),
|
||||
start: z.number().optional(),
|
||||
})
|
||||
.optional(),
|
||||
tags: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
describe('dropNullOptionals', () => {
|
||||
it('drops nulls for optional fields, including inside nested objects', () => {
|
||||
expect(
|
||||
dropNullOptionals(schema, {
|
||||
id: 'x',
|
||||
note: null,
|
||||
config: { mode: 'a', start: null },
|
||||
tags: null,
|
||||
}),
|
||||
).toEqual({ id: 'x', config: { mode: 'a' } })
|
||||
})
|
||||
|
||||
it('drops a null nested object when the object is optional', () => {
|
||||
expect(dropNullOptionals(schema, { id: 'x', config: null })).toEqual({ id: 'x' })
|
||||
})
|
||||
|
||||
it('keeps nulls for required fields so validation still fails', () => {
|
||||
const cleaned = dropNullOptionals(schema, { id: null, config: { mode: null } })
|
||||
expect(cleaned).toEqual({ id: null, config: { mode: null } })
|
||||
expect(schema.safeParse(cleaned).success).toBe(false)
|
||||
})
|
||||
|
||||
it('leaves unknown keys and non-object values alone', () => {
|
||||
expect(dropNullOptionals(schema, { id: 'x', other: null })).toEqual({ id: 'x', other: null })
|
||||
expect(dropNullOptionals(schema, null)).toBeNull()
|
||||
expect(dropNullOptionals(schema, ['a'])).toEqual(['a'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Strip optional/default wrappers to reach an object schema, if the field is one. */
|
||||
function objectSchemaOf(schema: z.ZodType): z.ZodObject | undefined {
|
||||
let current: z.ZodType = schema
|
||||
while (current instanceof z.ZodOptional || current instanceof z.ZodDefault) {
|
||||
current = current.unwrap() as z.ZodType
|
||||
}
|
||||
return current instanceof z.ZodObject ? current : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Models often send `null` for optional parameters they don't want to set, including inside
|
||||
* nested config objects. Operation inputs are optional rather than nullable (nullable types
|
||||
* don't translate to every model's tool format), so drop those nulls before validating:
|
||||
* they are treated as omitted. Nulls for required fields are kept and still fail validation.
|
||||
*/
|
||||
export function dropNullOptionals(schema: z.ZodObject, value: unknown): unknown {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return value
|
||||
const shape = schema.shape as Record<string, z.ZodType>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, field] of Object.entries(value)) {
|
||||
const fieldSchema = shape[key]
|
||||
if (field === null && fieldSchema?.safeParse(undefined).success) continue
|
||||
const nested = fieldSchema && objectSchemaOf(fieldSchema)
|
||||
result[key] = nested ? dropNullOptionals(nested, field) : field
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -19,6 +19,7 @@ describe('operation registry', () => {
|
||||
expect(operationDefinitions.map((d) => d.name).sort()).toEqual([
|
||||
'create_folder',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
@@ -36,6 +37,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', () => {
|
||||
@@ -43,6 +48,7 @@ describe('operation registry', () => {
|
||||
expect(destructive.map((d) => d.name)).toEqual(['delete_asset'])
|
||||
const readOnly = operationDefinitions.filter((d) => d.annotations.readOnly)
|
||||
expect(readOnly.map((d) => d.name).sort()).toEqual([
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
@@ -66,6 +72,18 @@ describe('operation registry', () => {
|
||||
},
|
||||
)
|
||||
|
||||
it.each(operationDefinitions.map((d) => [d.name, d] as const))(
|
||||
'%s input schema has no nullable types',
|
||||
(_name, definition) => {
|
||||
// Tool formats like Gemini's function declarations (an OpenAPI subset) can't express
|
||||
// `type: [..., "null"]` or a `null` branch, so inputs use optional fields instead.
|
||||
// Surfaces drop nulls that models send for optional fields (dropNullOptionals).
|
||||
const schema = JSON.stringify(z.toJSONSchema(definition.input, { io: 'input' }))
|
||||
expect(schema).not.toMatch(/"type":\[/)
|
||||
expect(schema).not.toContain('"type":"null"')
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps legacy CLI invocations mapped', () => {
|
||||
const commands = operationDefinitions.map((d) => [
|
||||
d.name,
|
||||
@@ -78,9 +96,9 @@ 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']],
|
||||
['download_asset', ['download']],
|
||||
])
|
||||
})
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createFolder } from './asset/create-folder'
|
||||
import { deleteAsset } from './asset/delete-asset'
|
||||
import { downloadAsset } from './asset/download-asset'
|
||||
import { listAssets } from './asset/list-assets'
|
||||
import { moveAssets } from './asset/move-assets'
|
||||
import { getAssetRender, readAsset } from './asset/read-asset'
|
||||
@@ -20,6 +21,7 @@ export const operationDefinitions = [
|
||||
deleteAsset,
|
||||
readAsset,
|
||||
getAssetRender,
|
||||
downloadAsset,
|
||||
] as const
|
||||
|
||||
export type RegisteredOperationDefinition = (typeof operationDefinitions)[number]
|
||||
|
||||
Reference in New Issue
Block a user