mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 05:14:25 +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:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user