mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +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:
@@ -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,146 @@ 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('gives MCP and CLI callers a download link to the file', async () => {
|
||||
const client = await connect(reviewerToken)
|
||||
const result = await client.callTool({
|
||||
name: 'download_asset',
|
||||
arguments: { assetIds: [imageId] },
|
||||
})
|
||||
expect(result.isError).toBeFalsy()
|
||||
const viaMcp = result.structuredContent as { files: Array<Record<string, unknown>> }
|
||||
expect(viaMcp.files).toEqual([
|
||||
{
|
||||
assetId: imageId,
|
||||
name: 'photo.png',
|
||||
kind: 'original',
|
||||
size: png.length,
|
||||
mimeType: 'image/png',
|
||||
url: expect.any(String),
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request('/api/ops/download_asset', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${reviewerToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'x-shumai-client': 'cli',
|
||||
},
|
||||
body: JSON.stringify({ assetIds: [imageId], proxy: false }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const viaCli = (await res.json()) as { files: Array<{ url: string; key?: string }> }
|
||||
expect(viaCli.files[0].key).toBeUndefined()
|
||||
const link = new URL(viaCli.files[0].url)
|
||||
const file = await app.request(link.pathname + link.search)
|
||||
expect(file.status).toBe(200)
|
||||
expect(Buffer.from(await file.arrayBuffer()).equals(png)).toBe(true)
|
||||
})
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user