// MCP 支持完善 · 阶段 E:服务端的资源与提示模板(docs/design/16-mcp-support.md §6) import fs from 'node:fs' import http from 'node:http' import type { AddressInfo } from 'node:net' import path from 'node:path' import pino from 'pino' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { z } from 'zod' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js' import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js' import type { FileDto, McpPromptListDto, McpPromptResultDto, McpResourceListDto, SessionDetailDto } from '@agent-server/shared' import { createApp, type App } from '../src/app' import { config } from '../src/config' import { buildServer } from '../src/http/server' import type { GatewayRunContext } from '../src/mcp-gateway/tokens' import { resolveAccess } from '../src/services/access-policy' let app: App let server: Awaited> let base: string let upstream: http.Server let serverId: string let apiKey: string const auth = () => ({ authorization: `Bearer ${apiKey}` }) function startUpstream(): Promise { upstream = http.createServer(async (req, res) => { const mcp = new McpServer({ name: 'docs', version: '1.0.0' }) mcp.registerResource('guide', 'docs://manual/guide.md', { title: '使用手册', description: '产品使用手册', mimeType: 'text/markdown' }, async uri => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: '# 手册\n第一章' }], })) mcp.registerResource('big', 'docs://manual/big.txt', { title: '大文件', mimeType: 'text/plain' }, async uri => ({ contents: [{ uri: uri.href, text: '行'.repeat(30_000) }] })) mcp.registerResource('logo', 'docs://assets/logo.png', { title: '标志', mimeType: 'image/png' }, async uri => ({ contents: [{ uri: uri.href, mimeType: 'image/png', blob: Buffer.from([137, 80, 78, 71]).toString('base64') }], })) mcp.registerResource('topic', new ResourceTemplate('docs://topics/{product}/{topic}', { list: undefined }), { title: '主题文档', description: '按产品和主题读取' }, async (uri, v) => ({ contents: [{ uri: uri.href, text: `${v.product} 的 ${v.topic}` }], })) mcp.registerPrompt('weekly', { title: '周报', description: '生成周报', argsSchema: { week: z.string().describe('第几周'), team: z.string().optional() } }, async ({ week, team }) => ({ messages: [ { role: 'user', content: { type: 'text', text: `请为${team ?? '团队'}写第 ${week} 周的周报` } }, { role: 'user', content: { type: 'resource', resource: { uri: 'docs://templates/weekly.md', mimeType: 'text/markdown', text: '## 本周进展' } } }, ], })) const t = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }) res.on('close', () => { void t.close(); void mcp.close() }) await mcp.connect(t) let body = '' req.on('data', c => (body += c)) req.on('end', () => void t.handleRequest(req, res, body ? JSON.parse(body) : undefined)) }) return new Promise(r => upstream.listen(0, '127.0.0.1', () => r(`http://127.0.0.1:${(upstream.address() as AddressInfo).port}/mcp`))) } function runCtx(ids: string[]): GatewayRunContext { const ws = path.join(config.dataDir, 'workspaces', `ses_res_${Math.random().toString(36).slice(2)}`) fs.mkdirSync(ws, { recursive: true }) const settings = app.settings.get() return { sessionId: `ses_${Math.random().toString(36).slice(2)}`, runId: 'r', provider: 'claude', workspaceDir: ws, permissionMode: 'readonly', settings, access: resolveAccess({ policy: { mode: 'restricted', read: [], write: [], deny: [] }, knowledgeRoots: [], selectedKnowledgeRootIds: [], workspaceDir: ws, settings }), knowledgeRoots: [], mcpServerIds: ids, audit: () => {}, interact: async () => ({ resolution: 'allowed', scope: 'once' }), } } async function gateway(ctx: GatewayRunContext) { const client = new Client({ name: 'test', version: '1' }) await client.connect(new StreamableHTTPClientTransport(new URL(`${base}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${app.gatewayTokens.issue(ctx)}` } } })) return client } const text = (r: unknown) => (r as { content: { text: string }[] }).content.map(c => c.text).join('\n') beforeAll(async () => { const log = pino({ level: 'silent' }) app = createApp(log, { providers: {} }) server = await buildServer(app, { logger: log }) base = await server.listen({ port: 0, host: '127.0.0.1' }) const url = await startUpstream() serverId = app.mcpServers.create({ name: 'docs', title: '文档服务', description: '', transport: 'http', enabled: true, url, headers: [], command: '', args: [], env: [], allowNetwork: false, readPaths: [], writePaths: [] }).id const { id: _id, version: _v, updatedAt: _u, builtin: _b, builtinKey: _k, ...input } = app.profiles.getBuiltin() const profile = app.profiles.create({ ...input, name: '带文档服务', isDefault: false, mcpServerIds: [serverId] }) apiKey = app.apiKeys.create('平台R', { allowedProfileIds: [profile.id], defaultProfileId: profile.id }).key }) afterAll(async () => { await app.mcpUpstream.closeAll() await server.close() upstream.close() }) describe('资源(模型按需读取)', () => { it('刷新时记录服务的能力;勾选了提供资源的服务时网关提供两个只读工具;读取的内容按大小内联或存为文件', async () => { // 第一次列出工具时连接服务、记录能力,资源工具在同一次列出中就会出现 const first = await gateway(runCtx([serverId])) expect((await first.listTools()).tools.map(t => t.name)).toContain('mcp_resources') await first.close() expect((await app.mcpServers.refresh(serverId)).features).toEqual({ resources: true, prompts: true }) const ctx = runCtx([serverId]) const c = await gateway(ctx) const names = (await c.listTools()).tools.map(t => t.name) expect(names).toEqual(expect.arrayContaining(['mcp_resources', 'mcp_resource_read'])) // 只读模式下也提供 const list = text(await c.callTool({ name: 'mcp_resources', arguments: {} })) expect(list).toContain('[docs] 使用手册 docs://manual/guide.md (text/markdown)') expect(list).toContain('模板 主题文档 docs://topics/{product}/{topic}') expect(list).not.toContain('第一章') expect(text(await c.callTool({ name: 'mcp_resource_read', arguments: { server: 'docs', uri: 'docs://manual/guide.md' } }))).toBe('docs://manual/guide.md(text/markdown)\n# 手册\n第一章') expect(text(await c.callTool({ name: 'mcp_resource_read', arguments: { server: 'docs', uri: 'docs://topics/ess/warranty' } }))).toContain('ess 的 warranty') const big = text(await c.callTool({ name: 'mcp_resource_read', arguments: { server: 'docs', uri: 'docs://manual/big.txt' } })) const saved = /保存到 (\S+))/.exec(big)![1]! expect(saved).toBe(path.join('.agent', 'mcp', 'resources', 'big.txt')) expect(fs.readFileSync(path.join(ctx.workspaceDir, saved), 'utf8')).toHaveLength(30_000) const logo = text(await c.callTool({ name: 'mcp_resource_read', arguments: { server: 'docs', uri: 'docs://assets/logo.png' } })) expect(logo).toMatch(/二进制内容(4 B)已保存到 \.agent\/mcp\/resources\/logo\.png/) await c.close() const none = await gateway(runCtx([])) expect((await none.listTools()).tools.map(t => t.name)).not.toContain('mcp_resources') await none.close() }) }) describe('资料与快捷指令(会话 API)', () => { it('会话详情给出能力;列出资源、附加为会话文件;列出提示模板、展开后返回文本和附件', async () => { const sid = (await server.inject({ method: 'POST', url: '/v1/sessions', headers: auth(), payload: {} })).json().id as string expect((await server.inject({ method: 'GET', url: `/v1/sessions/${sid}`, headers: auth() })).json().mcp).toEqual({ resources: true, prompts: true }) const list = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/mcp/resources`, headers: auth() })).json() expect(list.resources.map(r => r.uri)).toEqual(['docs://manual/guide.md', 'docs://manual/big.txt', 'docs://assets/logo.png']) expect(list.resources[0]).toMatchObject({ serverId, serverName: 'docs', serverTitle: '文档服务', title: '使用手册', description: '产品使用手册' }) expect(list.templates).toEqual([expect.objectContaining({ uriTemplate: 'docs://topics/{product}/{topic}', title: '主题文档' })]) const attached = (await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/mcp/resources/attach`, headers: auth(), payload: { server: 'docs', uri: 'docs://manual/guide.md' } })).json() expect(attached).toEqual([expect.objectContaining({ path: 'uploads/guide.md', origin: 'upload', size: Buffer.byteLength('# 手册\n第一章') })]) const run = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/messages`, headers: auth(), payload: { text: '看看这份手册', attachments: attached.map(f => f.id) } }) expect([202, 409]).toContain(run.statusCode) // 没有引擎时也能校验附件属于这个会话 const prompts = (await server.inject({ method: 'GET', url: `/v1/sessions/${sid}/mcp/prompts`, headers: auth() })).json() expect(prompts.prompts).toEqual([expect.objectContaining({ name: 'weekly', title: '周报', arguments: [{ name: 'week', description: '第几周', required: true }, { name: 'team', description: null, required: false }] })]) const got = (await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/mcp/prompts/get`, headers: auth(), payload: { server: serverId, name: 'weekly', arguments: { week: '44', team: '储能组' } } })).json() expect(got.text).toBe('请为储能组写第 44 周的周报') expect(got.attachments).toEqual([expect.objectContaining({ path: 'uploads/weekly.md' })]) const missing = await server.inject({ method: 'POST', url: `/v1/sessions/${sid}/mcp/resources/attach`, headers: auth(), payload: { server: 'nope', uri: 'docs://x' } }) expect(missing.statusCode).toBe(404) }) })