NestJS中文文档
MCP / 原语
已译 191/191

原语

一个 MCP 服务器暴露三种原语:工具,即模型调用的动作;资源,即客户端读取的数据;提示词(prompt),即用户挑选的模板。每一种都是你某个提供者里的一个方法,配一个装饰器,并且和路由一样,经过相同的守卫、拦截器、管道和异常过滤器。

工具

工具是用 @Tool() 装饰的方法。inputSchema 描述它的参数:SDK 把它作为 JSON Schema 提供给客户端,并在方法运行前依据它校验每次调用。.describe() 中的文字会送达模型,模型据此填写参数:

orders/orders.tools.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Tool, type McpContext } from '@nestjs/mcp';
import * as z from 'zod';
import { OrdersService } from './orders.service.js';

@Injectable()
export class OrdersTools {
  constructor(private readonly orders: OrdersService) {}

  @Tool({
    name: 'find-order',
    description:
      'Find an order by its id, or the latest orders of a customer by email',
    inputSchema: z.object({
      orderId: z.string().optional().describe('The order id, such as ord_123'),
      email: z.email().optional().describe("The customer's email address"),
    }),
    annotations: { readOnlyHint: true },
  })
  async find({ orderId, email }: { orderId?: string; email?: string }) {
    const orders = orderId
      ? [await this.orders.findById(orderId)]
      : await this.orders.latestFor(email!);
    if (orders.length === 0 || !orders[0]) {
      throw new NotFoundException('No such order');
    }
    return orders;
  }

  @Tool({
    name: 'change-address',
    description:
      'Change the delivery address of an order that has not shipped yet',
    inputSchema: z.object({ orderId: z.string(), address: z.string().min(10) }),
    outputSchema: z.object({
      orderId: z.string(),
      address: z.string(),
      status: z.string(),
    }),
  })
  async changeAddress(
    { orderId, address }: { orderId: string; address: string },
    ctx: McpContext,
  ) {
    const order = await this.orders.changeAddress(
      orderId,
      address,
      ctx.authInfo?.clientId,
    );
    return { orderId: order.id, address: order.address, status: order.status };
  }
}

像其他任何提供者一样,把这个类注册为提供者:

orders/orders.module.ts
@Module({
  providers: [OrdersService, OrdersTools],
})
export class OrdersModule {}

方法会带着校验过的参数和本次调用的上下文被调用。它返回的内容成为工具的结果:

方法返回 客户端得到
字符串 一个文本块
其他值,且定义了 outputSchema 该值作为 structuredContent(依 schema 校验),并作为一个 JSON 文本块
其他值,且未定义 outputSchema 一个 JSON 文本块
一个 CallToolResult({{ '{' }} content, structuredContent?, isError? {{ '}' }}) 原样使用它,用于图片、音频、内嵌资源和链接
undefined 空结果

名称默认取方法名(find);工具名长度为 1 到 128 个字符,取自 A-Z a-z 0-9 _ - .,两个工具同名会在启动时失败。annotations 是给客户端的提示,例如 readOnlyHint: true,它让客户端不必先询问用户就能运行该工具。

要返回文本之外的内容,例如一张模型应当查看的图片,就自己返回一个 CallToolResult(来自 @modelcontextprotocol/server):

orders/orders.tools.ts
@Tool({
  name: 'product-photo',
  description:
    'Show the photo of a product, to compare it with what the customer describes',
  inputSchema: z.object({
    sku: z.string().describe('The product SKU, such as SKU-1042'),
  }),
  annotations: { readOnlyHint: true },
})
async photo({ sku }: { sku: string }): Promise<CallToolResult> {
  const photo = await this.catalog.photo(sku);
  return {
    content: [
      {
        type: 'image',
        data: photo.toString('base64'),
        mimeType: 'image/jpeg',
      },
    ],
  };
}
提示

