NestJS中文文档
教程 / 用 Node.js 构建 MCP 服务器
已译 191/191

用 Node.js 构建 MCP 服务器

使用 NestJS,在 Node.js 和 TypeScript 中构建 MCP 服务器:通过 HTTP 和 stdio 提供工具、资源和提示词(prompt),校验 OAuth 访问令牌,并编写真实的测试。

一个客服团队在 AI 助手(Claude、ChatGPT,或 IDE 中的代理)里工作,希望助手能操作服务台的工单:找出与退款有关的工单、读取对话、起草回复,并在有人批准后发送。Model Context Protocol(MCP)是助手访问服务台的方式:服务台运行一个 MCP 服务器,助手则是它的客户端。大多数示例都是基于原始 SDK 的单文件,既没有身份验证也没有测试。本教程用 @nestjs/mcp 构建一个可以真正部署的服务器,其中的工具、资源和提示词都是某个提供者的方法。

协议本身是简单的部分。困难之处在于,服务器是以持有令牌者的身份行事的:无论模型要求什么,账单团队的代理都绝不能看到配送团队的工单;只能读取的助手也不能发送回复。

到最后,这个服务器将能够:

  • 提供一个只读的 工具 用于搜索工单,以及一个用于回复的工具,两者都带有为模型编写的 Zod schema,以及模型能读懂的错误。
  • 把每张工单作为 资源 提供,并提供一个用于起草回复的 提示词。
  • 作为 OAuth 2.1 资源服务器,只接受为它签发的 JWT 访问令牌;对没有令牌的客户端,指向它的受保护资源元数据。
  • 把每个查询都限定在令牌中指明的团队,并要求 tickets:write 作用域才能回复。
  • 拒绝来自其他站点网页的请求,以及 Host 不在其应答范围内的请求。
  • 通过 stdio 提供相同的工具,供在本地启动它的助手使用。
  • 把每次调用上报给 NestJS Observe,并用对应的工具、资源或提示词命名。
  • 用 SDK 自带的客户端,在内存中、通过 HTTP 和通过 stdio,对 PostgreSQL 验证上述全部能力。

服务器对外提供下列内容,右列是添加它们的小节:

原语 小节
工具 search-tickets 与 reply-to-ticket 为模型编写工具
工单的资源模板、提示词 draft-reply 把工单作为资源提供
POST /mcp、GET /.well-known/oauth-protected-resource/mcp 校验 OAuth 访问令牌
node dist/stdio.js 通过 stdio 提供相同的工具
提示

完成后的应用位于 GitHub:nestjs/example-mcp-server,其中包含测试和 CI 工作流。

你需要 Node.js 22.18 或更高版本(开发用令牌脚本会直接运行 TypeScript),以及用于在本地运行 PostgreSQL 的 Docker。

创建项目

使用 Nest CLI 创建项目。--minimal 会生成一个代码集中在单个文件中的应用,本教程会替换掉该文件。它还会安装 NestJS Observe SDK,即 @nestjs/observe,并将其接入该文件;应用自身的文件保持不变:

$ npm i -g @nestjs/cli
$ nest new helpdesk-mcp --minimal
$ cd helpdesk-mcp

安装 Node 适配器、@nestjs/mcp 及其所基于的 MCP SDK、Zod、@nestjs/config、@nestjs/drizzle,以及用于 JWT 校验器的 @nestjs/authentication,以替代 Express 适配器。SDK 的客户端用于测试:

$ npm uninstall @nestjs/platform-express @types/express
$ npm i --save @nestjs/platform-node @nestjs/mcp @modelcontextprotocol/server zod @nestjs/config @nestjs/drizzle drizzle-orm@rc pg @nestjs/authentication
$ npm i --save-dev @modelcontextprotocol/client drizzle-kit@rc @types/pg @nestjs/testing vitest vite

删除 src/main.ts:组装服务器 会写入一个新文件。在容器中启动 PostgreSQL:

$ docker run -d --name helpdesk-db -e POSTGRES_PASSWORD=helpdesk -e POSTGRES_DB=helpdesk -p 5432:5432 postgres:17

配置是一个 Zod schema。ConfigModule 在启动时用它校验环境变量,变量缺失或格式错误时服务器会拒绝启动:

src/config.ts
import { z } from 'zod';

const list = z
  .string()
  .transform((value) => value.split(',').map((item) => item.trim()).filter(Boolean));

export const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().default(3000),
  DATABASE_URL: z.url(),
  // MCP 服务器的公开 URL:其访问令牌的受众。
  MCP_RESOURCE: z.url(),
  // 身份提供者的签发者,与其令牌 `iss` 声明中的写法完全一致。
  OIDC_ISSUER: z.url(),
  // 该签发者的签名密钥:其 /.well-known/openid-configuration 中的 `jwks_uri`。
  OIDC_JWKS_URL: z.url(),
  // 令牌的 `aud`,当提供者无法把它设为 MCP_RESOURCE 时使用(Entra ID 会把 API 的客户端 ID 放在那里)。
  OIDC_AUDIENCE: z.string().min(1).optional(),
  // 其访问令牌携带的 `typ` 头:`at+jwt`(RFC 9068)。对不发送该头的提供者留空。
  OIDC_TOKEN_TYPE: z.string().default('at+jwt'),
  // 指明代理所属团队的声明。
  OIDC_TEAM_CLAIM: z.string().min(1).default('team'),
  // Host 头可以指明的主机名,逗号分隔。
  MCP_ALLOWED_HOSTS: list.default(['localhost', '127.0.0.1', '[::1]']),
  // 通过 stdio 时没有令牌:本地用户工作的团队。
  HELPDESK_TEAM: z.string().regex(/^[a-z0-9-]+$/).optional(),
});

export type Env = z.infer<typeof envSchema>;

每个变量都在用到它的地方解释。在项目根目录创建 .env 文件,写入数据库连接,以及替代身份提供者的 开发用令牌签发器:

DATABASE_URL=postgres://postgres:helpdesk@localhost:5432/helpdesk
MCP_RESOURCE=http://localhost:3000/mcp
OIDC_ISSUER=http://localhost:3001
OIDC_JWKS_URL=http://localhost:3001/jwks.json

把工单存储在 PostgreSQL 中

服务台有团队、团队的工单,以及每张工单上的回复。团队的 id 是一个 slug,例如 billing,代理的令牌通过 team 声明携带它:

src/database/schema.ts
import { index, integer, pgEnum, pgTable, text, timestamp } from 'drizzle-orm/pg-core';

const at = (name: string) => timestamp(name, { withTimezone: true, mode: 'date' });

export const ticketStatus = pgEnum('ticket_status', ['open', 'pending', 'solved']);

export const teams = pgTable('teams', {
  // 诸如 `billing` 的 slug:代理令牌中 `team` 声明的值。
  id: text('id').primaryKey(),
  name: text('name').notNull(),
});

export const tickets = pgTable(
  'tickets',
  {
    id: integer('id').primaryKey().generatedAlwaysAsIdentity({ startWith: 1001 }),
    teamId: text('team_id')
      .notNull()
      .references(() => teams.id),
    subject: text('subject').notNull(),
    body: text('body').notNull(),
    customerEmail: text('customer_email').notNull(),
    status: ticketStatus('status').notNull().default('open'),
    createdAt: at('created_at').notNull().defaultNow(),
    updatedAt: at('updated_at').notNull().defaultNow(),
  },
  // 每个查询都从团队开始:一次搜索就是对某个团队工单的扫描。
  (table) => [index('tickets_team_id_updated_at_idx').on(table.teamId, table.updatedAt)],
);

export const replies = pgTable(
  'replies',
  {
    id: integer('id').primaryKey().generatedAlwaysAsIdentity(),
    ticketId: integer('ticket_id')
      .notNull()
      .references(() => tickets.id, { onDelete: 'cascade' }),
    // 发送它的代理,按其令牌中的名称记录。
    author: text('author').notNull(),
    body: text('body').notNull(),
    createdAt: at('created_at').notNull().defaultNow(),
  },
  (table) => [index('replies_ticket_id_idx').on(table.ticketId)],
);

export type Ticket = typeof tickets.$inferSelect;
export type Reply = typeof replies.$inferSelect;
export type TicketStatus = (typeof ticketStatus.enumValues)[number];

工单编号从 1001 开始,与客户引用的编号一致,而且很容易猜:任何逻辑都不能依赖编号不被知晓。在项目根目录添加 drizzle.config.ts:

drizzle.config.ts
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  dialect: 'postgresql',
  schema: './src/database/schema.ts',
  out: './drizzle',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

生成迁移并应用它(参见 迁移):

$ npx drizzle-kit generate --name=helpdesk
$ npx drizzle-kit migrate

drizzle-kit 会从 .env 读取 DATABASE_URL。一个种子脚本会添加两个团队和几张工单。它先清空这些表,因此只适用于开发数据库:

