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
+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()
})