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:
Yiling-J
2026-10-27 08:09:11 +08:00
committed by GitHub
parent 155fb95a0e
commit 50fbd97953
55 changed files with 2612 additions and 620 deletions
@@ -0,0 +1,294 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import * as fs from 'fs'
import * as path from 'path'
import { prisma, type Asset, type StorageKey } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { authzService } from '@shumai/core/src/authz/authz'
import { getOperation } from '@shumai/core/src/operations'
import { toAgentTool } from '../operation-tools'
import './download-asset'
vi.mock('@shumai/db', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/db')>()
return {
...actual,
prisma: {
asset: { findUnique: vi.fn(), findFirst: vi.fn() },
storageKey: { findFirst: vi.fn(), findUnique: vi.fn() },
},
}
})
vi.mock('@shumai/core/src/s3/s3', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/core/src/s3/s3')>()
return {
...actual,
s3Service: {
headObject: vi.fn(),
downloadToFile: vi.fn(),
presign: vi.fn().mockResolvedValue('https://signed.example/file'),
},
}
})
vi.mock('@shumai/core/src/authz/authz', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/core/src/authz/authz')>()
return { ...actual, authzService: { hasPermission: vi.fn() } }
})
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
type Saved = { filePath: string; absolutePath: string; contentType: string; size: number }
const piDir = path.join(process.cwd(), '.pi')
function downloadTool(userId = 'user-1') {
return toAgentTool(getOperation('download_asset')!, { userId })
}
function textOf(result: { content: unknown[] }): string {
return (result.content[0] as { text: string }).text
}
function mockAssets(...assets: Array<Record<string, unknown>>) {
vi.mocked(prisma.asset.findUnique).mockImplementation(
(async (args: { where: { id: string } }) =>
assets.find((a) => a.id === args.where.id) ?? null) as never,
)
}
function mockStorage(contentType: string, write = 'bytes') {
vi.mocked(s3Service.headObject).mockResolvedValue({ size: 1234, contentType } as Head)
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, dest) => {
await fs.promises.writeFile(dest, write)
})
}
const photo = {
id: 'img-1',
name: 'sample_photo.jpg',
type: 'file',
isDeleted: false,
storageKey: { key: 'files/up-1/sample_photo.jpg' },
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/img-1/proxy.webp' }] },
}
describe('download_asset agent tool', () => {
const created: string[] = []
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue()
})
afterEach(() => {
for (const file of created.splice(0)) fs.rmSync(file, { force: true })
})
it('offers assetIds, proxy, and the agent-only key parameter', () => {
const tool = downloadTool()
const schema = tool.parameters as { properties: Record<string, unknown>; required?: string[] }
expect(Object.keys(schema.properties)).toEqual(['assetIds', 'proxy', 'key'])
expect(schema.required ?? []).not.toContain('assetIds')
expect(tool.description).toContain('.pi directory')
})
it('saves the web preview into .pi by default, named after the asset', async () => {
mockAssets(photo)
mockStorage('image/webp', 'proxy-bytes')
const result = await downloadTool().execute('call-1', { assetIds: ['img-1'] })
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
created.push(expectedPath)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'img-1',
})
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/img-1/proxy.webp',
expectedPath,
)
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('proxy-bytes')
expect(textOf(result)).toBe(
[
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.join('.pi', 'img-1_sample_photo.webp')}".`,
'Remember to delete these temporary files when finished.',
].join('\n'),
)
const details = result.details as { files: Saved[] }
expect(details.files[0]).toMatchObject({
filePath: path.join('.pi', 'img-1_sample_photo.webp'),
contentType: 'image/webp',
size: 11,
})
})
it('saves the original with proxy false', async () => {
mockAssets(photo)
mockStorage('image/jpeg')
await downloadTool().execute('call-1', { assetIds: ['img-1'], proxy: false })
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
created.push(expectedPath)
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
'shumai',
'files/up-1/sample_photo.jpg',
expectedPath,
)
})
it('downloads several files and the latest version of a version stack', async () => {
mockAssets(photo, { id: 'stack-1', name: 'banana', type: 'version_stack', isDeleted: false })
vi.mocked(prisma.asset.findFirst).mockResolvedValue({
id: 'file-v2',
name: 'banana_pig.png',
type: 'file',
isDeleted: false,
storageKey: { key: 'files/up-2/banana_pig.png' },
media: { proxyType: 'image', imageTranscodes: [{ key: 'files/file-v2/proxy.webp' }] },
} as unknown as Asset)
mockStorage('image/webp')
const result = await downloadTool().execute('call-1', {
assetIds: ['img-1', 'stack-1'],
key: null,
})
created.push(
path.join(piDir, 'img-1_sample_photo.webp'),
path.join(piDir, 'file-v2_banana_pig.webp'),
)
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
where: { parentId: 'stack-1', isDeleted: false },
orderBy: { sortIndex: 'asc' },
include: { storageKey: true },
})
expect(s3Service.downloadToFile).toHaveBeenCalledTimes(2)
expect(textOf(result)).toContain('Downloaded "banana_pig.webp" (ID: file-v2, proxy')
})
it('rejects folders', async () => {
mockAssets({ id: 'folder-1', name: 'Renders', type: 'folder', isDeleted: false })
await expect(downloadTool().execute('call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
)
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('checks Read on every asset before downloading anything', async () => {
mockAssets(photo)
vi.mocked(authzService.hasPermission).mockImplementation(async ({ id }) => {
if (id === 'secret') throw new Error('Forbidden')
})
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1', 'secret'] }),
).rejects.toThrow('Forbidden')
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('requires assetIds or key', async () => {
await expect(downloadTool().execute('call-1', { assetIds: null, key: null })).rejects.toThrow(
'Invalid input for download_asset',
)
})
it('rejects assetIds and key together', async () => {
await expect(
downloadTool().execute('call-1', { assetIds: ['img-1'], key: 'files/img-1/a.webp' }),
).rejects.toThrow('Provide either "assetIds" or "key", not both.')
})
describe('by storage key', () => {
it('requires a user', async () => {
await expect(
downloadTool('').execute('call-1', { key: 'files/ast-1/shot.webp' }),
).rejects.toThrow('User ID is required for authorization.')
})
it('rejects keys outside files/ and path traversal', async () => {
await expect(downloadTool().execute('call-1', { key: 'avatars/user-1.png' })).rejects.toThrow(
'Invalid storage key format: key must start with "files/"',
)
await expect(
downloadTool().execute('call-1', { key: 'files/../../etc/passwd' }),
).rejects.toThrow('cannot contain ".."')
})
it('rejects keys that belong to no asset', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findUnique).mockResolvedValue(null)
await expect(
downloadTool().execute('call-1', { key: 'files/nope/shot.webp' }),
).rejects.toThrow('does not belong to any valid asset or the asset has been deleted')
})
it('checks Read on the owning asset', async () => {
mockAssets({ id: 'other-project-asset' })
vi.mocked(authzService.hasPermission).mockRejectedValue(new Error('Forbidden'))
await expect(
downloadTool().execute('call-1', { key: 'files/other-project-asset/shots/a.webp' }),
).rejects.toThrow('Forbidden')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'Read',
type: 'asset',
id: 'other-project-asset',
})
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
})
it('downloads a read_asset artifact into .pi', async () => {
mockAssets({ id: 'ast-123' })
mockStorage('image/webp', 'frame-bytes')
const result = await downloadTool().execute('call-1', {
key: 'files/ast-123/screenshots/shot_5.0s.webp',
})
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
created.push(expectedPath)
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('frame-bytes')
expect(textOf(result)).toBe(
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
)
expect(result.details).toMatchObject({
key: 'files/ast-123/screenshots/shot_5.0s.webp',
assetId: 'ast-123',
size: Buffer.from('frame-bytes').length,
})
})
it('resolves original upload keys through the storage key', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
vi.mocked(prisma.storageKey.findFirst).mockResolvedValue({
id: 'sk-1',
key: 'files/upload-ulid-456/photo.png',
assets: [{ id: 'asset-photo-1' }],
} as unknown as StorageKey & { assets: Asset[] })
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
vi.mocked(s3Service.headObject).mockResolvedValue({
size: 8,
contentType: 'application/octet-stream',
} as Head)
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
await fs.promises.writeFile(dest, pngHeader)
})
const result = await downloadTool().execute('call-1', {
key: 'files/upload-ulid-456/photo.png',
})
created.push(path.join(piDir, 'photo.png'))
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({ id: 'asset-photo-1' }),
)
// Falls back to detecting the type from the bytes
expect(result.details).toMatchObject({ assetId: 'asset-photo-1', contentType: 'image/png' })
})
})
})
@@ -0,0 +1,124 @@
import * as fs from 'fs'
import * as path from 'path'
import { z } from 'zod'
import type { AgentToolResult } from '@earendil-works/pi-agent-core'
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
import type { User } from '@shumai/db'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { storageBucket } from '@shumai/core/src/asset-read'
import { s3Service } from '@shumai/core/src/s3/s3'
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
import { resolveAssetIdFromKey } from '../tools/download-asset'
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
/** The agent's sandbox, where downloaded files are saved for local scripts and bash. */
function sandboxDir(): string {
const dir = path.join(process.cwd(), '.pi')
fs.mkdirSync(dir, { recursive: true })
return dir
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
/** Saves a storage object into the sandbox; returns the paths and detected content type. */
async function saveToSandbox(key: string, filename: string) {
const dir = sandboxDir()
const absolutePath = path.join(dir, filename)
const bucket = storageBucket()
const info = await s3Service.headObject(bucket, key).catch(() => null)
await s3Service.downloadToFile(bucket, key, absolutePath)
const size = await fs.promises
.stat(absolutePath)
.then((s) => s.size)
.catch(() => info?.size ?? 0)
const contentType =
info?.contentType && info.contentType !== 'application/octet-stream'
? info.contentType
: readFileMimeType(absolutePath)
return { absolutePath, filePath: path.join('.pi', filename), size, contentType }
}
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
async function downloadKey(key: string, userId: string): Promise<AgentToolResult<unknown>> {
const owningAssetId = await resolveAssetIdFromKey(key)
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Read,
type: ResourceType.Asset,
id: owningAssetId,
})
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
const saved = await saveToSandbox(key, filename)
return {
content: [
{
type: 'text',
text: `Downloaded storage key "${key}" to "${saved.filePath}". Remember to delete this temporary file when finished.`,
},
],
details: { key, assetId: owningAssetId, ...saved },
}
}
/** Saves each file of a download_asset result into the sandbox. */
export async function presentDownloadOutput(
output: DownloadAssetOutput,
): Promise<AgentToolResult<unknown>> {
const lines: string[] = []
const files = []
for (const file of output.files) {
if (!file.key) throw new Error(`download_asset returned no storage key for ${file.assetId}`)
const saved = await saveToSandbox(
file.key,
`${file.assetId}_${sanitizeFilename(file.name) || 'file'}`,
)
lines.push(
`Downloaded "${file.name}" (ID: ${file.assetId}, ${file.kind}, ${saved.contentType}, ${formatSize(saved.size)}) to "${saved.filePath}".`,
)
files.push({ assetId: file.assetId, name: file.name, kind: file.kind, ...saved })
}
lines.push(CLEANUP_REMINDER)
return { content: [{ type: 'text', text: lines.join('\n') }], details: { files } }
}
const downloadAssetExtension: AgentToolExtension = {
description:
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the local .pi directory, for processing with local scripts or bash commands. ` +
'By default it saves the web preview version (proxy) when there is one, e.g. the transcoded video or the web image; set proxy to false for the original uploaded file. ' +
'A version stack downloads its latest version; folders are not supported. ' +
'To download a specific artifact from read_asset (e.g. a frame or page), pass its storage key as "key" instead of assetIds. ' +
'Remember to delete the downloaded files when finished.',
parameterOverrides: z.object({
assetIds: downloadAsset.input.shape.assetIds
.optional()
.describe(
`IDs of the files or version stacks to download (1 to ${MAX_DOWNLOAD_ASSETS}). Omit when passing "key".`,
),
}),
extraParameters: z.object({
key: z
.string()
.optional()
.describe(
'Storage S3 key of a specific media artifact to download instead of assetIds, e.g. a screenshot or page key from read_asset.',
),
}),
async intercept(input, extra, ctx) {
if (typeof extra.key !== 'string') return undefined
if (Array.isArray(input.assetIds) && input.assetIds.length > 0) {
throw new Error('Provide either "assetIds" or "key", not both.')
}
if (!ctx.userId) throw new Error('User ID is required for authorization.')
return downloadKey(extra.key, ctx.userId)
},
present: (output) => presentDownloadOutput(output as DownloadAssetOutput),
}
registerAgentToolExtension('download_asset', downloadAssetExtension)
@@ -1,2 +1,3 @@
// Registers agent-specific presentation for Operations. Import once before building tools.
export { createAutofillReadAssetTool, presentReadOutput } from './read-asset'
export { presentDownloadOutput } from './download-asset'
@@ -752,7 +752,7 @@ describe('read_asset agent tool', () => {
assetId: 'doc-md',
docConfig: { mode: 'text', startPage: 1, endPage: 2 },
}),
).rejects.toThrow('startPage and endPage must be null when docConfig mode is "text"')
).rejects.toThrow('startPage and endPage must be left out when docConfig mode is "text"')
})
it('reads raw text in mode "text"', async () => {