src/database/seed.ts
// 开发数据:两个团队及其工单。它会先清空这三张表。
import { drizzle } from 'drizzle-orm/node-postgres';
import { sql } from 'drizzle-orm';
import { Pool } from 'pg';
import { envSchema } from '../config.js';
import { replies, teams, tickets } from './schema.js';

const { DATABASE_URL } = envSchema.pick({ DATABASE_URL: true }).parse(process.env);
const pool = new Pool({ connectionString: DATABASE_URL });
const db = drizzle({ client: pool });

try {
  await db.transaction(async (tx) => {
    await tx.execute(sql`TRUNCATE replies, tickets, teams RESTART IDENTITY CASCADE`);
    await tx.insert(teams).values([
      { id: 'billing', name: 'Billing' },
      { id: 'shipping', name: 'Shipping' },
    ]);
    const created = await tx
      .insert(tickets)
      .values([
        {
          teamId: 'billing',
          subject: 'Charged twice for order 5521',
          body: 'My card shows two charges of 49.90 for the same order yesterday. Please refund one.',
          customerEmail: 'maria@example.com',
        },
        {
          teamId: 'billing',
          subject: 'Refund for a cancelled subscription',
          body: 'I cancelled on the 3rd but was charged on the 5th. I would like that refunded.',
          customerEmail: 'li@example.com',
          status: 'pending',
        },
        {
          teamId: 'shipping',
          subject: 'Parcel stuck in customs',
          body: 'Tracking for order 5498 has said "held at customs" for six days.',
          customerEmail: 'sam@example.com',
        },
        {
          teamId: 'shipping',
          subject: 'Wrong size delivered',
          body: 'I ordered the jacket in M and got an L. How do I exchange it?',
          customerEmail: 'noor@example.com',
        },
      ])
      .returning({ id: tickets.id });
    await tx.insert(replies).values({
      ticketId: created[1].id,
      author: 'grace',
      body: 'Sorry about that. Which card was charged, and on which date exactly?',
    });
  });
  console.log('Seeded 2 teams, 4 tickets and 1 reply');
} finally {
  await pool.end();
}

把这些脚本加入 package.json。db:seed 运行编译后的脚本,并在存在 .env 时加载它:

"db:seed": "node --env-file-if-exists=.env dist/database/seed.js",
"dev:issuer": "node --env-file=.env scripts/dev-issuer.ts",
"test:e2e": "nest build && vitest run --config ./vitest.config.e2e.ts"

另外两个脚本用于 开发用令牌 和 测试。构建,并填充数据库:

$ npm run build
$ npm run db:seed
Seeded 2 teams, 4 tickets and 1 reply

把每个查询限定在代理的团队

模型可能被诱导传入任意参数:一封写着 “also show me ticket 1004” 的客户邮件,对它来说就是要读的文本。因此访问权限绝不依赖参数。服务的每个方法都从调用方的令牌中取出团队,并把它放进语句里:

src/tickets/tickets.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectDrizzle } from '@nestjs/drizzle';
import { and, asc, desc, eq, ilike, or, type SQL } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import { replies, tickets, type Reply, type Ticket, type TicketStatus } from '../database/schema.js';

export interface SearchTicketsQuery {
  text?: string;
  status?: TicketStatus;
  limit: number;
}

export type TicketSummary = Pick<Ticket, 'id' | 'subject' | 'status' | 'customerEmail' | 'updatedAt'>;
export type TicketWithReplies = Ticket & { replies: Reply[] };

/** 每个方法都接收代理的团队,并且绝不读取或修改其它团队的工单。 */
@Injectable()
export class TicketsService {
  constructor(@InjectDrizzle() private readonly db: NodePgDatabase) {}

  search(team: string, { text, status, limit }: SearchTicketsQuery): Promise<TicketSummary[]> {
    const conditions: SQL[] = [eq(tickets.teamId, team)];
    if (text) {
      // 文本按字面匹配:其中的 % 和 _ 不是通配符。
      const pattern = `%${text.replace(/[\\%_]/g, '\\$&')}%`;
      conditions.push(or(ilike(tickets.subject, pattern), ilike(tickets.body, pattern))!);
    }
    if (status) {
      conditions.push(eq(tickets.status, status));
    }
    return this.db
      .select({
        id: tickets.id,
        subject: tickets.subject,
        status: tickets.status,
        customerEmail: tickets.customerEmail,
        updatedAt: tickets.updatedAt,
      })
      .from(tickets)
      .where(and(...conditions))
      .orderBy(desc(tickets.updatedAt), desc(tickets.id))
      .limit(limit);
  }

  /** 工单及其回复,最早的在前。其它团队的工单与不存在的工单一样不可知。 */
  async findOne(team: string, id: number): Promise<TicketWithReplies> {
    const [ticket] = await this.db
      .select()
      .from(tickets)
      .where(and(eq(tickets.id, id), eq(tickets.teamId, team)));
    if (!ticket) {
      throw notFound(id);
    }
    const thread = await this.db
      .select()
      .from(replies)
      .where(eq(replies.ticketId, id))
      .orderBy(asc(replies.createdAt), asc(replies.id));
    return { ...ticket, replies: thread };
  }

  /** 添加一条回复,并可选地设置状态:两者都做,或都不做。 */
  reply(team: string, id: number, author: string, body: string, status?: TicketStatus) {
    return this.db.transaction(async (tx) => {
      // 团队是查找工单的语句的一部分,该行会保持锁定,直到回复写入。
      const [ticket] = await tx
        .update(tickets)
        .set({ updatedAt: new Date(), ...(status && { status }) })
        .where(and(eq(tickets.id, id), eq(tickets.teamId, team)))
        .returning({ id: tickets.id, status: tickets.status });
      if (!ticket) {
        throw notFound(id);
      }
      const [reply] = await tx
        .insert(replies)
        .values({ ticketId: id, author, body })
        .returning({ id: replies.id });
      return { ticketId: ticket.id, replyId: reply.id, status: ticket.status };
    });
  }
}

function notFound(id: number) {
  return new NotFoundException(`Ticket ${id} not found`);
}
  • 团队位于 WHERE 子句中,而不是在读取之后再检查。其它团队的工单会像不存在的工单一样应答,因此账单团队甚至无法得知存在哪些配送工单编号。
  • 一次回复是一个事务。 UPDATE 在团队范围内找到并锁定工单,然后插入回复;其它团队的工单不会更新任何行,也不会插入任何内容。
  • 搜索文本按字面匹配:% 和 _ 会被转义。

知道调用者是谁

模块会在任何方法运行之前校验令牌(参见 校验 OAuth 访问令牌)。一个参数装饰器从中读取代理:客服代理,也就是助手所代表的人:

src/tickets/agent.decorator.ts
import { createParamDecorator, ForbiddenException, type ExecutionContext } from '@nestjs/common';
import { McpExecutionContext } from '@nestjs/mcp';

/** 调用者是谁:客服代理所属的团队,以及其回复署名所用的名字。 */
export interface Agent {
  team: string;
  username: string;
}

/**
 * 一次调用所代表的代理。通过 HTTP 时来自已校验的访问令牌;通过 stdio 时没有令牌,
 * 来自本地客户端启动服务器时的环境变量。
 */
export const CurrentAgent = createParamDecorator((_data: unknown, context: ExecutionContext): Agent => {
  const ctx = McpExecutionContext.create(context).getContext();
  const agent =
    ctx.transport === 'stdio'
      ? { team: process.env.HELPDESK_TEAM, username: process.env.USER ?? 'local' }
      : { team: ctx.authInfo?.extra?.team, username: ctx.authInfo?.extra?.username };
  if (typeof agent.team !== 'string' || !agent.team || typeof agent.username !== 'string') {
    // 令牌有效,但未授予任何团队的工单。
    throw new ForbiddenException(
      ctx.transport === 'stdio' ? 'Set HELPDESK_TEAM to the team to work in' : 'The access token names no team',
    );
  }
  return { team: agent.team, username: agent.username };
});

McpExecutionContext.create(context) 读取 MCP 调用的上下文,就像 GqlExecutionContext 之于 GraphQL(参见 守卫、拦截器、管道和过滤器)。通过 HTTP 时,authInfo 是校验器返回的内容;通过 stdio 时没有令牌,团队来自环境变量。由传输方式决定,因此 HTTP 请求绝不会回退到环境变量中的团队。有效但不含团队的令牌返回 403:401 会让客户端重新登录,而这帮不上忙。

为模型编写工具

工具就是一个带 @Tool() 的方法。模型根据名称和描述来选择工具,并根据 .describe() 文本填写参数,因此这些文本要说明工具做什么、何时使用,以及每个参数的含义并给出示例。SDK 会在方法运行之前按 schema 校验每次调用:

src/tickets/tickets.tools.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Prompt, ResourceTemplate, Tool, type McpContext } from '@nestjs/mcp';
import type { PromptMessage } from '@modelcontextprotocol/server';
import { z } from 'zod';
import { CurrentAgent, type Agent } from './agent.decorator.js';
import { TicketsService } from './tickets.service.js';