模型依据名称和描述挑选工具,并依据参数各自的 .describe() 文字填写参数,所以要为模型而写:这个工具做什么、何时使用,每个参数是什么意思,并给一个示例值。工具会改动东西时,要说明清楚。

资源

资源是客户端读取、并展示给用户或交给模型的数据。@Resource() 提供一个固定 URI;@ResourceTemplate() 提供匹配 RFC 6570 模板的每个 URI,方法会收到模板中的变量:

orders/orders.tools.ts
@Resource({
  uri: 'catalog://products',
  description: 'Every product and its stock',
  mimeType: 'application/json',
})
catalog() {
  return this.catalog.all();
}

@ResourceTemplate({
  uriTemplate: 'orders://{orderId}',
  description: 'One order',
  mimeType: 'application/json',
})
async order({ orderId }: { orderId: string }) {
  const order = await this.orders.findById(orderId);
  if (!order) {
    throw new NotFoundException();
  }
  return order;
}

字符串按 mimeType 指定的类型作为文本发送,Uint8Array 或 Buffer 作为二进制块发送,ReadResourceResult({{ '{' }} contents: [...] {{ '}' }})原样发送,其他任何内容作为 JSON 发送。NotFoundException 会以规范中的「资源未找到」错误作答。

资源适用于客户端原样载入对话的内容:商品目录、某个订单、退货政策。何时读取由客户端决定,通常是在用户附加某个资源时。要让模型带参数去查询,请给它一个工具。

提示词

提示词是用户在客户端里挑选的消息模板。它的参数同样是一个 schema,客户端会逐个向用户询问:

orders/orders.tools.ts
@Prompt({
  name: 'draft-reply',
  description: 'Draft a reply to a customer about an order',
  argsSchema: z.object({
    orderId: z.string().describe('The order the customer wrote about'),
    tone: z.enum(['formal', 'friendly']).describe('How the reply sounds'),
  }),
})
async draftReply({
  orderId,
  tone,
}: {
  orderId: string;
  tone: 'formal' | 'friendly';
}) {
  const order = await this.orders.findById(orderId);
  return `Draft a ${tone} reply to the customer of order ${orderId}. The order: ${JSON.stringify(order)}`;
}

字符串是一条用户消息;消息数组,或一个 GetPromptResult({{ '{' }} messages: [...] {{ '}' }}),会原样发送。

提示词还可以用不止一条消息开启对话。下面这个先把订单作为内嵌资源附上,再提出问题:

orders/orders.tools.ts
@Prompt({
  name: 'review-complaint',
  description: 'Review a complaint about an order',
  argsSchema: z.object({
    orderId: z.string().describe('The order the complaint is about'),
  }),
})
async reviewComplaint({
  orderId,
}: {
  orderId: string;
}): Promise<PromptMessage[]> {
  const order = await this.orders.findById(orderId);
  return [
    {
      role: 'user',
      content: {
        type: 'resource',
        resource: {
          uri: `orders://${orderId}`,
          mimeType: 'application/json',
          text: JSON.stringify(order),
        },
      },
    },
    {
      role: 'user',
      content: {
        type: 'text',
        text: 'Is the complaint about this order justified? Answer in two sentences.',
      },
    },
  ];
}

PromptMessage 是 @modelcontextprotocol/server 中的类型。

试一试

启动应用后,端点在 http://localhost:3000/mcp。MCP Inspector 会列出并调用服务器暴露的一切:

$ npx @modelcontextprotocol/inspector

选择 Streamable HTTP,输入 URL,再点 Connect。连接远程 MCP 服务器的助手用的也是同一个 URL。

调用上下文

每个 MCP 方法的第二个参数都是一个 McpContext:

