feat(mcp): serve Operations over MCP and a generic /api/ops endpoint (#495)

Add a stateless Streamable HTTP MCP server at /api/mcp that exposes every
mcp-surface Operation with its input/output schemas and annotations, and
POST /api/ops/:name for the CLI. Both require an API token (session
cookies are rejected), run Operations as the token's user, honor demo
read-only mode, and record via mcp/cli/api in audit logs.

Also make list_projects toggleable in agent settings and document MCP
client setup.
This commit is contained in:
Yiling-J
2026-10-27 08:09:09 +08:00
committed by GitHub
parent 76057ccd21
commit 4d61786799
20 changed files with 866 additions and 18 deletions
+9 -1
View File
@@ -11,8 +11,10 @@ import inviteRoute from './invite'
import metadataRoute from './metadata'
import mcpRoute, { mcpOauthCallbackRoute } from './mcp'
import { authMiddleware } from './middleware/auth'
import { tokenAuthMiddleware } from './middleware/tokenAuth'
import { requireApiTokenMiddleware, tokenAuthMiddleware } from './middleware/tokenAuth'
import mcpServerRoute from './mcp-server'
import notificationRoute from './notification'
import operationsRoute from './operations'
import projectRoute from './project'
import providerRoute from './provider'
import publicInviteRoute from './public-invite'
@@ -40,6 +42,12 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
.route('/', localUploadRoute)
.route('/', mcpOauthCallbackRoute)
// Programmatic endpoints: API token required, session cookies not accepted
.use('/ops/*', requireApiTokenMiddleware)
.use('/mcp', requireApiTokenMiddleware)
.route('/', operationsRoute)
.route('/', mcpServerRoute)
// Selected routes supporting API token authentication
.use('/projects', tokenAuthMiddleware)
.use('/projects/*', tokenAuthMiddleware)
@@ -0,0 +1,161 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
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 { apiTokenService } from '@shumai/core/src/user/api-token'
import app from './index'
/**
* End-to-end through the composed API app: API token auth → /api/mcp and /api/ops →
* runOperation → core services → database. Nothing is mocked.
*/
describe('MCP server and /api/ops (integration)', () => {
setupTestDbHooks()
let owner: User
let ownerToken: string
let reviewerToken: string
let teamId: string
let projectId: string
let rootFolderId: string
const clients: Client[] = []
beforeEach(async () => {
owner = await prisma.user.create({
data: { name: 'MCP Owner', email: 'mcp-owner@test.com', password: 'pw' },
})
const reviewer = await prisma.user.create({
data: { name: 'MCP Reviewer', email: 'mcp-reviewer@test.com', password: 'pw' },
})
const team = await prisma.team.create({ data: { name: 'MCP Team' } })
teamId = team.id
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
const project = await projectService.createProject(owner, { teamId, name: 'MCP Project' })
projectId = project.id
rootFolderId = project.rootFolder!
ownerToken = (await apiTokenService.createToken(owner.id, 'mcp')).token
reviewerToken = (await apiTokenService.createToken(reviewer.id, 'mcp')).token
})
afterEach(async () => {
await Promise.all(clients.splice(0).map((c) => c.close()))
})
async function connect(token: string): Promise<Client> {
const transport = new StreamableHTTPClientTransport(new URL('http://shumai.test/api/mcp'), {
requestInit: { headers: { Authorization: `Bearer ${token}` } },
fetch: async (input, init) => app.request(String(input), init),
})
const client = new Client({ name: 'integration-test', version: '1.0.0' })
await client.connect(transport)
clients.push(client)
return client
}
it('lets an MCP client find a project and create a folder in it', async () => {
const client = await connect(ownerToken)
const projects = await client.callTool({ name: 'list_projects', arguments: {} })
expect(projects.structuredContent).toEqual({
data: [{ id: projectId, name: 'MCP Project', teamId, rootFolderId }],
})
const created = await client.callTool({
name: 'create_folder',
arguments: { parent: rootFolderId, name: 'From MCP' },
})
expect(created.isError).toBeFalsy()
const folderId = (created.structuredContent as { id: string }).id
const folder = await prisma.asset.findUniqueOrThrow({ where: { id: folderId } })
expect(folder).toMatchObject({ name: 'From MCP', parentId: rootFolderId, creatorId: owner.id })
const audit = await prisma.auditLog.findFirstOrThrow({
where: { action: 'folder_create', itemId: folderId },
})
expect(audit).toMatchObject({ userId: owner.id, teamId, projectId, via: 'mcp' })
})
it("enforces the token owner's permissions", async () => {
const client = await connect(reviewerToken)
const result = await client.callTool({
name: 'create_folder',
arguments: { parent: rootFolderId, name: 'Not allowed' },
})
expect(result.isError).toBe(true)
expect(await prisma.asset.count({ where: { name: 'Not allowed' } })).toBe(0)
})
it('rejects MCP requests without a valid token', async () => {
const initialize = JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'initialize',
params: {
protocolVersion: '2025-06-18',
capabilities: {},
clientInfo: { name: 'x', version: '1' },
},
})
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json, text/event-stream',
}
const missing = await app.request('/api/mcp', { method: 'POST', headers, body: initialize })
expect(missing.status).toBe(401)
expect(missing.headers.get('WWW-Authenticate')).toContain('Bearer')
const invalid = await app.request('/api/mcp', {
method: 'POST',
headers: { ...headers, Authorization: 'Bearer shumai_invalid' },
body: initialize,
})
expect(invalid.status).toBe(401)
})
it('serves /api/ops for the CLI with via cli', async () => {
const headers = {
Authorization: `Bearer ${ownerToken}`,
'Content-Type': 'application/json',
'x-shumai-client': 'cli',
}
const created = await app.request('/api/ops/create_folder', {
method: 'POST',
headers,
body: JSON.stringify({ parent: rootFolderId, name: 'From CLI' }),
})
expect(created.status).toBe(200)
const { id } = (await created.json()) as { id: string }
const listed = await app.request('/api/ops/list_assets', {
method: 'POST',
headers,
body: JSON.stringify({ parent: rootFolderId }),
})
expect(listed.status).toBe(200)
const listing = (await listed.json()) as { data: Array<{ id: string }>; total: number }
expect(listing.data.map((a) => a.id)).toContain(id)
const audit = await prisma.auditLog.findFirstOrThrow({
where: { action: 'folder_create', itemId: id },
})
expect(audit.via).toBe('cli')
const unauthenticated = await app.request('/api/ops/list_projects', { method: 'POST' })
expect(unauthenticated.status).toBe(401)
})
it('leaves session-only MCP management routes behind session auth', async () => {
const res = await app.request('/api/mcp/servers/some-id', {
headers: { Authorization: `Bearer ${ownerToken}` },
})
expect(res.status).toBe(401)
})
})
+144
View File
@@ -0,0 +1,144 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
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 mcpServerRoute, { MCP_SERVER_INSTRUCTIONS } from './mcp-server'
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
const app = new Hono<{ Variables: { user: { id: string } } }>()
.use('*', async (c, next) => {
c.set('user', { id: 'user1' })
await next()
})
.route('/', mcpServerRoute)
/** Connects the real MCP client to the Hono route without opening a port. */
async function connect(): Promise<Client> {
const transport = new StreamableHTTPClientTransport(new URL('http://shumai.test/mcp'), {
fetch: async (input, init) => app.request(String(input), init),
})
const client = new Client({ name: 'mcp-server-test', version: '1.0.0' })
await client.connect(transport)
return client
}
describe('MCP server', () => {
let client: Client
beforeEach(async () => {
vi.mocked(runOperation).mockReset()
client = await connect()
})
afterEach(async () => {
await client.close()
vi.restoreAllMocks()
delete process.env.SHUMAI_DEMO_MODE
})
it('identifies itself and shares usage instructions', () => {
expect(client.getServerVersion()).toMatchObject({ name: 'shumai', title: 'Shumai' })
expect(client.getInstructions()).toBe(MCP_SERVER_INSTRUCTIONS)
})
it('lists every mcp-surface Operation with schemas and annotations', async () => {
const { tools } = await client.listTools()
expect(tools.map((t) => t.name).sort()).toEqual([
'create_folder',
'delete_asset',
'list_assets',
'list_projects',
'move_assets',
'rename_asset',
])
const createFolder = tools.find((t) => t.name === 'create_folder')!
expect(createFolder.title).toBe('Create Folder')
expect(createFolder.inputSchema).toMatchObject({
type: 'object',
properties: { parent: { type: 'string' }, name: { type: 'string' } },
required: ['parent', 'name'],
})
expect(createFolder.outputSchema).toMatchObject({
type: 'object',
properties: { id: { type: 'string' } },
})
expect(createFolder.annotations).toMatchObject({
readOnlyHint: false,
destructiveHint: false,
openWorldHint: false,
})
const annotations = (name: string) => tools.find((t) => t.name === name)!.annotations
expect(annotations('delete_asset')).toMatchObject({ destructiveHint: true })
expect(annotations('list_assets')).toMatchObject({ readOnlyHint: true, idempotentHint: true })
})
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']) {
expect(names).not.toContain(agentOnly)
}
})
it('runs the Operation for the authenticated user with via mcp', async () => {
const output = { id: 'f1', name: 'Renders', type: 'folder', size: 0, projectId: 'p1' }
vi.mocked(runOperation).mockResolvedValue(output)
const result = await client.callTool({
name: 'create_folder',
arguments: { parent: 'root', name: 'Renders' },
})
expect(runOperation).toHaveBeenCalledWith(
createFolderOp,
{ userId: 'user1', via: 'mcp' },
{ parent: 'root', name: 'Renders' },
)
expect(result.isError).toBeFalsy()
expect(result.structuredContent).toEqual(output)
expect(result.content).toEqual([{ type: 'text', text: JSON.stringify(output) }])
})
it('reports Operation failures as tool errors', async () => {
vi.mocked(runOperation).mockRejectedValue(
new HTTPException(403, { message: 'User is not a member of the team' }),
)
const result = await client.callTool({
name: 'create_folder',
arguments: { parent: 'root', name: 'Renders' },
})
expect(result.isError).toBe(true)
expect(result.content).toEqual([{ type: 'text', text: 'User is not a member of the team' }])
})
it('rejects arguments that do not match the input schema before running', async () => {
const result = await client.callTool({ name: 'create_folder', arguments: { parent: 'root' } })
expect(result.isError).toBe(true)
expect(runOperation).not.toHaveBeenCalled()
})
it('blocks data changes for read-only users in demo mode', async () => {
process.env.SHUMAI_DEMO_MODE = '1'
vi.spyOn(teamService, 'hasWritableRoleInAnyTeam').mockResolvedValue(false)
const result = await client.callTool({
name: 'create_folder',
arguments: { parent: 'root', name: 'Renders' },
})
expect(result.isError).toBe(true)
expect(result.content).toEqual([{ type: 'text', text: 'System is in read-only mode' }])
expect(runOperation).not.toHaveBeenCalled()
})
})
+87
View File
@@ -0,0 +1,87 @@
import { Hono } from 'hono'
import { createMcpHandler, McpServer, type CallToolResult } from '@modelcontextprotocol/server'
import type { Prisma } from '@shumai/db'
import { getOperationsForSurface, runOperation, type Operation } from '@shumai/core/src/operations'
import { assertWritableInDemoMode, describeOperationError } from './operation-support'
type User = Prisma.UserGetPayload<Record<string, never>>
/** Implementation version reported to MCP clients (independent of the protocol version). */
export const MCP_SERVER_VERSION = '1.0.0'
export const MCP_SERVER_INSTRUCTIONS = [
'Shumai is a media asset workspace organized as teams > projects > folders > files.',
'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.',
].join(' ')
async function callOperation(
op: Operation,
userId: string,
args: unknown,
): Promise<CallToolResult> {
try {
await assertWritableInDemoMode(op, userId)
const output = (await runOperation(op, { userId, via: 'mcp' }, args)) as Record<string, unknown>
return {
content: [{ type: 'text', text: JSON.stringify(output) }],
structuredContent: output,
}
} catch (err) {
return {
content: [{ type: 'text', text: describeOperationError(op.definition.name, err).message }],
isError: true,
}
}
}
/** A fresh MCP server exposing every `mcp`-surface Operation on behalf of one user. */
export function buildMcpServer(userId: string): McpServer {
const server = new McpServer(
{ name: 'shumai', title: 'Shumai', version: MCP_SERVER_VERSION },
{ instructions: MCP_SERVER_INSTRUCTIONS },
)
for (const op of getOperationsForSurface('mcp')) {
const { definition } = op
server.registerTool(
definition.name,
{
title: definition.title,
description: definition.description,
inputSchema: definition.input,
outputSchema: definition.output,
annotations: {
title: definition.title,
readOnlyHint: definition.annotations.readOnly,
destructiveHint: definition.annotations.destructive,
idempotentHint: definition.annotations.idempotent ?? false,
openWorldHint: false,
},
},
(args) => callOperation(op, userId, args),
)
}
return server
}
// Stateless serving: the factory builds a server per request for the authenticated user,
// so no state is shared between users or requests. The user is resolved by
// `requireApiTokenMiddleware` and handed to the factory through `authInfo`.
const mcpHandler = createMcpHandler(({ authInfo }) => {
const userId = authInfo?.extra?.userId
if (typeof userId !== 'string') {
throw new Error('MCP request reached the handler without an authenticated user')
}
return buildMcpServer(userId)
})
/** Shumai's MCP server (Streamable HTTP). Mounted at `/api/mcp` behind API token auth. */
const route = new Hono<{ Variables: { user: User } }>().all('/mcp', (c) => {
const user = c.get('user')
return mcpHandler.fetch(c.req.raw, {
authInfo: { token: '', clientId: user.id, scopes: [], extra: { userId: user.id } },
})
})
export default route
+59 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono } from 'hono'
import { tokenAuthMiddleware } from './tokenAuth'
import { requireApiTokenMiddleware, tokenAuthMiddleware } from './tokenAuth'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import type { Prisma } from '@shumai/db'
@@ -74,3 +74,61 @@ describe('tokenAuthMiddleware', () => {
expect(await res.json()).toEqual({ error: 'Unauthorized: Invalid API Key' })
})
})
describe('requireApiTokenMiddleware', () => {
const app = new Hono()
.use('*', requireApiTokenMiddleware)
.post('/test', (c) => c.text(`user:${c.get('user').id}`))
beforeEach(() => {
vi.resetAllMocks()
})
it('rejects requests without a token and advertises Bearer auth', async () => {
const res = await app.request('/test', { method: 'POST' })
expect(res.status).toBe(401)
expect(res.headers.get('WWW-Authenticate')).toBe('Bearer realm="shumai"')
expect(await res.json()).toEqual({
error: 'Unauthorized: an API token is required (Authorization: Bearer <token>)',
})
expect(apiTokenService.validateToken).not.toHaveBeenCalled()
})
it('does not accept a session cookie in place of a token', async () => {
const res = await app.request('/test', {
method: 'POST',
headers: { Cookie: 'better-auth.session_token=abc' },
})
expect(res.status).toBe(401)
})
it('rejects an invalid token', async () => {
vi.mocked(apiTokenService.validateToken).mockResolvedValue(null)
const res = await app.request('/test', {
method: 'POST',
headers: { Authorization: 'Bearer nope' },
})
expect(res.status).toBe(401)
expect(res.headers.get('WWW-Authenticate')).toBe('Bearer realm="shumai"')
expect(await res.json()).toEqual({ error: 'Unauthorized: Invalid API Key' })
})
it.each<Record<string, string>>([{ Authorization: 'Bearer good' }, { 'x-api-key': 'good' }])(
'sets the user for a valid token (%o)',
async (headers) => {
vi.mocked(apiTokenService.validateToken).mockResolvedValue({
id: 'user123',
} as unknown as Prisma.UserGetPayload<Record<string, never>>)
const res = await app.request('/test', { method: 'POST', headers })
expect(res.status).toBe(200)
expect(await res.text()).toBe('user:user123')
expect(apiTokenService.validateToken).toHaveBeenCalledWith('good')
},
)
})
+43 -5
View File
@@ -1,19 +1,29 @@
import type { Prisma } from '@shumai/db'
import { apiTokenService } from '@shumai/core/src/user/api-token'
import type { Context } from 'hono'
import { createMiddleware } from 'hono/factory'
type User = Prisma.UserGetPayload<Record<string, never>>
/** Reads an API token from `Authorization: Bearer <token>` or `x-api-key`. */
function readApiToken(c: Context): string | null {
const authHeader = c.req.header('Authorization')
if (authHeader && authHeader.startsWith('Bearer ')) {
return authHeader.substring(7)
}
return c.req.header('x-api-key') || null
}
/**
* Optional API token authentication: sets `user` when a valid token is present, rejects
* invalid tokens, and otherwise falls through to session authentication.
*/
export const tokenAuthMiddleware = createMiddleware<{
Variables: {
user: User
}
}>(async (c, next) => {
const authHeader = c.req.header('Authorization')
const token =
authHeader && authHeader.startsWith('Bearer ')
? authHeader.substring(7)
: c.req.header('x-api-key') || null
const token = readApiToken(c)
if (token) {
const user = await apiTokenService.validateToken(token)
@@ -27,3 +37,31 @@ export const tokenAuthMiddleware = createMiddleware<{
await next()
})
/**
* Required API token authentication for programmatic endpoints (`/ops`, `/mcp`). Session
* cookies are not accepted, so these endpoints cannot be driven from a browser session.
*/
export const requireApiTokenMiddleware = createMiddleware<{
Variables: {
user: User
}
}>(async (c, next) => {
const token = readApiToken(c)
const user = token ? await apiTokenService.validateToken(token) : null
if (!user) {
c.header('WWW-Authenticate', 'Bearer realm="shumai"')
return c.json(
{
error: token
? 'Unauthorized: Invalid API Key'
: 'Unauthorized: an API token is required (Authorization: Bearer <token>)',
},
401,
)
}
c.set('user', user)
await next()
})
+35
View File
@@ -0,0 +1,35 @@
import { HTTPException } from 'hono/http-exception'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { Operation } from '@shumai/core/src/operations'
import { teamService } from '@shumai/core/src/team/team'
import { logger } from '@shumai/core/src/logger'
/**
* Map an error thrown while running an Operation to a status and a message that is safe to
* return to an external caller. `HTTPException`s and plain `Error`s raised by services carry
* user-facing messages; anything else (e.g. database driver errors) is logged and hidden.
*/
export function describeOperationError(
operation: string,
err: unknown,
): { status: ContentfulStatusCode; message: string } {
if (err instanceof HTTPException) {
return { status: err.status as ContentfulStatusCode, message: err.message }
}
logger.error({ err, operation }, 'Operation failed')
if (err instanceof Error && err.constructor === Error) {
return { status: 500, message: err.message }
}
return { status: 500, message: 'Internal server error' }
}
/**
* Mirrors the read-only demo mode enforced by `authMiddleware` for session requests:
* Operations that change data are rejected for users without a writable role in any team.
*/
export async function assertWritableInDemoMode(op: Operation, userId: string): Promise<void> {
if (process.env.SHUMAI_DEMO_MODE !== '1' || op.definition.annotations.readOnly) return
if (!(await teamService.hasWritableRoleInAnyTeam(userId))) {
throw new HTTPException(403, { message: 'System is in read-only mode' })
}
}
+161
View File
@@ -0,0 +1,161 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { Hono } from 'hono'
import { HTTPException } from 'hono/http-exception'
import { teamService } from '@shumai/core/src/team/team'
import {
createFolderOp,
getOperation,
listAssetsOp,
runOperation,
type Operation,
} from '@shumai/core/src/operations'
import operationsRoute from './operations'
vi.mock('@shumai/core/src/operations', async (importOriginal) => {
const actual = await importOriginal<typeof import('@shumai/core/src/operations')>()
return { ...actual, runOperation: vi.fn(), getOperation: vi.fn(actual.getOperation) }
})
const app = new Hono<{ Variables: { user: { id: string } } }>()
.use('*', async (c, next) => {
c.set('user', { id: 'user1' })
await next()
})
.route('/', operationsRoute)
function post(name: string, body?: string, headers: Record<string, string> = {}) {
return app.request(`/ops/${name}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body,
})
}
describe('POST /ops/:name', () => {
beforeEach(() => {
vi.mocked(runOperation).mockReset()
delete process.env.SHUMAI_DEMO_MODE
})
afterEach(() => {
vi.restoreAllMocks()
delete process.env.SHUMAI_DEMO_MODE
})
it('runs the Operation with the JSON body and returns its output', async () => {
const output = { id: 'f1', name: 'Renders', type: 'folder', size: 0, projectId: 'p1' }
vi.mocked(runOperation).mockResolvedValue(output)
const res = await post('create_folder', JSON.stringify({ parent: 'root', name: 'Renders' }))
expect(res.status).toBe(200)
expect(await res.json()).toEqual(output)
expect(runOperation).toHaveBeenCalledWith(
createFolderOp,
{ userId: 'user1', via: 'api' },
{ parent: 'root', name: 'Renders' },
)
})
it('attributes calls from the CLI to via cli', async () => {
vi.mocked(runOperation).mockResolvedValue({ data: [] })
await post('list_projects', '{}', { 'x-shumai-client': 'cli' })
expect(runOperation).toHaveBeenCalledWith(
expect.anything(),
{ userId: 'user1', via: 'cli' },
{},
)
})
it('treats an empty body as an empty input', async () => {
vi.mocked(runOperation).mockResolvedValue({ data: [] })
const res = await post('list_projects')
expect(res.status).toBe(200)
expect(runOperation).toHaveBeenCalledWith(expect.anything(), expect.anything(), {})
})
it('returns 404 for an unknown Operation', async () => {
const res = await post('drop_database', '{}')
expect(res.status).toBe(404)
expect(await res.json()).toEqual({ error: 'Unknown operation "drop_database"' })
expect(runOperation).not.toHaveBeenCalled()
})
it('returns 404 for an Operation without the cli surface', async () => {
const agentOnly: Operation = {
...listAssetsOp,
definition: { ...listAssetsOp.definition, surfaces: ['agent'] },
}
vi.mocked(getOperation).mockReturnValueOnce(agentOnly)
const res = await post('list_assets', '{}')
expect(res.status).toBe(404)
expect(runOperation).not.toHaveBeenCalled()
})
it('returns 400 for a body that is not JSON', async () => {
const res = await post('list_projects', 'not json')
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'Request body must be a JSON object' })
})
it('returns the status and message of HTTP errors', async () => {
vi.mocked(runOperation).mockRejectedValue(
new HTTPException(403, { message: 'User is not a member of the team' }),
)
const res = await post('create_folder', '{"parent":"p","name":"n"}')
expect(res.status).toBe(403)
expect(await res.json()).toEqual({ error: 'User is not a member of the team' })
})
it('returns service error messages as 500', async () => {
vi.mocked(runOperation).mockRejectedValue(new Error('Parent not found'))
const res = await post('create_folder', '{"parent":"p","name":"n"}')
expect(res.status).toBe(500)
expect(await res.json()).toEqual({ error: 'Parent not found' })
})
it('hides messages of unexpected error types', async () => {
class DriverError extends Error {}
vi.mocked(runOperation).mockRejectedValue(new DriverError('SELECT * FROM secrets failed'))
const res = await post('create_folder', '{"parent":"p","name":"n"}')
expect(res.status).toBe(500)
expect(await res.json()).toEqual({ error: 'Internal server error' })
})
describe('in demo mode', () => {
beforeEach(() => {
process.env.SHUMAI_DEMO_MODE = '1'
vi.spyOn(teamService, 'hasWritableRoleInAnyTeam').mockResolvedValue(false)
})
it('rejects Operations that change data for read-only users', async () => {
const res = await post('create_folder', '{"parent":"p","name":"n"}')
expect(res.status).toBe(403)
expect(await res.json()).toEqual({ error: 'System is in read-only mode' })
expect(runOperation).not.toHaveBeenCalled()
})
it('still allows read-only Operations', async () => {
vi.mocked(runOperation).mockResolvedValue({ data: [] })
const res = await post('list_projects', '{}')
expect(res.status).toBe(200)
})
})
})
+44
View File
@@ -0,0 +1,44 @@
import { Hono } from 'hono'
import type { Prisma } from '@shumai/db'
import { getOperation, runOperation } from '@shumai/core/src/operations'
import { assertWritableInDemoMode, describeOperationError } from './operation-support'
type User = Prisma.UserGetPayload<Record<string, never>>
/** Header the CLI sends so its invocations are attributed to `via: cli` in audit logs. */
export const CLIENT_HEADER = 'x-shumai-client'
/**
* Generic Operation endpoint used by `shumai-cli`: `POST /ops/:name` with the Operation input
* as the JSON body. Requires API token authentication (mounted with `requireApiTokenMiddleware`).
*/
const route = new Hono<{ Variables: { user: User } }>().post('/ops/:name', async (c) => {
const name = c.req.param('name')
const op = getOperation(name)
if (!op || !op.definition.surfaces.includes('cli')) {
return c.json({ error: `Unknown operation "${name}"` }, 404)
}
let input: unknown = {}
const body = await c.req.text()
if (body.trim()) {
try {
input = JSON.parse(body)
} catch {
return c.json({ error: 'Request body must be a JSON object' }, 400)
}
}
const userId = c.get('user').id
const via = c.req.header(CLIENT_HEADER) === 'cli' ? 'cli' : 'api'
try {
await assertWritableInDemoMode(op, userId)
const output = await runOperation(op, { userId, via }, input)
return c.json(output as Record<string, unknown>)
} catch (err) {
const { status, message } = describeOperationError(name, err)
return c.json({ error: message }, status)
}
})
export default route