// 数据库的整数范围:更大的数字会导致 500,而不是校验错误。
const ticketId = z.number().int().min(1).max(2_147_483_647).describe('The ticket number, such as 1042');
const status = z.enum(['open', 'pending', 'solved']);

const searchTicketsSchema = z.object({
  text: z
    .string()
    .trim()
    .min(2)
    .max(200)
    .optional()
    .describe('Words to find in the subject or the description, such as "refund" or an order number'),
  status: status.optional().describe('Only tickets in this status. Leave it out to search all of them'),
  limit: z.number().int().min(1).max(50).default(10).describe('How many tickets to return, newest first'),
});

const replyToTicketSchema = z.object({
  ticketId,
  message: z
    .string()
    .trim()
    .min(1)
    .max(5000)
    .describe('The reply as the customer will read it, in plain text'),
  status: z
    .enum(['pending', 'solved'])
    .optional()
    .describe('"pending" when you asked the customer something, "solved" when nothing is left to do. Leave it out to keep the status'),
});

@Injectable()
export class TicketsTools {
  constructor(private readonly tickets: TicketsService) {}

  @Tool({
    name: 'search-tickets',
    description:
      "Search the support team's tickets by text and status. Returns each ticket's number, subject, status and customer, newest first; read a ticket's full thread as the resource tickets://{ticketId}",
    inputSchema: searchTicketsSchema,
    annotations: { readOnlyHint: true },
  })
  search(input: z.infer<typeof searchTicketsSchema>, _ctx: McpContext, @CurrentAgent() agent: Agent) {
    return this.tickets.search(agent.team, input);
  }

  @Tool({
    name: 'reply-to-ticket',
    description:
      "Reply to a ticket's customer, and optionally change the ticket's status. The customer reads the reply: only call it with text the user has approved",
    inputSchema: replyToTicketSchema,
    outputSchema: z.object({ ticketId: z.number().int(), replyId: z.number().int(), status }),
    // 它会往工单上追加内容而不删除任何东西,但重试会追加第二条回复。
    annotations: { destructiveHint: false, idempotentHint: false },
    scopes: ['tickets:write'],
  })
  reply(
    { ticketId, message, status }: z.infer<typeof replyToTicketSchema>,
    _ctx: McpContext,
    @CurrentAgent() agent: Agent,
  ) {
    return this.tickets.reply(agent.team, ticketId, agent.username, message, status);
  }

  @ResourceTemplate({
    uriTemplate: 'tickets://{ticketId}',
    name: 'ticket',
    description: 'A ticket with its whole thread: the description, then every reply, oldest first',
    mimeType: 'application/json',
  })
  ticket({ ticketId }: { ticketId: string }, _ctx: McpContext, @CurrentAgent() agent: Agent) {
    return this.tickets.findOne(agent.team, parseTicketId(ticketId));
  }

  @Prompt({
    name: 'draft-reply',
    description: 'Draft a reply to a ticket, for you to review before it is sent',
    argsSchema: z.object({
      ticketId: z.string().regex(/^\d+$/).describe('The ticket number, such as 1042'),
      tone: z.enum(['formal', 'friendly']).default('friendly').describe('How the reply sounds'),
    }),
  })
  async draftReply(
    { ticketId, tone }: { ticketId: string; tone: 'formal' | 'friendly' },
    _ctx: McpContext,
    @CurrentAgent() agent: Agent,
  ): Promise<PromptMessage[]> {
    const ticket = await this.tickets.findOne(agent.team, parseTicketId(ticketId));
    return [
      {
        role: 'user',
        content: {
          type: 'resource',
          resource: { uri: `tickets://${ticket.id}`, mimeType: 'application/json', text: JSON.stringify(ticket) },
        },
      },
      {
        role: 'user',
        content: {
          type: 'text',
          text: `Draft a ${tone} reply to the customer of ticket ${ticket.id}. Answer what they asked last, and say what happens next. Show me the draft; send it with reply-to-ticket only once I approve it.`,
        },
      },
    ];
  }
}

/** URI 的变量可以是任意字符串:可能是一个工单编号,也可能查不到。 */
function parseTicketId(value: string): number {
  const id = Number(value);
  if (!/^\d+$/.test(value) || !Number.isSafeInteger(id) || id > 2_147_483_647) {
    throw new NotFoundException(`Ticket ${value} not found`);
  }
  return id;
}
  • 搜索工具上的 readOnlyHint: true 告诉客户端它不会改变任何东西,因此可以在不询问用户的情况下运行。没有它时(如 reply-to-ticket),客户端可能先询问;该工具的描述也会告诉模型只发送已批准的文本。
  • 回复工具上的 scopes: ['tickets:write']。 缺少该作用域的令牌会在方法运行之前得到 403,其质询中会指明所需作用域,客户端据此可以向用户申请(逐步提升授权)。
  • 方法拿到的是已校验的输入:text 已去除首尾空白,limit 已填入默认值。schema 拒绝的参数根本不会到达方法;模型会收到说明问题所在的错误,并可重试。
  • ticketId 采用数据库的范围。 没有那个 max(),更大的数字会在 PostgreSQL 中失败,模型拿到的就是 Internal server error,而不是一条它可以据以行动的消息。
  • 代理是第三个参数。 MCP 方法的前两个参数是输入和调用的上下文(参见 调用上下文)。

工具抛出的内容会变成一个带 isError: true 的结果:NotFoundException 会发送它的消息,如 Ticket 1003 not found;其他任何错误则发送 Internal server error(参见 错误)。

把工单作为资源提供

资源是客户端按 URI 读取的数据,通常由用户附加到对话中。上面的 ticket 方法把每个对话线程以 tickets://1001 这样的 URI 提供,该 URI 来自一个 RFC 6570 模板,其变量以字符串形式传入。不是工单编号的值,或属于其它团队的工单,都会得到 NotFoundException,即规范中的“资源未找到”错误。

提示词是用户在客户端中选择的模板,例如斜杠命令。draft-reply 先把工单作为内嵌资源附加进去,然后给出指令。MCP 中提示词的参数都是字符串,所以 ticketId 需要那个正则。

模块像注册普通提供者一样注册这个类:

src/tickets/tickets.module.ts
import { Module } from '@nestjs/common';
import { TicketsService } from './tickets.service.js';
import { TicketsTools } from './tickets.tools.js';

@Module({
  providers: [TicketsService, TicketsTools],
})
export class TicketsModule {}

校验 OAuth 访问令牌

在 MCP 中,网络上的服务器是一个 OAuth 2.1 资源服务器:客户端从你的身份提供者获取访问令牌,并在每个请求中携带它。服务器只负责校验,从不签发令牌(参见 授权)。校验器是一个带 verifyAccessToken(token) 方法的类。@nestjs/authentication 的 JwtVerifier 会用提供者的密钥校验签名,并校验签发者、受众、类型和过期时间。所有与具体提供者相关的内容都是配置:

src/auth/access-token.verifier.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtVerifier, type JwtClaims } from '@nestjs/authentication';
import type { McpTokenVerifier } from '@nestjs/mcp';
import type { AuthInfo } from '@modelcontextprotocol/server';
import type { Env } from '../config.js';

/** 校验身份提供者的 JWT 访问令牌,并从中读出工具所需的内容。 */
@Injectable()
export class AccessTokenVerifier implements McpTokenVerifier {
  private readonly jwt: JwtVerifier;
  private readonly resource: URL;
  private readonly teamClaim: string;

  constructor(config: ConfigService<Env, true>) {
    this.resource = new URL(config.get('MCP_RESOURCE', { infer: true }));
    this.teamClaim = config.get('OIDC_TEAM_CLAIM', { infer: true });
    this.jwt = new JwtVerifier({
      jwks: config.get('OIDC_JWKS_URL', { infer: true }),
      issuer: config.get('OIDC_ISSUER', { infer: true }),
      // 只接受为本服务器签发的令牌:不是用户浏览器为另一个 API 取得的令牌。
      audience: config.get('OIDC_AUDIENCE', { infer: true }) ?? config.get('MCP_RESOURCE', { infer: true }),
      // 访问令牌,而不是 ID 令牌或提供者签发的其它 JWT。
      type: config.get('OIDC_TOKEN_TYPE', { infer: true }) || undefined,
      required: ['exp', 'sub'],
      // 提供者的时钟与本服务器的时钟永远不会完全一致。
      clockTolerance: '30s',
    });
  }

  async verifyAccessToken(token: string): Promise<AuthInfo> {
    // 签名不对、签发者或受众不符、或令牌已过期,都会抛出 JwtError:即 401。
    const claims = await this.jwt.verify(token);
    const team = claims[this.teamClaim];
    return {
      token,
      // 令牌签发给的 OAuth 客户端:助手,而不是代理。
      clientId: String(claims.azp ?? claims.client_id ?? claims.sub),
      scopes: scopesOf(claims),
      expiresAt: claims.exp,
      resource: this.resource,
      extra: {
        subject: claims.sub,
        username: typeof claims.preferred_username === 'string' ? claims.preferred_username : claims.sub,
        team: typeof team === 'string' ? team : undefined,
      },
    };
  }
}