属性 是什么
kind、name、uri 'tool'、'resource' 或 'prompt';工具或提示词的名称,或资源的名称;正在读取的 URI
authInfo 校验过的访问令牌,配合授权使用:clientId、scopes、expiresAt、extra
request HTTP 平台的请求(Express、Fastify、Node 适配器),带其请求头和中间件在其上设置的任何内容;对内存测试客户端,是一个普通的 {{ '{' }} method, url, headers {{ '}' }} 对象;在 stdio 下为 undefined
requestInfo SDK 所服务的、符合 Web 标准的 Request
transport、era 'http' 或 'stdio';'modern'(协议修订版 2026-07-28)或 'legacy'(2025 年的各修订版)
signal 一个 AbortSignal,在客户端取消调用或断开时中止:把它继续传给 fetch() 和你的数据库
reportProgress(progress, total?, message?) 在客户端要求时发送进度通知
server SDK 自己的请求上下文,用于其余内容(mcpReq.envelope、mcpReq.inputResponses)
@Tool({
  name: 'export-orders',
  description: 'Export a month of orders as CSV',
})
async export(_input: unknown, ctx: McpContext) {
  const pages = await this.orders.pages();
  for (let page = 0; page < pages; page++) {
    ctx.signal.throwIfAborted();
    await this.orders.exportPage(page, { signal: ctx.signal });
    await ctx.reportProgress(page + 1, pages);
  }
  return 'Exported';
}

询问用户。 需要用户确认、或缺少某个值的工具,会返回 @modelcontextprotocol/server 的 inputRequired():客户端去询问用户,然后带着答案再次调用该工具,由 acceptedContent() 读取并校验这个答案:

@Tool({
  name: 'cancel-order',
  description: 'Cancel an order',
  inputSchema: z.object({ orderId: z.string() }),
})
cancel({ orderId }: { orderId: string }, ctx: McpContext) {
  const Confirmation = z.object({ confirm: z.boolean() });
  const answer = acceptedContent(
    ctx.server.mcpReq.inputResponses,
    'confirm',
    Confirmation,
  );
  if (!answer) {
    return inputRequired({
      inputRequests: {
        confirm: inputRequired.elicit({
          message: `Cancel order ${orderId}?`,
          requestedSchema: Confirmation,
        }),
      },
    });
  }
  return answer.confirm ? this.orders.cancel(orderId) : 'Kept the order';
}
警告

在 HTTP 下,这要求客户端为 2026-07-28 修订版。2025 修订版的客户端要通过服务器发起的请求来询问,而这需要会话,端点却一个会话都不保留:该调用最终以工具错误结束。在 stdio 下两者都能工作。

守卫、拦截器、管道和过滤器

每次调用都会经过 Nest 的增强器,它们可以绑定在类上、方法上或全局,与路由相同。执行上下文的类型是 'mcp',McpExecutionContext 读取该调用,就像 GqlExecutionContext 对 GraphQL 解析器所做的那样。只有客服团队可以修改订单:

orders/support-team.guard.ts
import {
  Injectable,
  type CanActivate,
  type ExecutionContext,
} from '@nestjs/common';
import { McpExecutionContext } from '@nestjs/mcp';

@Injectable()
export class SupportTeamGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const mcp = McpExecutionContext.create(context);
    return mcp.getAuthInfo()?.extra?.team === 'support';
  }
}
orders/orders.tools.ts
@Tool({ name: 'change-address', ... })
@UseGuards(SupportTeamGuard)
async changeAddress(...) {}

McpExecutionContext.create(context) 提供 getInput()(参数)、getContext()(McpContext)、getKind()、getName()、getRequest() 和 getAuthInfo()。拦截器在方法的返回值成为结果之前看到它,可以为其计时、记录日志或做转换。管道把输入当作该调用的 body,因此全局的 ValidationPipe({{ '{' }} transform: true {{ '}' }}) 能校验你用来标注输入类型的 DTO 类,与路由上一样。用 createParamDecorator() 创建的自定义参数装饰器在输入和上下文之后工作,与 GraphQL 解析器相同:add(input, ctx, @CurrentUser() user)。

拦截器的工作方式相同。下面这个记录每次调用的耗时,以及它的种类和名称:

