迁移
用社区包 @rekog/mcp-nest 构建的 MCP 服务器迁移到 @nestjs/mcp 时,改动基本是机械性的:装饰器保持原名,工具、资源和提示词(prompt)仍然是类中的方法。本页把它的两套 API——1.x 各版本的 McpModule.forRoot() 与 2.x 的 McpStrategy——映射到 @nestjs/mcp。
软件包
@nestjs/mcp 构建在 MCP TypeScript SDK 第 2 版 @modelcontextprotocol/server 之上。请替换这些包:
$ npm uninstall @rekog/mcp-nest @modelcontextprotocol/sdk
$ npm i --save @nestjs/mcp @modelcontextprotocol/server zod如果你来自 2.x,还要卸载 @modelcontextprotocol/core 和 @modelcontextprotocol/node;若你用过它的授权服务器,还要卸载 @rekog/mcp-nest-auth;若应用中没有其他东西用到 @nestjs/microservices,也一并卸载。你原先从 @modelcontextprotocol/sdk 导入的类型(例如 CallToolResult)现来自 @modelcontextprotocol/server。
模块
若从 1.x 而来,McpModule.forRoot() 保留,只是选项更少:
// 之前,使用 @rekog/mcp-nest 1.x
McpModule.forRoot({
name: 'cat-store',
version: '1.0.0',
transport: [McpTransportType.STREAMABLE_HTTP],
mcpEndpoint: 'mcp-operations',
guards: [ApiKeyGuard],
}),
// 之后
McpModule.forRoot({
name: 'cat-store',
version: '1.0.0',
path: 'mcp-operations',
decorators: [UseGuards(ApiKeyGuard)],
}),@rekog/mcp-nest 1.x |
@nestjs/mcp |
|---|---|
name, version |
相同 |
transport |
除非 path: false,否则提供 Streamable HTTP;stdio 由 McpStdioServer 提供(参见传输方式) |
mcpEndpoint, apiPrefix |
path,位于应用的全局前缀之下 |
guards |
decorators: [UseGuards(...)] |
streamableHttp |
无需设置:每个请求都独立处理,http.responseMode 决定 2026-07-28 请求的应答形态 |
forRootAsync() |
forRootAsync(),path、decorators 和 imports 位于其顶层 |
forFeature() |
每个应用一个 MCP 服务器 |
若从 2.x 而来,strategy 及其引导启动代码不复存在。McpModule.forRoot() 接收 strategy 的 name 和 version,端点成为应用的一条路由,由 app.listen() 提供服务:
// 之前,使用 @rekog/mcp-nest 2.x
const app = await NestFactory.create(AppModule);
mcp.setHttpAdapter(app.getHttpAdapter());
app.connectMicroservice({ strategy: mcp });
await app.startAllMicroservices();
await app.listen(3000);
// 之后
const app = await NestFactory.create(AppModule);
await app.listen(3000);@McpController() 类变成普通的 @Injectable() 提供者,列在模块的 providers 而不是 controllers 里,MCP_STRATEGY 提供者也随之消失。原先由 NestFactory.createMicroservice() 启动的 stdio 服务器,改为用 McpStdioServer 从应用上下文提供,如传输方式所示。
工具、资源和提示词
装饰器保持原名,也保留大部分选项。方法的参数则变了:
// 之前,使用 @rekog/mcp-nest 1.x
@Tool({
name: 'greeting-tool',
description: 'Returns a greeting with progress updates',
parameters: z.object({ name: z.string().default('World') }),
})
async sayHello({ name }, context: Context, request: Request) {
await context.reportProgress({ progress: 50, total: 100 });
return `Hello, ${name}, from ${request.headers['user-agent']}!`;
}
// 之后
@Tool({
name: 'greeting-tool',
description: 'Returns a greeting with progress updates',
inputSchema: z.object({ name: z.string().default('World') }),
})
async sayHello({ name }: { name: string }, ctx: McpContext<Request>) {
await ctx.reportProgress(50, 100);
return `Hello, ${name}, from ${ctx.request?.headers['user-agent']}!`;
}@rekog/mcp-nest |
@nestjs/mcp |
|---|---|
parameters |
工具上用 inputSchema,提示词上用 argsSchema |
outputSchema, annotations |
相同 |
1.x 的 (args, context, request),2.x 的 @Payload() 与 @Ctx() |
(input, ctx):请求是 ctx.request,校验过的令牌是 ctx.authInfo |
context.reportProgress({{ '{' }} progress, total {{ '}' }}) |
ctx.reportProgress(progress, total) |
context.mcpServer.server.elicitInput() |
返回 inputRequired():参见询问用户 |
资源的 ({{ '{' }} uri {{ '}' }}) |
ctx.uri。资源模板的方法以输入的形式接收其变量 |
{{ '{' }} content {{ '}' }}、{{ '{' }} contents {{ '}' }} 与 {{ '{' }} messages {{ '}' }} 结果 |
原样返回,或者返回那个值本身、让模块来构建结果 |
@Injectable({{ '{' }} scope: Scope.REQUEST {{ '}' }}) |
单例提供者:从 ctx 读取属于该次调用的内容 |
McpRegistryService.registerTool()、strategy.registerTool() |
不支持:用装饰器声明工具 |
例如,一个资源模板:
// 之前,使用 @rekog/mcp-nest 1.x
@ResourceTemplate({
name: 'user-language',
description: "Get a specific user's preferred language",
mimeType: 'application/json',
uriTemplate: 'mcp://users/{name}',
})
getUserLanguage({ uri, name }) {
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify({ name, language: this.languages.of(name) }),
},
],
};
}
// 之后
@ResourceTemplate({
name: 'user-language',
description: "Get a specific user's preferred language",
mimeType: 'application/json',
uriTemplate: 'mcp://users/{name}',
})
getUserLanguage({ name }: { name: string }) {
return { name, language: this.languages.of(name) };
}在 @nestjs/mcp 下,请求作用域的提供者会在启动时失败:每个请求都由同一批单例实例处理,而调用之间不同的东西——请求、令牌和客户端——都在 ctx 里。
守卫与错误
守卫、拦截器、管道和过滤器继续可用,只需把 context.switchToRpc().getContext<McpContext>() 换成 McpExecutionContext.create(context)。上下文类型是 'mcp',不再是 'rpc'。
工具的错误仍然作为工具结果到达模型。HttpException 会把它的消息带给客户端,而在 2.x 中这需要 RpcException;其他任何错误都以 Internal server error 作答。
// 之前,使用 @rekog/mcp-nest 2.x
throw new RpcException('The address has no postcode');
// 之后
throw new BadRequestException('The address has no postcode');授权
@nestjs/mcp 是一个资源服务器,正如 MCP 规范对服务器的要求:令牌来自身份提供方,由模块校验它们(参见授权)。
@rekog/mcp-nest |
@nestjs/mcp |
|---|---|
McpAuthModule,内置的授权服务器 |
签发令牌的身份提供方(Auth0、Keycloak、Entra ID、WorkOS,或你自己的),以及指向它的 auth |
guards 中的 McpAuthJwtGuard |
auth.verifier |
@ToolScopes(['orders:write']) |
装饰器上的 scopes: ['orders:write']。带作用域的工具仍会向每个客户端列出 |
@ToolRoles(['admin']) |
一个守卫,或配合 @nestjs/authorization 的 @Can() 策略 |
@PublicTool()、allowUnauthenticatedAccess |
不支持:配置了 auth 后,每个请求都需要令牌 |
2.x 的 ctx.getUser() |
ctx.authInfo,或配合 @nestjs/authentication 的 @CurrentUser() |
这版没有的内容
- HTTP+SSE 传输,即 2024-11-05 协议修订版中的那种,不予提供。客户端通过 Streamable HTTP 连接,也就是当前客户端所用的传输方式。
- 会话不保留:每个 HTTP 请求都独立处理,这正是服务器能跑在多个实例上的原因。2025 的客户端在 HTTP 上无法在调用中途被索取输入;该调用最终以工具错误结束。
- 在运行时注册工具、一个应用里多个 MCP 服务器 以及 请求作用域的提供者 在本版本中不受支持。