/** `scope` 是以空格分隔的字符串(RFC 9068);有些提供者发送 `scp`,可能是字符串也可能是列表。 */
function scopesOf(claims: JwtClaims): string[] {
  const value = claims.scope ?? claims.scp;
  const scopes = Array.isArray(value) ? value : typeof value === 'string' ? value.split(' ') : [];
  return scopes.filter((scope): scope is string => typeof scope === 'string' && scope.length > 0);
}
  • 受众是服务器的 URL。 提供者用同一套密钥为所有 API 签发令牌:若不做这项检查,用户为另一个 API 获取的令牌在本服务器上也能用,因此 JwtVerifier 拒绝没有 audience 的密钥集。MCP 客户端为 MCP_RESOURCE 申请令牌;OIDC_AUDIENCE 用于把其他值放进 aud 的提供者。
  • type 默认为 at+jwt,即 RFC 9068 访问令牌的头部值,它可以挡掉提供者签发的其它 JWT,例如 ID 令牌。若提供者不发送该字段,把 OIDC_TOKEN_TYPE 留空。
  • 被拒绝的令牌会抛出 JwtError(status: 401),模块以 401 和 WWW-Authenticate 质询应答。无法获取密钥时抛出的是普通错误,即 500,这样客户端不会在提供者故障期间丢弃有效令牌。
  • clientId 是助手,即令牌签发给的 OAuth 客户端;sub 是代理。模块还会检查 resource 是服务器的 URL,且 expiresAt 在未来。

由一个模块提供校验器,这样 McpModule 才能注入它:

src/auth/auth.module.ts
import { Module } from '@nestjs/common';
import { AccessTokenVerifier } from './access-token.verifier.js';

@Module({
  providers: [AccessTokenVerifier],
  exports: [AccessTokenVerifier],
})
export class AuthModule {}

组装服务器

根模块加载配置、打开数据库连接池,并用配置中的值注册 McpModule。forRootAsync() 接收校验器实例,由其工厂注入:

src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { DrizzleModule } from '@nestjs/drizzle';
import { McpModule } from '@nestjs/mcp';
import { createObserveModule } from '@nestjs/observe';
import { drizzle } from 'drizzle-orm/node-postgres';
import { fileURLToPath } from 'node:url';
import { AccessTokenVerifier } from './auth/access-token.verifier.js';
import { AuthModule } from './auth/auth.module.js';
import { envSchema, type Env } from './config.js';
import { TicketsModule } from './tickets/tickets.module.js';

export const { ObserveModule, ObserveInstrument } = createObserveModule();

@Module({
  imports: [
    // 放在最先,这样它最后关闭,仍能发送其它模块产生的数据。
    ObserveModule.forRoot({
      // 在 `npx @nestjs/observe link` 把密钥对写入 .env 之前为空:此时 SDK 不发送任何数据。
      appKey: process.env.OBSERVE_APP_KEY ?? '',
      appSecret: process.env.OBSERVE_APP_SECRET ?? '',
      serviceId: 'helpdesk-mcp',
    }),
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: envSchema,
      // 项目的 .env,无论本地客户端在哪个目录启动 stdio 服务器。
      envFilePath: fileURLToPath(new URL('../.env', import.meta.url)),
    }),
    DrizzleModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService<Env, true>) => ({
        drizzle,
        connection: config.get('DATABASE_URL', { infer: true }),
      }),
    }),
    McpModule.forRootAsync({
      imports: [AuthModule],
      inject: [ConfigService, AccessTokenVerifier],
      useFactory: (config: ConfigService<Env, true>, verifier: AccessTokenVerifier) => ({
        name: 'helpdesk',
        version: '1.0.0',
        instructions:
          "The support team's helpdesk. Find tickets with search-tickets, read one with its thread as tickets://{ticketId}, and reply with reply-to-ticket only after the user approved the text.",
        include: [TicketsModule],
        http: { allowedHosts: config.get('MCP_ALLOWED_HOSTS', { infer: true }) },
        auth: {
          verifier,
          resource: config.get('MCP_RESOURCE', { infer: true }),
          authorizationServers: [config.get('OIDC_ISSUER', { infer: true })],
          scopesSupported: ['tickets:read', 'tickets:write'],
          // 每个请求,从第一个开始,都需要读取作用域。
          requiredScopes: ['tickets:read'],
          resourceName: 'Helpdesk',
        },
      }),
    }),
    TicketsModule,
  ],
})
export class AppModule {}
  • auth 让每个请求都需要有效令牌:resource 是服务器的规范 URL,authorizationServers 是它信任的签发者,scopesSupported 是它对外声明的作用域,requiredScopes 则把 tickets:read 加到每个请求上,并列出所包含的工具。
  • 受保护资源元数据(RFC 9728)告诉客户端该去哪里登录,由模块在 /.well-known/oauth-protected-resource/mcp 提供。
  • allowedHosts 对其它 Host 头返回 403。没有它,一个域名解析到 127.0.0.1 的网页就能访问 localhost 上的服务器(DNS 重绑定)。Origin 检查默认开启:除 localhost 之外任何站点的页面都会得到 403,而助手和 CLI 不发送 Origin,因此可以通过(参见 HTTP 端点)。
  • envFilePath 从编译后的文件出发定位项目的 .env,无论桌面客户端在哪个目录启动 stdio 服务器。
  • ObserveModule 在 imports 中排在首位,与 SDK 的快速开始 一致:模块按相反顺序关闭,因此它最后停止,并把其它模块记录的内容发送出去(参见 关闭)。createObserveModule() 返回它和 ObserveInstrument,后者由 main.ts 和 stdio.ts 传给 Nest。
  • 在链接项目之前,密钥对是空的。 没有密钥对时,SDK 什么也不发送,并在启动时说明这一点。npx @nestjs/observe link 把 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET 写入 .env,并在 start 脚本中加入 --env-file .env,使它们在导入 AppModule(也就是 SDK 读取它们的时刻)之前就进入环境(参见 从终端链接)。空值,以及 nest new 写入的 'YOUR_APP_KEY' 占位符,都会回退到环境变量(参见 从环境变量读取密钥对);在生产环境之外设 enabled: false 也会让你特意链接过的开发机保持静默。

main.ts 在 Node 适配器上启动 HTTP 应用。使用适配器时,应用选项(其中包含 instrument)是第三个参数:

src/main.ts
import { ConsoleLogger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { AppModule, ObserveInstrument } from './app.module.js';
import type { Env } from './config.js';

const production = process.env.NODE_ENV === 'production';
const app = await NestFactory.create<NestNodeApplication>(AppModule, new NodeAdapter(), {
  instrument: ObserveInstrument,
  // 生产环境每行一个 JSON 对象;开发环境用可读文本。
  logger: new ConsoleLogger({ json: production, redact: ['authorization', 'token'] }),
});
app.useSecurityHeaders();
app.enableShutdownHooks();

const config = app.get<ConfigService<Env, true>>(ConfigService);
await app.listen(config.get('PORT', { infer: true }));
  • 生产环境输出 JSON 日志(参见 JSON 日志),从被记录的对象中隐去令牌,并在每个响应上添加 安全响应头。
  • 不启用 CORS。 助手不会从浏览器发起调用。若要让另一个来源上基于浏览器的客户端访问,需要把它的主机名加入 allowedOrigins 和你的 CORS 配置(参见 HTTP 端点)。

端点是 http://localhost:3000/mcp,每个请求都需要令牌。在项目被链接之前,服务器会在日志中说明 Observe 不发送任何内容:

$ npm run start
...
WARN [ObserveAgentWorker] Observe is installed but sends nothing: appKey and appSecret are not set, and the hosted collector accepts no telemetry without a key and a secret. If they come from the environment, check that OBSERVE_APP_KEY and OBSERVE_APP_SECRET reach this process, then restart it. To get a pair, run npx @nestjs/observe link or create one at https://observe.nestjs.com.
LOG [NestApplication] Nest application successfully started

获取开发用令牌

身份提供者负责让用户登录,并向助手签发令牌。开发时用一个脚本来代替它:它持有密钥对,把公钥以 JSON Web Key Set(JWKS)形式在 OIDC_JWKS_URL 提供,并为任意代理、团队和作用域签发访问令牌。测试也用它:

scripts/dev-issuer.ts
/**
 * 身份提供者的替代品,仅用于开发和测试:它有自己的密钥对,公钥以 JWKS 形式提供,
 * 并用它为您要求的任意团队和作用域签发访问令牌。绝不要部署它:任何能访问它的人都能铸造令牌。
 */
import { generateKeyPairSync } from 'node:crypto';
import { createServer, type Server } from 'node:http';
import { fileURLToPath } from 'node:url';
import { JwtSigner, type Duration } from '@nestjs/authentication';

export type DevTokenClaims = { username?: string; team?: string; scope?: string };
export type DevTokenOptions = { issuer?: string; audience?: string; ttl?: Duration; type?: string; now?: () => number };

const KID = 'dev-key';

export class DevIssuer {
  private readonly keys = generateKeyPairSync('rsa', { modulusLength: 2048 });
  readonly issuer: string;
  readonly audience: string;

  constructor(issuer: string, audience: string) {
    this.issuer = issuer;
    this.audience = audience;
  }

  /** 一个 RFC 9068 访问令牌,如同授权服务器为 MCP 服务器签发的那样。 */
  sign(
    { username = 'ada', team = 'billing', scope = 'tickets:read tickets:write' }: DevTokenClaims = {},
    { issuer = this.issuer, audience = this.audience, ttl = '1h', type = 'at+jwt', now = Date.now }: DevTokenOptions = {},
  ): string {
    const signer = new JwtSigner({ key: this.keys.privateKey, kid: KID, issuer, audience, ttl, type, now });
    return signer.sign({ sub: username, preferred_username: username, client_id: 'dev-issuer', scope, team });
  }

  jwks() {
    const jwk = this.keys.publicKey.export({ format: 'jwk' });
    return { keys: [{ ...jwk, kid: KID, alg: 'RS256', use: 'sig' }] };
  }

  /** 提供 JWKS,以及接受 `username`、`team` 和 `scope` 表单的 `POST /token`。 */
  listen(port: number): Promise<Server> {
    const server = createServer(async (req, res) => {
      res.setHeader('content-type', 'application/json');
      if (req.method === 'GET' && req.url === '/jwks.json') {
        res.end(JSON.stringify(this.jwks()));
      } else if (req.method === 'POST' && req.url === '/token') {
        let body = '';
        for await (const chunk of req) body += chunk;
        const form = Object.fromEntries(new URLSearchParams(body));
        const accessToken = this.sign(form);
        res.end(JSON.stringify({ access_token: accessToken, token_type: 'Bearer', expires_in: 3600 }));
      } else {
        res.statusCode = 404;
        res.end('{"error":"not_found"}');
      }
    });
    // 仅回环地址:本机之外无法向它申请令牌。
    return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve(server)));
  }
}