orders/call-logging.interceptor.ts
import {
  Injectable,
  Logger,
  type CallHandler,
  type ExecutionContext,
  type NestInterceptor,
} from '@nestjs/common';
import { McpExecutionContext } from '@nestjs/mcp';
import { tap, type Observable } from 'rxjs';

@Injectable()
export class CallLoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('MCP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
    const mcp = McpExecutionContext.create(context);
    const started = performance.now();
    return next
      .handle()
      .pipe(
        tap(() =>
          this.logger.log(
            `${mcp.getKind()} ${mcp.getName()} took ${Math.round(performance.now() - started)} ms`,
          ),
        ),
      );
  }
}

在 OrdersTools 类上加 @UseInterceptors(CallLoggingInterceptor),就会记录该类每个工具、资源和提示词。

警告

全局守卫、拦截器和过滤器(app.useGlobalGuards()、APP_GUARD)在 MCP 调用上也会运行,正如它们在 GraphQL 解析器上运行一样,也会在承载该调用的 HTTP 请求上运行。为 HTTP 路由编写、且会调用 context.switchToHttp().getRequest() 的增强器,应先检查 context.getType() === 'http'。

错误

工具抛出的内容会变成一个带 isError: true 的结果,模型读取它并可从中恢复:HttpException 的消息(如 BadRequestException('The address has no postcode')),对其他任何错误则是 Internal server error,后者由 Nest 的异常处理器记录日志,其消息永远不会到达客户端。资源和提示词则以 JSON-RPC 错误作答:NotFoundException 作为资源未找到,BadRequestException 作为无效参数,其他 HttpException 作为内部错误并携带其消息和状态码。异常过滤器也可以代为作答:它返回的内容就是结果,而它抛出的 ProtocolError(来自 @modelcontextprotocol/server)就是那个 JSON-RPC 错误。

@Catch(PaymentProviderError)
export class PaymentProviderFilter implements ExceptionFilter {
  catch(exception: PaymentProviderError, host: ArgumentsHost) {
    if (host.getType<McpContextType>() !== 'mcp') {
      throw exception;
    }
    return {
      content: [
        {
          type: 'text',
          text: 'Payments are down; try again in a few minutes.',
        },
      ],
      isError: true,
    };
  }
}

授权

订单 API 的 MCP 服务器要回答关于客户的问题,因此需要已登录的用户。在 MCP 中,服务器是 OAuth 2.1 的 资源服务器:客户端从网店的身份提供方(Auth0、Keycloak、Entra ID、WorkOS,或你自己的)取得访问令牌,并在每个请求中发送它。服务器负责校验,从不签发令牌。配置 auth:

app.module.ts
McpModule.forRoot({
  name: 'cat-store',
  version: '1.0.0',
  auth: {
    verifier: IdentityProviderTokenVerifier,
    resource: 'https://api.catstore.example/mcp',
    authorizationServers: ['https://auth.catstore.example'],
    scopesSupported: ['orders:read'],
  },
}),
  • resource 是 MCP 服务器的规范 URL。客户端向身份提供方索取针对它的令牌,服务器只接受针对它签发的令牌(即其受众),这是规范的要求。
  • authorizationServers 是其令牌被接受的签发方。模块把它们连同 scopesSupported 一起,作为受保护资源元数据(RFC 9728)发布在 /.well-known/oauth-protected-resource/mcp,客户端在那里发现如何登录。
  • 不带有效令牌的请求会得到 401,并附带指向该元数据的 WWW-Authenticate: Bearer 质询。正是这个质询启动了客户端的登录流程。

verifier 决定哪些令牌有效。它是你自己的一个类,带 verifyAccessToken(token),返回令牌的 AuthInfo,或返回 null 表示拒绝。Nest 负责实例化它,因此它可以注入所需的东西。对 JWT 访问令牌,@nestjs/authentication 的 JwtVerifier 会依据身份提供方的密钥、签发方、受众和有效期校验签名:

