mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +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,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. Use download_asset to get the whole file.]`
|
||||
}
|
||||
}
|
||||
return { content: [{ type: 'text', text }, ...images], structuredContent }
|
||||
}
|
||||
|
||||
export const readAssetMcpExtension: McpToolExtension = {
|
||||
extraInput,
|
||||
present: presentReadForMcp,
|
||||
}
|
||||
|
||||
export const getAssetRenderMcpExtension: McpToolExtension = {
|
||||
extraInput,
|
||||
present: presentReadForMcp,
|
||||
}
|
||||
@@ -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>
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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,12 @@ describe('MCP server', () => {
|
||||
expect(tools.map((t) => t.name).sort()).toEqual([
|
||||
'create_folder',
|
||||
'delete_asset',
|
||||
'download_asset',
|
||||
'get_asset_render',
|
||||
'list_assets',
|
||||
'list_projects',
|
||||
'move_assets',
|
||||
'read_asset',
|
||||
'rename_asset',
|
||||
])
|
||||
|
||||
@@ -81,9 +86,58 @@ describe('MCP server', () => {
|
||||
expect(annotations('list_assets')).toMatchObject({ readOnlyHint: true, idempotentHint: true })
|
||||
})
|
||||
|
||||
it('advertises input schemas without nullable types', async () => {
|
||||
// Nullable types don't translate to every client's tool format (e.g. Gemini's)
|
||||
for (const tool of (await client.listTools()).tools) {
|
||||
const schema = JSON.stringify(tool.inputSchema)
|
||||
expect(schema, tool.name).not.toMatch(/"type":\[/)
|
||||
expect(schema, tool.name).not.toContain('"type":"null"')
|
||||
}
|
||||
})
|
||||
|
||||
it('treats null optional arguments as omitted, including nested ones', async () => {
|
||||
vi.mocked(runOperation).mockResolvedValue({
|
||||
status: 'pending',
|
||||
summary: 'Rendering is still in progress for "deck.pdf".',
|
||||
asset: { id: 'doc-1', name: 'deck.pdf', kind: 'document', mediaType: 'application/pdf' },
|
||||
details: [],
|
||||
images: [],
|
||||
taskId: 'task-1',
|
||||
retryAfterSeconds: 5,
|
||||
})
|
||||
|
||||
const result = await client.callTool({
|
||||
name: 'read_asset',
|
||||
arguments: {
|
||||
assetId: 'doc-1',
|
||||
annotationId: null,
|
||||
videoConfig: null,
|
||||
docConfig: { mode: 'pages', startPage: 1, endPage: null },
|
||||
inlineImages: null,
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.isError).toBeFalsy()
|
||||
expect(runOperation).toHaveBeenCalledWith(
|
||||
readAssetOp,
|
||||
{ userId: 'user1', via: 'mcp' },
|
||||
{ assetId: 'doc-1', docConfig: { mode: 'pages', startPage: 1 } },
|
||||
)
|
||||
})
|
||||
|
||||
it('still rejects null for required arguments', async () => {
|
||||
const result = await client.callTool({
|
||||
name: 'create_folder',
|
||||
arguments: { parent: null, name: 'Renders' },
|
||||
})
|
||||
|
||||
expect(result.isError).toBe(true)
|
||||
expect(runOperation).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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', 'mcp']) {
|
||||
expect(names).not.toContain(agentOnly)
|
||||
}
|
||||
})
|
||||
@@ -141,4 +195,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' },
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { Hono } from 'hono'
|
||||
import { createMcpHandler, McpServer, type CallToolResult } from '@modelcontextprotocol/server'
|
||||
import type { z } from 'zod'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { dropNullOptionals } from '@shumai/operations'
|
||||
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 +17,58 @@ 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(' ')
|
||||
|
||||
/**
|
||||
* The tool's input schema, with `null` for optional arguments treated as omitted. The SDK
|
||||
* validates arguments before calling the tool, so the nulls must be dropped here; the JSON
|
||||
* Schema shown to clients is unchanged (optional, not nullable, which more clients support).
|
||||
*/
|
||||
function toolInputSchema(schema: z.ZodObject): Pick<z.ZodObject, '~standard'> {
|
||||
const standard = schema['~standard']
|
||||
return {
|
||||
'~standard': {
|
||||
...standard,
|
||||
validate: (value) => standard.validate(dropNullOptionals(schema, value)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 +89,17 @@ 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: toolInputSchema(
|
||||
extension?.extraInput
|
||||
? definition.input.extend(extension.extraInput.shape)
|
||||
: definition.input,
|
||||
),
|
||||
outputSchema: definition.output,
|
||||
annotations: {
|
||||
title: definition.title,
|
||||
|
||||
Reference in New Issue
Block a user