// `npm run dev:issuer`:在 OIDC_JWKS_URL 的端口上提供服务,签发者和受众取自 .env。
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  if (process.env.NODE_ENV === 'production') {
    throw new Error('The dev issuer mints tokens for anyone who asks: never run it in production');
  }
  const { OIDC_ISSUER, OIDC_JWKS_URL, MCP_RESOURCE } = process.env;
  if (!OIDC_ISSUER || !OIDC_JWKS_URL || !MCP_RESOURCE) {
    throw new Error('Set OIDC_ISSUER, OIDC_JWKS_URL and MCP_RESOURCE in .env');
  }
  const port = Number(new URL(OIDC_JWKS_URL).port);
  await new DevIssuer(OIDC_ISSUER, MCP_RESOURCE).listen(port);
  console.log(`Dev issuer ${OIDC_ISSUER}: keys at ${OIDC_JWKS_URL}, tokens from POST http://localhost:${port}/token`);
}
警告

开发用签发器会给任何请求者发放令牌。绝不要部署它:它在 NODE_ENV=production 时拒绝启动,只监听回环接口,并且位于构建过程不会编译的 scripts/ 目录。它也不是授权服务器:它没有登录页,因此那些通过 OAuth 让用户登录的客户端无法使用它(参见 连接助手)。

它签发的令牌以 OIDC_ISSUER 为 iss、MCP_RESOURCE 为 aud、at+jwt 为 typ,一小时后过期;重启会生成新密钥,并使旧令牌失效。在单独的终端中启动它:

$ npm run dev:issuer
Dev issuer http://localhost:3001: keys at http://localhost:3001/jwks.json, tokens from POST http://localhost:3001/token

试一试

在另一个终端中用 npm run start 启动服务器。没有令牌的请求会得到 401,并带有 WWW-Authenticate 质询,其中指明每个请求所需的作用域,并指向元数据(此处及下文省略了部分响应头):

$ curl -i localhost:3000/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
HTTP/1.1 401 Unauthorized
content-type: application/json
www-authenticate: Bearer error="invalid_token", error_description="Missing Authorization header", scope="tickets:read", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
...

{"error":"invalid_token","error_description":"Missing Authorization header"}

元数据说明了服务器本身、它接受哪些签发者签发的令牌,以及它的作用域。访问它无需令牌:

$ curl -i localhost:3000/.well-known/oauth-protected-resource/mcp
HTTP/1.1 200 OK
...
Access-Control-Allow-Origin: *
Cache-Control: public, max-age=3600
Content-Type: application/json; charset=utf-8
...

{"resource":"http://localhost:3000/mcp","authorization_servers":["http://localhost:3001"],"bearer_methods_supported":["header"],"scopes_supported":["tickets:read","tickets:write"],"resource_name":"Helpdesk"}

向开发用签发器申请一个属于账单团队 Ada 的令牌,带两个作用域,并用 jq 存入变量:

$ curl localhost:3001/token -d username=ada -d team=billing -d 'scope=tickets:read tickets:write'
{"access_token":"eyJhbGciOiJSUzI1NiIsInR5...","token_type":"Bearer","expires_in":3600}
$ TOKEN=$(curl -s localhost:3001/token -d username=ada -d team=billing -d 'scope=tickets:read tickets:write' | jq -r .access_token)

带着它发起 tools/call 会搜索账单团队的工单。该端点不保存会话,因此不需要先 initialize;它用服务器发送事件(server-sent event)应答,因为客户端已声明接受该格式:

$ curl -i localhost:3000/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -H "Authorization: Bearer $TOKEN" -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"search-tickets","arguments":{"text":"refund"}}}'
HTTP/1.1 200 OK
content-type: text/event-stream
...

event: message
data: {"result":{"content":[{"type":"text","text":"[{\"id\":1002,\"subject\":\"Refund for a cancelled subscription\",\"status\":\"pending\",\"customerEmail\":\"li@example.com\",\"updatedAt\":\"2026-11-25T09:20:49.738Z\"},{\"id\":1001,\"subject\":\"Charged twice for order 5521\",\"status\":\"open\",\"customerEmail\":\"maria@example.com\",\"updatedAt\":\"2026-11-25T09:20:49.738Z\"}]"}]},"jsonrpc":"2.0","id":1}

MCP Inspector 的命令行是一个真正的 MCP 客户端,可以把令牌作为请求头传入。--method tools/list 会列出工具及其 schema,正如助手所看到的那样。以资源方式读取工单,然后回复并把它标记为已解决;回复的结果就是它的 structuredContent,与 JSON 文本内容相同:

$ npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp --header "Authorization: Bearer $TOKEN" --method resources/read --uri tickets://1002
{
  "contents": [
    {
      "uri": "tickets://1002",
      "mimeType": "application/json",
      "text": "{\"id\":1002,\"teamId\":\"billing\",\"subject\":\"Refund for a cancelled subscription\",\"body\":\"I cancelled on the 3rd but was charged on the 5th. I would like that refunded.\",\"customerEmail\":\"li@example.com\",\"status\":\"pending\",\"createdAt\":\"2026-11-25T09:20:49.738Z\",\"updatedAt\":\"2026-11-25T09:20:49.738Z\",\"replies\":[{\"id\":1,\"ticketId\":1002,\"author\":\"grace\",\"body\":\"Sorry about that. Which card was charged, and on which date exactly?\",\"createdAt\":\"2026-11-25T09:20:49.738Z\"}]}"
    }
  ]
}
$ npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp --header "Authorization: Bearer $TOKEN" --method tools/call --tool-name reply-to-ticket --tool-arg ticketId=1002 'message=We have refunded the charge of the 5th. It reaches your card in 3 to 5 days.' status=solved
{
  "content": [
    {
      "type": "text",
      "text": "{\"ticketId\":1002,\"replyId\":2,\"status\":\"solved\"}"
    }
  ],
  "structuredContent": {
    "ticketId": 1002,
    "replyId": 2,
    "status": "solved"
  }
}

Bob 属于配送团队。账单团队的工单对他并不存在:

$ BOB=$(curl -s localhost:3001/token -d username=bob -d team=shipping | jq -r .access_token)
$ npx @modelcontextprotocol/inspector --cli http://localhost:3000/mcp --header "Authorization: Bearer $BOB" --method resources/read --uri tickets://1002
{"error":{"code":"error","message":"Resource not found: tickets://1002"}}

只有 tickets:read 的令牌可以搜索,但不能回复。403 的质询中指明了应向用户申请的作用域:

$ READER=$(curl -s localhost:3001/token -d username=ada -d team=billing -d scope=tickets:read | jq -r .access_token)
$ curl -i localhost:3000/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -H "Authorization: Bearer $READER" -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"reply-to-ticket","arguments":{"ticketId":1001,"message":"Hello"}}}'
HTTP/1.1 403 Forbidden
content-type: application/json
www-authenticate: Bearer error="insufficient_scope", error_description="Insufficient scope", scope="tickets:write", resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"
...

{"error":"insufficient_scope","error_description":"Insufficient scope"}