auth/identity-provider-token.verifier.ts
import { Injectable } from '@nestjs/common';
import { JwtVerifier } from '@nestjs/authentication';
import type { McpTokenVerifier } from '@nestjs/mcp';
import type { AuthInfo } from '@modelcontextprotocol/server';

const RESOURCE = 'https://api.catstore.example/mcp';

@Injectable()
export class IdentityProviderTokenVerifier implements McpTokenVerifier {
  private readonly jwt = new JwtVerifier({
    jwks: 'https://auth.catstore.example/.well-known/jwks.json',
    issuer: 'https://auth.catstore.example',
    audience: RESOURCE,
    type: 'at+jwt',
  });

  async verifyAccessToken(token: string): Promise<AuthInfo> {
    // 签名不对、令牌过期或受众不符会抛出 JwtError:以 401 作答。
    const claims = await this.jwt.verify(token);
    return {
      token,
      clientId: String(claims.client_id ?? claims.sub),
      scopes: typeof claims.scope === 'string' ? claims.scope.split(' ') : [],
      expiresAt: claims.exp,
      resource: new URL(RESOURCE),
      extra: { team: claims.team },
    };
  }
}

带 status: 401 的错误(JwtError、UnauthorizedException)表示拒绝该令牌;其他任何错误(例如密钥取不到)以 500 作答。不透明令牌则改走你身份提供方的自省端点,同样藏在同一个方法后面。

对于不透明令牌,verifier 改为询问身份提供方的自省端点(RFC 7662):

auth/introspection-token.verifier.ts
import { Injectable } from '@nestjs/common';
import type { McpTokenVerifier } from '@nestjs/mcp';
import type { AuthInfo } from '@modelcontextprotocol/server';

const RESOURCE = 'https://api.catstore.example/mcp';

@Injectable()
export class IntrospectionTokenVerifier implements McpTokenVerifier {
  async verifyAccessToken(token: string): Promise<AuthInfo | null> {
    const credentials = btoa(
      `${process.env.INTROSPECTION_CLIENT_ID}:${process.env.INTROSPECTION_CLIENT_SECRET}`,
    );
    const response = await fetch(
      'https://auth.catstore.example/oauth/introspect',
      {
        method: 'POST',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
          authorization: `Basic ${credentials}`,
        },
        body: new URLSearchParams({ token }),
      },
    );
    if (!response.ok) {
      // 无法判断该令牌:以 500 作答。
      throw new Error(`Token introspection failed with ${response.status}`);
    }
    const claims = (await response.json()) as {
      active: boolean;
      aud?: string | string[];
      client_id: string;
      scope?: string;
      exp: number;
    };
    if (!claims.active || ![claims.aud].flat().includes(RESOURCE)) {
      return null; // 以 401 作答。
    }
    return {
      token,
      clientId: claims.client_id,
      scopes: claims.scope ? claims.scope.split(' ') : [],
      expiresAt: claims.exp,
      resource: new URL(RESOURCE),
    };
  }
}

无论你写哪种 verifier,模块都会检查它返回的两件事:resource 必须是 auth.resource 那个 URL,expiresAt 必须已设置且在将来。任一项不满足的令牌都会以 401 拒绝。

作用域。 工具、资源或提示词上的 scopes 规定了令牌必须携带什么才能调用它。缺少这些作用域的调用会在方法运行之前得到 403,并在质询中列出缺失的作用域,客户端随后请用户授予它们(逐步提升授权)。auth 中的 requiredScopes 要求每个请求都带作用域:

@Tool({ name: 'change-address', ..., scopes: ['orders:write'] })

声明 scopes 却没有 auth 会在启动时失败,因为没有任何东西会去检查它们。令牌在方法中是 ctx.authInfo,在守卫中是 McpExecutionContext.create(context).getAuthInfo(),用于作用域无法表达的判断。

