MCP Server 官方示例大多是单文件 + stdio,跑通很快。但企业内部往往是:工具逻辑已经在 NestJS 服务里了,还要做鉴权、限流、审计、部署。这时候最省事的做法不是重写一套,而是把 MCP 当成一个新入口,复用现有 service。这篇记录具体怎么接。
两种接法
| 方式 |
传输 |
部署 |
适用 |
| 进程内嵌 |
stdio |
随客户端启动 |
本地工具、开发辅助 |
| 独立服务 |
Streamable HTTP |
独立部署、走网关 |
团队共享、需要鉴权审计 |
内部工具基本都是第二种:独立部署,前面挂 Nginx,统一鉴权。这样多个 AI 客户端(编辑器、聊天平台、Agent 平台)都能接同一个服务。
初始化
1
| npm i @modelcontextprotocol/sdk zod
|
核心思路:用 NestJS 创建应用,然后把 MCP 的 HTTP 处理器挂到一个路由上。
1 2 3 4 5 6 7 8 9 10 11 12
| import { Module } from '@nestjs/common' import { McpController } from './mcp.controller' import { McpService } from './mcp.service' import { OrderModule } from '../order/order.module'
@Module({ imports: [OrderModule], controllers: [McpController], providers: [McpService] }) export class McpModule {}
|
工具注册:与 DI 结合
关键点是:MCP 的工具处理函数里要能拿到 Nest 的 provider。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import { Injectable, Logger } from '@nestjs/common' import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' import { z } from 'zod' import { OrderService } from '../order/order.service'
@Injectable() export class McpService { private readonly logger = new Logger(McpService.name)
constructor(private readonly orderService: OrderService) {}
createServer() { const server = new McpServer({ name: 'orders-mcp', version: '1.2.0' })
server.tool( 'query_order', '按订单号查询订单状态、金额、下单时间。仅在用户提供了订单号时调用。', { orderId: z.string().regex(/^ORD-\d{8}$/).describe('订单号,格式 ORD-20250817') }, async ({ orderId }) => { this.logger.log(`tool=query_order orderId=${orderId}`) const order = await this.orderService.findByOrderId(orderId)
if (!order) { return { isError: true, content: [{ type: 'text', text: `订单 ${orderId} 不存在` }] } }
return { content: [{ type: 'text', text: `订单 ${orderId} 状态:${order.status},金额 ${order.amount} 元` }], structuredContent: { orderId: order.orderId, status: order.status, amount: order.amount, createdAt: order.createdAt } } } )
server.tool( 'cancel_order', '取消订单。这是不可逆操作,仅在用户明确要求取消时调用,且必须先向用户确认。', { orderId: z.string(), reason: z.string().min(2).max(200).describe('取消原因') }, async ({ orderId, reason }, extra) => { const userId = (extra as any)?.authInfo?.extra?.userId if (!userId) { return { isError: true, content: [{ type: 'text', text: '未认证' }] } }
try { await this.orderService.cancel(orderId, reason, userId) return { content: [{ type: 'text', text: `订单 ${orderId} 已取消` }] } } catch (e) { return { isError: true, content: [{ type: 'text', text: `取消失败:${(e as Error).message}` }] } } } )
return server } }
|
三个设计要点:
- **描述里写”何时调用”,不只是”做什么”**。写操作的描述必须包含”需先向用户确认”,这句话能显著降低误操作
- 参数用 zod 做运行时校验。模型传错类型时,SDK 会直接返回错误给模型,它会自我纠正
- 返回
isError: true 而不是抛异常。抛异常会变成协议级错误,模型看不到具体原因
HTTP 端点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import { All, Controller, Req, Res, UseGuards } from '@nestjs/common' import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js' import type { Request, Response } from 'express' import { McpService } from './mcp.service' import { McpAuthGuard } from './mcp-auth.guard'
@Controller('mcp') export class McpController { constructor(private readonly mcpService: McpService) {}
@All() @UseGuards(McpAuthGuard) async handle(@Req() req: Request, @Res() res: Response) { const server = this.mcpService.createServer()
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true })
res.on('close', () => { transport.close() server.close() })
await server.connect(transport) await transport.handleRequest(req, res, req.body) } }
|
sessionIdGenerator: undefined 表示无状态模式:每个请求独立处理,服务端不保存会话。这种方式可以直接水平扩容,是 2025 年之后推荐的做法——有状态会话需要粘性路由或者共享存储,部署复杂度高很多。
鉴权与审计
MCP 服务本质上就是一组 HTTP 接口,鉴权按普通 API 做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Injectable() export class McpAuthGuard implements CanActivate { constructor(private readonly auth: AuthService) {}
async canActivate(ctx: ExecutionContext): Promise<boolean> { const req = ctx.switchToHttp().getRequest() const token = req.headers.authorization?.replace(/^Bearer /, '') if (!token) throw new UnauthorizedException('missing token')
const principal = await this.auth.verifyToken(token) if (!principal) throw new UnauthorizedException('invalid token')
req.principal = principal return true } }
|
工具调用必须留审计日志——这是和普通 API 最大的不同:调用方是模型,出了问题需要能回溯”它当时看到了什么、基于什么做了这个调用”:
1 2 3 4 5
| { traceId, userId, toolName, args, isError, latencyMs, modelHint }
|
traceId 一定要从上游透传进来(X-Request-Id),否则 AI 客户端的日志和你的日志对不上。
和网关配合
MCP 的流式响应和普通接口不一样,Nginx 上必须注意:
1 2 3 4 5 6 7 8 9
| location /mcp { proxy_pass http://mcp_backend; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_read_timeout 300s; proxy_cache off; client_max_body_size 2m; }
|
proxy_buffering off 漏了会出很典型的现象:本地跑没问题,一过网关就变成”等全部结果算完才一次性返回”。
工具设计的取舍
工具数量:一个 Server 超过 20 个工具,模型选择准确率明显下降。按领域拆分多个 Server 更好:orders-mcp、crm-mcp、docs-mcp,让客户端按场景挂载。
粒度:宁可多几个细粒度工具,也不要一个 do_action(action, data) 的万能工具。模型对枚举参数的判断准确率很低。
返回大小:单次返回不要超过几千 token。查询类工具一定要支持 limit,否则一次拉回 500 条订单,上下文直接爆。
幂等:模型会重试。create_* 类工具要支持幂等键,或者至少做重复检测。
踩过的坑
1. 用 console.log 调试
HTTP 模式下没问题,但切到 stdio 就全乱套——stdout 被日志污染,客户端解析失败。统一用 Logger 输出到 stderr。
2. 把内部异常直接返回
堆栈里有表名、路径、SQL。返回给模型等于返回给用户。要包一层,只返回可读的错误类型。
3. 忘记限制返回体积
query_orders 不传分页参数时默认返回全部,一个租户有 3 万条订单,一次调用就把上下文撑爆。
4. 无状态模式下用了内存缓存
以为会话是持久的,把用户上下文存在 Map 里,扩容后随机丢失。无状态模式下所有状态必须外置。
小结
用 NestJS 写 MCP Server 的收益很直接:业务逻辑不用重写,DI、日志、监控、鉴权全部复用。代价是要接受”AI 客户端是新的调用方”这个事实——它的行为不可预测,会重试、会传错参数、会误解返回值。所以工具要写得像给陌生人用的 API:描述清楚、校验严格、错误可读、返回克制。