来自其他站点网页的请求,以及 Host 不在服务器应答范围内的请求,会在读取任何其它内容之前得到 403:

$ curl -i localhost:3000/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -H "Authorization: Bearer $TOKEN" -H 'Origin: https://elsewhere.example' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
HTTP/1.1 403 Forbidden
...

{"jsonrpc":"2.0","error":{"code":-32000,"message":"Invalid Origin: elsewhere.example"},"id":null}
$ curl -i localhost:3000/mcp -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -H "Authorization: Bearer $TOKEN" -H 'Host: attacker.example:3000' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
HTTP/1.1 403 Forbidden
...

{"jsonrpc":"2.0","error":{"code":-32000,"message":"Invalid Host: attacker.example"},"id":null}

通过 stdio 提供相同的工具

用户机器上的助手(Claude Desktop、Claude Code、IDE)也可以把服务器作为本地进程启动,并通过 stdin 和 stdout 与它通信。stdio.ts 从独立的应用上下文中提供同一个模块:

src/stdio.ts
import { NestFactory } from '@nestjs/core';
import { McpStdioLogger, McpStdioServer } from '@nestjs/mcp';
import { AppModule, ObserveInstrument } from './app.module.js';

// stdout 承载协议:每一行日志都写到 stderr。
const app = await NestFactory.createApplicationContext(AppModule, {
  instrument: ObserveInstrument,
  logger: new McpStdioLogger(),
});
await app.get(McpStdioServer).listen();
await app.close();

McpStdioLogger 把每个日志级别都写到 stderr:stdout 承载协议,而 Nest 的默认日志器会写到那里。Observe 的 SDK 通过 Nest 的日志器记录,因此它的日志也进入 stderr。客户端关闭 stdin 时,listen() 返回(参见 通过 stdio)。

通过 stdio 时,进程属于单个用户,规范要求从环境变量而非 OAuth 取得凭据。由于没有令牌,scopes 不会被检查,团队来自 HELPDESK_TEAM。.env 中的数据库 URL 才是那里真正的访问控制:拿到它的人本来也就拿到了数据。

客户端接受的是一条命令,并在它选择的目录中运行:node 加构建产物的绝对路径。不要用 npm run,它会把自己的输出打到 stdout,而那正是协议的通道。桌面客户端在类似下面的配置中写入这条命令:

{
  "mcpServers": {
    "helpdesk": {
      "command": "node",
      "args": ["/path/to/helpdesk-mcp/dist/stdio.js"],
      "env": { "HELPDESK_TEAM": "billing" }
    }
  }
}

其余配置来自项目的 .env,但 Observe 的密钥对除外——SDK 会在 ConfigModule 加载该文件之前从环境变量读取它:要上报 stdio 调用,就把 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET 加入客户端的 env。测试用这条命令和这套环境启动服务器,Inspector 的命令行也是如此,这里是配送团队的例子(服务器在 stderr 上的日志已省略):

$ npx @modelcontextprotocol/inspector --cli -e HELPDESK_TEAM=shipping node dist/stdio.js --method tools/call --tool-name search-tickets
{
  "content": [
    {
      "type": "text",
      "text": "[{\"id\":1004,\"subject\":\"Wrong size delivered\",\"status\":\"open\",\"customerEmail\":\"noor@example.com\",\"updatedAt\":\"2026-11-25T09:20:49.738Z\"},{\"id\":1003,\"subject\":\"Parcel stuck in customs\",\"status\":\"open\",\"customerEmail\":\"sam@example.com\",\"updatedAt\":\"2026-11-25T09:20:49.738Z\"}]"
    }
  ]
}

连接助手

大多数 MCP 客户端可以自己让用户登录:收到 401 时,它们读取元数据、找到身份提供者、向其注册或使用你配置的客户端 ID,并打开它的登录页。这需要一个真正的授权服务器,而开发用签发器并不是:用它时,请把令牌作为 Authorization 请求头交给客户端,或者运行 stdio 命令。

警告

本节内容均未在本教程中实际运行过,本教程是用 SDK 的客户端和 MCP Inspector 的命令行测试的。本节内容依据撰写时各客户端的文档。

客户端 带请求头的远程服务器 stdio 命令 用 OAuth 登录
Claude Code claude mcp add --transport http ... --header claude mcp add --env ... -- node ... 是,使用 /mcp
Claude Desktop 自定义连接器,经由 Anthropic 的云端访问:只支持公开 URL claude_desktop_config.json 中的 mcpServers 是,通过自定义连接器
Cursor .cursor/mcp.json 中的 mcpServers:url、headers 同一个文件:command、args、env 是
VS Code (Copilot) .vscode/mcp.json 中的 servers:"type": "http"、url、headers 同一个文件:"type": "stdio" 是
Windsurf mcp_config.json 中的 mcpServers:serverUrl、headers 同一个文件 是
Cline cline_mcp_settings.json 中的 mcpServers:"type": "streamableHttp"、url、headers 同一个文件 未记录
Zed 其设置中的 context_servers:url、headers 同一个键:command、args、env 是,无需请求头
Gemini CLI gemini mcp add --transport http --header,或 settings.json 中的 httpUrl 和 headers gemini mcp add -e ... 是
Codex CLI config.toml 中的 [mcp_servers.helpdesk]:url、bearer_token_env_var codex mcp add --env ... -- node ... 是,使用 codex mcp login
ChatGPT 否:它不发送自定义请求头,且需要公开 URL 否 是,仅支持 OAuth

Claude Code、Gemini CLI 和 Codex CLI 通过命令行添加服务器。Claude Code 和 Gemini CLI 直接接收请求头;Codex 则从你指定的环境变量中读取令牌:

$ claude mcp add --transport http helpdesk http://localhost:3000/mcp --header "Authorization: Bearer $TOKEN"
$ claude mcp add --env HELPDESK_TEAM=billing --transport stdio helpdesk-local -- node /path/to/helpdesk-mcp/dist/stdio.js
$ gemini mcp add --transport http --header "Authorization: Bearer $TOKEN" helpdesk http://localhost:3000/mcp
$ codex mcp add helpdesk-local --env HELPDESK_TEAM=billing -- node /path/to/helpdesk-mcp/dist/stdio.js

大多数编辑器采用 上一节 中 mcpServers 的结构,远程服务器再加 url 和 headers。在 Cursor 的 .cursor/mcp.json 中,请求头可以从你的环境变量读取令牌,而不必写在文件里:

{
  "mcpServers": {
    "helpdesk": {
      "url": "http://localhost:3000/mcp",
      "headers": { "Authorization": "Bearer ${env:HELPDESK_TOKEN}" }
    }
  }
}

其它客户端会重命名键,正如表格所示:Windsurf 用 serverUrl,Gemini 用 httpUrl(它的 url 表示较旧的 SSE 传输),Cline 需要 "type": "streamableHttp",否则会退回 SSE。VS Code 的 .vscode/mcp.json 列出 servers,并且可以提示一次令牌,然后存入它的密钥存储:

{
  "inputs": [{ "type": "promptString", "id": "helpdesk-token", "password": true }],
  "servers": {
    "helpdesk": {
      "type": "http",
      "url": "http://localhost:3000/mcp",
      "headers": { "Authorization": "Bearer ${input:helpdesk-token}" }
    }
  }
}

Codex CLI 在 ~/.codex/config.toml 中配置远程服务器,并指定存放令牌的变量名:

[mcp_servers.helpdesk]
url = "http://localhost:3000/mcp"
bearer_token_env_var = "HELPDESK_TOKEN"

使用真实的身份提供者时,去掉请求头,让客户端自行登录。开发用令牌一小时后过期:向签发器申请新令牌,并更新请求头或变量。

使用真实的身份提供者

生产环境中,把配置指向你的身份提供者。OIDC_JWKS_URL 是其 /.well-known/openid-configuration 文档中的 jwks_uri,OIDC_ISSUER 是其访问令牌中 iss 的精确值。在提供者中创建一个 API,标识符为 MCP_RESOURCE,作用域包含 tickets:read 和 tickets:write,并添加一个表示团队的声明(由 OIDC_TEAM_CLAIM 指明其名称)。根据各提供者的文档,主要差异如下:

提供者 签发者 aud typ 作用域 团队
Auth0 https://<tenant>.auth0.com/,带末尾斜杠 API 的标识符 at+jwt,需启用 API 的 RFC 9068 令牌配置 scope 由 Action 设置的自定义声明
Microsoft Entra ID https://login.microsoftonline.com/<tenant-id>/v2.0 API 的客户端 ID:设置 OIDC_AUDIENCE JWT:把 OIDC_TOKEN_TYPE 设为空 scp 需要声明映射
Okta https://<domain>/oauth2/<server-id> 授权服务器的受众 无:把 OIDC_TOKEN_TYPE 设为空 scp,一个列表 授权服务器上的自定义声明
WorkOS AuthKit https://<authkit-domain> 资源指示符(resource indicator) 检查一个令牌 scope JWT 模板
警告