配合 @nestjs/authentication 与 @nestjs/authorization。 它们的全局守卫会在每次 MCP 调用上运行。认证守卫用你的提供者、依据该调用所来自的 HTTP 请求对调用进行认证:接受身份提供方令牌的 JwtBearerProvider 也接受 MCP 客户端的令牌。于是 @CurrentUser() 和 AuthenticationContext 在工具中可用,@Can() 策略为每次调用作决定:

orders/orders.tools.ts
@Tool({
  name: 'refund',
  description: 'Refund an order',
  inputSchema: z.object({ orderId: z.string() }),
})
@Can(OrderPolicy, 'refund')
refund(
  { orderId }: { orderId: string },
  ctx: McpContext,
  @CurrentUser() agent: Agent,
) {
  return this.orders.refund(orderId, agent);
}

用 decorators: [Public()] 让端点的路由豁免认证守卫,并让 auth 应答它的未认证请求:守卫自带的质询不会把 MCP 客户端指向该元数据。对某次调用的拒绝是一个工具错误,Unauthorized 或 Forbidden;没有声明 @Can() 的工具会被拒绝,与路由一样。在 stdio 下没有请求,因此除非你自己的某个提供者从环境中完成认证,调用就是匿名的。

提示

这需要 @nestjs/authentication 0.1.3 与 @nestjs/authorization 0.1.1 或更高版本,即最早认识 MCP 调用(上下文类型 'mcp')的版本。使用更早的版本时,全局守卫在调用上找不到凭据:请给你的工具所在的提供者标上 @Public()。

按请求可见性

scopes 让工具继续被列出、并在调用时发起质询,这适合那种能向用户索取更多授权的客户端。有时某个工具在某个请求里根本不该出现:它在功能开关后面,它属于另一个租户,或者客户端永远不会被授予它的作用域。网店先把 refund 开放给少数客服。filter 为每个请求挑选要提供的原语,且早于其服务器注册它们:

app.module.ts
McpModule.forRootAsync({
  imports: [FlagsModule],
  inject: [FlagsService],
  useFactory: (flags: FlagsService) => ({
    name: 'cat-store',
    version: '1.0.0',
    filter: async ({ tools }, { authInfo }) => {
      const refunds = await flags.isEnabled('refunds', authInfo?.clientId);
      return {
        tools: tools.filter((tool) => tool.name !== 'refund' || refunds),
      };
    },
  }),
}),
  • 它接收应用声明的每一个原语,分别作为 tools、resources、resourceTemplates 和 prompts,并为每一类返回一个子集。未列出的那一类保留该类全部原语。第二个参数是服务器的构建依据:transport、era、authInfo(配置了 auth 时)和 request,即 HTTP 平台的请求。
  • 被排除的原语既不列出也不可调用:对它的调用会在任何守卫运行之前得到 SDK 的未知工具错误。
  • 当一个工具都不剩时,服务器不再公布工具,tools/list 回答「Method not found」,而不是空列表。资源和提示词同理。
  • 它在每个 HTTP 请求上运行一次。在 stdio 下,它在每个连接上运行一次;当客户端先以 server/discover 探测、随后回退到 2025 握手时,会再运行一次:同一个连接上运行两次,era 不同。
  • 如果它抛出异常,或返回了没被交给它的原语,该请求失败。绝不会因此改为给它提供每个原语。
提示

客户端会保留它取到的列表,因此 filter 返回值的变化(例如某个开关被打开)要等它再次列出工具时才显现。

装饰器

装饰器 选项 方法被调用时传入
@Tool() name、title、description、inputSchema、outputSchema、annotations、icons、_meta、scopes 校验过的参数、上下文
@Resource() uri、name、title、description、mimeType、size、annotations、icons、_meta、cacheHint、scopes {{ '{' }}{{ '}' }}、上下文(ctx.uri)
@ResourceTemplate() uriTemplate,以及上述其他选项 模板中的变量、上下文
@Prompt() name、title、description、argsSchema、icons、_meta、scopes 校验过的参数、上下文