这些表格行未在本教程中运行过;它们概括了撰写时各提供者的文档。部署之前,请解码一个来自你的提供者的访问令牌(其头部和载荷是 base64url 编码的 JSON),并与配置对照。助手能否自行登录也取决于提供者:它必须允许助手注册(通过动态客户端注册或 Client ID Metadata Documents),或者由你逐个注册。

测试它

测试用开发用签发器代替身份提供者:为本次运行生成一对密钥,作为 OIDC_JWKS_URL 指明的 JWKS 提供,并用它签发令牌。应用对它们运行真正的校验器;JwksClient 只在回环地址上接受纯 http。数据存放在 PostgreSQL 中,因为团队限定涉及的是 SQL 语句。测试配置为应用提供了它在启动时要校验的环境变量:

vitest.config.e2e.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    root: './',
    include: ['test/**/*.e2e-spec.ts'],
    // 这些文件共用一个数据库,且每个文件都会先清空它。
    fileParallelism: false,
    env: {
      DATABASE_URL: 'postgres://unused-in-tests',
      MCP_RESOURCE: 'http://localhost:3000/mcp',
      OIDC_ISSUER: 'https://idp.test',
      // test/helpdesk.e2e-spec.ts 提供的密钥集,来自开发用签发器。
      OIDC_JWKS_URL: 'http://127.0.0.1:3162/jwks.json',
    },
  },
});

一个辅助函数会迁移测试数据库、清空它,并为每个团队添加一张工单:

test/fixtures.ts
import { fileURLToPath } from 'node:url';
import { sql } from 'drizzle-orm';
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import type { Pool } from 'pg';
import { teams, tickets } from '../src/database/schema.js';

/** 迁移测试数据库,清空它,并为两个团队各添加一张工单。 */
export async function resetDatabase(pool: Pool) {
  const db = drizzle({ client: pool });
  await migrate(db, { migrationsFolder: fileURLToPath(new URL('../drizzle', import.meta.url)) });
  await db.execute(sql`TRUNCATE replies, tickets, teams RESTART IDENTITY CASCADE`);
  await db.insert(teams).values([
    { id: 'billing', name: 'Billing' },
    { id: 'shipping', name: 'Shipping' },
  ]);
  const [billing, shipping] = await db
    .insert(tickets)
    .values([
      { teamId: 'billing', subject: 'Charged twice', body: 'Two charges for order 5521', customerEmail: 'maria@example.com' },
      { teamId: 'shipping', subject: 'Parcel stuck in customs', body: 'Order 5498', customerEmail: 'sam@example.com' },
    ])
    .returning({ id: tickets.id });
  return { db, billingTicket: billing.id, shippingTicket: shipping.id };
}

第一个文件用 @nestjs/mcp/testing 的 connectMcpClient() 在内存中连接 SDK 的客户端:令牌校验、schema、作用域和装饰器都会执行,但不需要套接字(参见 内存客户端)。401 以及 Origin 和 Host 检查则通过真实 HTTP 测试,使用 fetch() 和 SDK 的 Streamable HTTP 客户端:

test/helpdesk.e2e-spec.ts
import { request as httpRequest, type Server } from 'node:http';
import {
  Client,
  InsufficientScopeError,
  StreamableHTTPClientTransport,
} from '@modelcontextprotocol/client';
import { getDrizzleToken } from '@nestjs/drizzle';
import { connectMcpClient } from '@nestjs/mcp/testing';
import { NodeAdapter, type NestNodeApplication } from '@nestjs/platform-node';
import { Test } from '@nestjs/testing';
import { eq } from 'drizzle-orm';
import { Pool } from 'pg';
import { DevIssuer, type DevTokenClaims } from '../scripts/dev-issuer.js';
import { AppModule } from '../src/app.module.js';
import { replies, tickets } from '../src/database/schema.js';
import { resetDatabase } from './fixtures.js';

const url = process.env.TEST_DATABASE_URL;
const PORT = 3163;

// 代替身份提供者:它的密钥,作为 OIDC_JWKS_URL 指明的 JWKS 提供。
const issuer = new DevIssuer(process.env.OIDC_ISSUER!, process.env.MCP_RESOURCE!);

describe.skipIf(!url)('Helpdesk MCP server (e2e)', () => {
  const pool = new Pool({ connectionString: url });
  let fixtures: Awaited<ReturnType<typeof resetDatabase>>;
  let jwks: Server;
  let app: NestNodeApplication;

  beforeAll(async () => {
    jwks = await issuer.listen(Number(new URL(process.env.OIDC_JWKS_URL!).port));
    fixtures = await resetDatabase(pool);
    const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(getDrizzleToken())
      .useValue(fixtures.db)
      .compile();
    app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
    // 为通过 HTTP 的测试而监听;内存客户端不需要套接字。
    await app.listen(PORT, '127.0.0.1');
  });

  afterAll(async () => {
    await app.close(); // 同时也关闭连接池
    jwks.close();
  });

  /** 一个内存中的 MCP 客户端,以 `team` 团队代理的身份登录,作用域为 `scope`。 */
  async function as<T>(claims: DevTokenClaims, run: (client: Client) => Promise<T>): Promise<T> {
    const client = await connectMcpClient(app, { token: issuer.sign(claims) });
    try {
      return await run(client);
    } finally {
      await client.close();
    }
  }
  const billing = { username: 'ada', team: 'billing' };
  const textOf = (result: { content?: unknown }) => (result.content as { text: string }[])[0].text;

  it('lists the tools, with the search marked read-only', async () => {
    const { tools } = await as(billing, (client) => client.listTools());
    expect(tools.map((tool) => [tool.name, tool.annotations?.readOnlyHint])).toEqual([
      ['search-tickets', true],
      ['reply-to-ticket', undefined],
    ]);
  });

  it("finds only the agent's own team's tickets", async () => {
    const found = await as(billing, (client) => client.callTool({ name: 'search-tickets', arguments: {} }));
    expect(JSON.parse(textOf(found)).map((ticket: { id: number }) => ticket.id)).toEqual([fixtures.billingTicket]);
  });

  it("never reads or changes another team's ticket", async () => {
    const other = fixtures.shippingTicket;
    await as(billing, async (client) => {
      await expect(client.readResource({ uri: `tickets://${other}` })).rejects.toThrow(`Resource not found: tickets://${other}`);
      await expect(
        client.getPrompt({ name: 'draft-reply', arguments: { ticketId: String(other) } }),
      ).rejects.toThrow(`Ticket ${other} not found`);
      const reply = await client.callTool({
        name: 'reply-to-ticket',
        arguments: { ticketId: other, message: 'Hello from billing', status: 'solved' },
      });
      expect(reply).toMatchObject({ isError: true, content: [{ type: 'text', text: `Ticket ${other} not found` }] });
    });
    const [ticket] = await fixtures.db.select().from(tickets).where(eq(tickets.id, other));
    expect(ticket.status).toBe('open');
    expect(await fixtures.db.$count(replies, eq(replies.ticketId, other))).toBe(0);
  });

  it('replies, sets the status, and shows the reply in the ticket', async () => {
    const id = fixtures.billingTicket;
    await as(billing, async (client) => {
      const reply = await client.callTool({
        name: 'reply-to-ticket',
        arguments: { ticketId: id, message: 'Refunded the second charge.', status: 'solved' },
      });
      expect(reply.structuredContent).toEqual({ ticketId: id, replyId: expect.any(Number), status: 'solved' });

      const { contents } = await client.readResource({ uri: `tickets://${id}` });
      const ticket = JSON.parse((contents[0] as { text: string }).text);
      expect(ticket).toMatchObject({ id, status: 'solved', replies: [{ author: 'ada', body: 'Refunded the second charge.' }] });
    });
  });

  it('asks for tickets:write before a reply, and changes nothing without it', async () => {
    const id = fixtures.billingTicket;
    const before = await fixtures.db.$count(replies, eq(replies.ticketId, id));
    await as({ ...billing, scope: 'tickets:read' }, async (client) => {
      const search = await client.callTool({ name: 'search-tickets', arguments: { text: 'charged' } });
      expect(search.isError).toBeFalsy();
      const error = await client
        .callTool({ name: 'reply-to-ticket', arguments: { ticketId: id, message: 'Hi' } })
        .catch((e: unknown) => e);
      expect(error).toBeInstanceOf(InsufficientScopeError);
      expect(error).toMatchObject({ requiredScope: 'tickets:write' });
    });
    expect(await fixtures.db.$count(replies, eq(replies.ticketId, id))).toBe(before);
  });

  it('tells the model what is wrong with its arguments', async () => {
    await as(billing, async (client) => {
      for (const args of [{ ticketId: '1001', message: 'Hi' }, { ticketId: 2 ** 31, message: 'Hi' }, { ticketId: 1001, message: ' ' }]) {
        const result = await client.callTool({ name: 'reply-to-ticket', arguments: args });
        expect(result.isError).toBe(true);
        expect(textOf(result)).toMatch(/^Input validation error/);
      }
    });
  });

  describe('over HTTP', () => {
    const endpoint = `http://127.0.0.1:${PORT}/mcp`;
    const listTools = (headers: Record<string, string> = {}) =>
      fetch(endpoint, {
        method: 'POST',
        headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...headers },
        body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }),
      });

    it('challenges a request without a token, pointing at the metadata', async () => {
      const response = await listTools();
      expect(response.status).toBe(401);
      expect(response.headers.get('www-authenticate')).toContain(
        'resource_metadata="http://localhost:3000/.well-known/oauth-protected-resource/mcp"',
      );
      const metadata = await fetch(`http://127.0.0.1:${PORT}/.well-known/oauth-protected-resource/mcp`);
      expect(await metadata.json()).toMatchObject({
        resource: 'http://localhost:3000/mcp',
        authorization_servers: ['https://idp.test'],
        scopes_supported: ['tickets:read', 'tickets:write'],
      });
    });

    it('refuses tokens for another audience, expired, wrongly signed or of another type with 401', async () => {
      const impostor = new DevIssuer(issuer.issuer, issuer.audience); // 相同的 kid,另一把密钥
      const tokens = {
        'another audience': issuer.sign(billing, { audience: 'https://other-api.example/mcp' }),
        'another issuer': issuer.sign(billing, { issuer: 'https://evil.example' }),
        expired: issuer.sign(billing, { now: () => Date.now() - 2 * 60 * 60 * 1000 }),
        'wrongly signed': impostor.sign(billing),
        'an ID token': issuer.sign(billing, { type: 'JWT' }),
      };
      for (const [reason, token] of Object.entries(tokens)) {
        const response = await listTools({ authorization: `Bearer ${token}` });
        expect(response.status, reason).toBe(401);
        expect(response.headers.get('www-authenticate'), reason).toContain('error="invalid_token"');
      }
      expect((await listTools({ authorization: `Bearer ${issuer.sign(billing)}` })).status).toBe(200);
    });

    it('refuses a page from another site, and a Host it does not answer to', async () => {
      const token = issuer.sign(billing);
      expect((await listTools({ authorization: `Bearer ${token}`, origin: 'https://elsewhere.example' })).status).toBe(403);
      // fetch() 会自行设置 Host,所以这一项走 node:http。
      const status = await new Promise<number>((resolve, reject) => {
        const req = httpRequest(endpoint, {
          method: 'POST',
          headers: {
            host: 'attacker.example:3000',
            authorization: `Bearer ${token}`,
            'content-type': 'application/json',
            accept: 'application/json, text/event-stream',
          },
        });
        req.on('response', (res) => resolve(res.statusCode!)).on('error', reject);
        req.end(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }));
      });
      expect(status).toBe(403);
    });

    it('serves the SDK client with a bearer token', async () => {
      const client = new Client({ name: 'helpdesk-e2e', version: '1.0.0' });
      await client.connect(
        new StreamableHTTPClientTransport(new URL(endpoint), {
          requestInit: { headers: { authorization: `Bearer ${issuer.sign(billing)}` } },
        }),
      );
      try {
        const result = await client.callTool({ name: 'search-tickets', arguments: { text: 'charged' } });
        expect(JSON.parse(textOf(result))).toMatchObject([{ id: fixtures.billingTicket }]);
      } finally {
        await client.close();
      }
    });
  });
});

第二个文件像桌面客户端那样启动构建好的 stdio.js,然后再启动一次并直接读取原始 stdout:SDK 的客户端会跳过 stdout 中不是 JSON 的行,因此只有原始读取才能表明没有其它内容(Nest 或 Observe 的日志行)混入其中:

test/stdio.e2e-spec.ts
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { Pool } from 'pg';
import { resetDatabase } from './fixtures.js';

const url = process.env.TEST_DATABASE_URL;
const stdioJs = fileURLToPath(new URL('../dist/stdio.js', import.meta.url));

describe.skipIf(!url)('stdio entry point (e2e)', () => {
  it('serves the tools to a client that launches it, for the team in its environment', async () => {
    const pool = new Pool({ connectionString: url });
    const { billingTicket } = await resetDatabase(pool);
    await pool.end();

    // 桌面客户端运行的内容:node、构建好的 stdio.js,以及它配置中的环境变量。
    // 其余配置来自项目的 .env;DATABASE_URL 指向测试数据库。
    const client = new Client({ name: 'stdio-e2e', version: '1.0.0' });
    await client.connect(
      new StdioClientTransport({ command: 'node', args: [stdioJs], env: { HELPDESK_TEAM: 'billing', DATABASE_URL: url! } }),
    );
    try {
      const { tools } = await client.listTools();
      expect(tools.map((tool) => tool.name)).toEqual(['search-tickets', 'reply-to-ticket']);
      const found = await client.callTool({ name: 'search-tickets', arguments: {} });
      const ids = JSON.parse((found.content as { text: string }[])[0].text).map((ticket: { id: number }) => ticket.id);
      expect(ids).toEqual([billingTicket]);
    } finally {
      await client.close();
    }
  });

  it('writes nothing but protocol messages to stdout, from start to exit', async () => {
    // SDK 的客户端会跳过 stdout 中不是 JSON 的行;其它客户端不会。所以要原始读取 stdout。
    const server = spawn('node', [stdioJs], { env: { ...process.env, HELPDESK_TEAM: 'billing', DATABASE_URL: url } });
    let stdout = '';
    let stderr = '';
    server.stderr.on('data', (chunk) => (stderr += chunk));
    server.stdout.on('data', (chunk) => {
      stdout += chunk;
      // 答案已到:关闭 stdin,就像客户端退出时那样。
      if (stdout.includes('\n')) server.stdin.end();
    });
    const initialize = { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'raw', version: '1.0.0' } };
    server.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: initialize })}\n`);
    await new Promise((resolve) => server.on('exit', resolve));

    expect(stdout.trim().split('\n').map((line) => JSON.parse(line).id)).toEqual([1]);
    // 日志都进了 stderr,包括 Observe 关于缺少密钥对的警告。
    expect(stderr).toContain('Starting Nest application');
    expect(stderr).toContain('Observe is installed but sends nothing');
  });
});

先创建一次测试数据库,然后运行这两个文件。脚本会先构建,供 stdio 测试使用:

$ docker exec helpdesk-db psql -U postgres -c "CREATE DATABASE helpdesk_test"
$ TEST_DATABASE_URL=postgres://postgres:helpdesk@localhost:5432/helpdesk_test npm run test:e2e
...
 Test Files  2 passed (2)
      Tests  12 passed (12)

删掉代码后,每一项保证都会让它对应的测试失败:tickets:write 作用域,search()、findOne() 和 reply() 中各自的团队条件,ticketId 上的 max(),受众和 type 检查(把 audience 设为 false),allowedHosts,Origin 检查(把 allowedOrigins 设为 false),以及 McpStdioLogger(否则 Nest 的启动日志会落到 stdout)。过期和签名错误的令牌由 JwtVerifier 自身拒绝。

生产环境检查清单

  • 把配置指向你的身份提供者,MCP_RESOURCE 用服务器的公开 https URL。绝不要部署开发用签发器,或类似它的令牌端点。
  • 设置 MCP_ALLOWED_HOSTS,填入客户端访问服务器所用的主机名,例如 helpdesk.example.com。
  • 列出基于浏览器的客户端(如果有),加入 http.allowedOrigins 和 CORS 配置:默认情况下,只有 localhost 上的页面能通过。
  • 提高请求体解析器的上限,如果工具参数可能超过 Node 适配器默认的 100 KB:app.useBodyParser() 接受一个 limit。
  • 把 drizzle-kit migrate 作为发布步骤运行,绝不要运行种子脚本:它会清空表。
  • 让访问令牌保持短期有效。 服务器在令牌过期前一直接受它,不会再去询问提供者;被你停用的用户在过期前仍保有访问权限。
  • 让描述保持诚实。 模型只通过名称、描述和 schema 来了解工具,而 readOnlyHint 决定哪些调用可以不经询问用户就执行。
  • 为生产环境准备独立的 Observe 密钥对,从项目的 API Keys 页面获取,并以 OBSERVE_APP_KEY 和 OBSERVE_APP_SECRET 写入平台的环境变量:start:prod 不会加载 .env。这样每次 MCP 调用都会按其操作记录,如 tools/call search-tickets 或带模板的 resources/read,而不是 POST /mcp(参见 NestJS Observe);enableShutdownHooks() 则让 SDK 能在部署时的 SIGTERM 上发送最后一批数据。

下一步

  • 让策略决定每次调用,使用 @nestjs/authorization 的 @Can(),如 授权 所述。
  • 在工具调用中请用户确认回复,使用 inputRequired():参见 调用上下文。
  • 上报长耗时工具的进度,并在客户端取消时停止:调用上下文。
  • 给已有的 API 添加 MCP 服务器:MCP 概览 会为一个订单 API 构建一个。
  • 构建带登录和按记录权限的服务台 API 侧:用 JWT 认证构建 REST API 和 项目管理教程。