NestJS中文文档
MCP / 测试
已译 191/191

测试

工具、资源和提示词(prompt)都是提供者的方法,因此它们的逻辑按任何提供者的方式来测:直接调用方法。MCP 在其周围添加的东西——schema、守卫、作用域以及结果的形态——则通过一个真实的 MCP 客户端来测,@nestjs/mcp/testing 会在内存中把这个客户端连接到应用。

单元测试

单元测试带着方法所需的参数和上下文来调用它:

orders/orders.tools.spec.ts
import type { McpContext } from '@nestjs/mcp';
import { OrdersService } from './orders.service.js';
import { OrdersTools } from './orders.tools.js';

describe('OrdersTools', () => {
  it('changes the delivery address', async () => {
    const orders = {
      changeAddress: vi
        .fn()
        .mockResolvedValue({
          id: 'ord_123',
          address: '12 Whisker Lane, Leeds',
          status: 'pending',
        }),
    };
    const tools = new OrdersTools(orders as unknown as OrdersService);
    const ctx = { authInfo: { clientId: 'support-desk' } } as McpContext;

    const result = await tools.changeAddress(
      { orderId: 'ord_123', address: '12 Whisker Lane, Leeds' },
      ctx,
    );

    expect(result).toEqual({
      orderId: 'ord_123',
      address: '12 Whisker Lane, Leeds',
      status: 'pending',
    });
    expect(orders.changeAddress).toHaveBeenCalledWith(
      'ord_123',
      '12 Whisker Lane, Leeds',
      'support-desk',
    );
  });
});

直接调用会跳过模块添加的一切:参数不被校验,守卫和拦截器不运行,返回值也不会变成 MCP 结果。这些由客户端来测。

内存客户端

connectMcpClient() 把官方 MCP SDK 的客户端连接到应用,走的是与 HTTP 端点相同的处理器:令牌检查、schema,以及每个守卫、拦截器、管道和过滤器。它不启动 HTTP 服务器。该客户端来自 @modelcontextprotocol/client,是一个开发依赖:

$ npm i --save-dev @modelcontextprotocol/client

订单 API 需要令牌,因此测试会替换它的 verifier,换成一个认识几个测试令牌的实现:

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

const TOKENS: Record<
  string,
  { clientId: string; scopes: string[]; team?: string }
> = {
  'support-token': {
    clientId: 'support-desk',
    scopes: ['orders:read', 'orders:write'],
    team: 'support',
  },
  'warehouse-token': {
    clientId: 'warehouse',
    scopes: ['orders:read', 'orders:write'],
    team: 'warehouse',
  },
  'reader-token': { clientId: 'reporting', scopes: ['orders:read'] },
};

export class TestTokenVerifier implements McpTokenVerifier {
  async verifyAccessToken(token: string): Promise<AuthInfo | null> {
    const found = TOKENS[token];
    if (!found) {
      return null;
    }
    return {
      token,
      clientId: found.clientId,
      scopes: found.scopes,
      expiresAt: Math.floor(Date.now() / 1000) + 3600,
      resource: new URL('https://api.catstore.example/mcp'),
      extra: { team: found.team },
    };
  }
}

和真实令牌一样,测试令牌也需要在将来的 expiresAt 以及服务器的 resource。测试覆写 verifier 类,并用一个令牌连接:

test/orders.e2e-spec.ts
import { Test, type TestingModule } from '@nestjs/testing';
import type { Client } from '@modelcontextprotocol/client';
import { connectMcpClient } from '@nestjs/mcp/testing';
import { AppModule } from '../src/app.module.js';
import { IdentityProviderTokenVerifier } from '../src/auth/identity-provider-token.verifier.js';
import { TestTokenVerifier } from './test-token.verifier.js';

describe('cat-store MCP server', () => {
  let moduleRef: TestingModule;
  let client: Client;

  beforeAll(async () => {
    moduleRef = await Test.createTestingModule({ imports: [AppModule] })
      .overrideProvider(IdentityProviderTokenVerifier)
      .useClass(TestTokenVerifier)
      .compile();
    client = await connectMcpClient(moduleRef, { token: 'support-token' });
  });

  afterAll(async () => {
    await client.close();
    await moduleRef.close();
  });

  it('lists the tools', async () => {
    const { tools } = await client.listTools();
    expect(tools.map((tool) => tool.name)).toEqual(
      expect.arrayContaining(['find-order', 'change-address']),
    );
  });

  it('finds an order', async () => {
    const result = await client.callTool({
      name: 'find-order',
      arguments: { orderId: 'ord_123' },
    });
    expect(result.isError).toBeFalsy();
    expect(result.content).toEqual([
      { type: 'text', text: expect.stringContaining('ord_123') },
    ]);
  });
});

该客户端就是 SDK 自己的 Client:listTools()、callTool()、readResource()、getPrompt() 等方法正是助手所调用的。

结果与错误

工具里出问题,得到的是模型能读到的一条结果,而不是测试中的异常。isError 和文本说明了模型被告知了什么:

test/orders.e2e-spec.ts
it('tells the model about arguments the schema refuses', async () => {
  const result = await client.callTool({
    name: 'change-address',
    arguments: { orderId: 'ord_123', address: 'Leeds' },
  });
  expect(result.isError).toBe(true);
  expect(result.content).toEqual([
    { type: 'text', text: expect.stringContaining('Input validation error') },
  ]);
});

it('returns structured content, as the output schema describes it', async () => {
  const result = await client.callTool({
    name: 'change-address',
    arguments: { orderId: 'ord_123', address: '12 Whisker Lane, Leeds' },
  });
  expect(result.structuredContent).toEqual({
    orderId: 'ord_123',
    address: '12 Whisker Lane, Leeds',
    status: 'pending',
  });
});

it('answers a guard refusal with a tool error', async () => {
  const warehouse = await connectMcpClient(moduleRef, {
    token: 'warehouse-token',
  });
  try {
    const result = await warehouse.callTool({
      name: 'change-address',
      arguments: { orderId: 'ord_123', address: '12 Whisker Lane, Leeds' },
    });
    expect(result).toMatchObject({
      isError: true,
      content: [{ type: 'text', text: 'Forbidden resource' }],
    });
  } finally {
    await warehouse.close();
  }
});

资源和提示词则反过来以 JSON-RPC 错误作答,客户端会抛出这些错误:

test/orders.e2e-spec.ts
it('reads an order', async () => {
  const { contents } = await client.readResource({ uri: 'orders://ord_123' });
  expect(JSON.parse((contents[0] as { text: string }).text)).toMatchObject({
    id: 'ord_123',
  });
});

it('knows no order that does not exist', async () => {
  await expect(
    client.readResource({ uri: 'orders://ord_404' }),
  ).rejects.toThrow();
});

it('drafts a reply', async () => {
  const { messages } = await client.getPrompt({
    name: 'draft-reply',
    arguments: { orderId: 'ord_123', tone: 'friendly' },
  });
  expect(messages[0].content).toMatchObject({
    type: 'text',
    text: expect.stringContaining('friendly'),
  });
});

令牌与作用域

测试需要哪个令牌,就为它连接一个客户端。缺少其工具所声明的作用域的调用,会在方法运行之前失败,并返回那种会告知真实客户端去请求用户授予更多权限的错误。没有令牌的客户端则根本连不上:

test/orders.e2e-spec.ts
import {
  InsufficientScopeError,
  SdkHttpError,
} from '@modelcontextprotocol/client';

it('asks for orders:write to change an address', async () => {
  const reader = await connectMcpClient(moduleRef, { token: 'reader-token' });
  try {
    const error = await reader
      .callTool({
        name: 'change-address',
        arguments: { orderId: 'ord_123', address: '12 Whisker Lane, Leeds' },
      })
      .catch((e: unknown) => e);
    expect(error).toBeInstanceOf(InsufficientScopeError);
    expect(error).toMatchObject({ requiredScope: 'orders:write' });
  } finally {
    await reader.close();
  }
});

it('refuses a client without a token', async () => {
  await expect(connectMcpClient(moduleRef)).rejects.toBeInstanceOf(
    SdkHttpError,
  );
});

请求头与协议修订版

headers 会在每个请求中发送请求头,守卫从 ctx.request.headers 以全小写形式读取。era: 'legacy' 以 2025 协议修订版的客户端连接,以检查服务器对两者都能工作:

test/orders.e2e-spec.ts
it('serves clients of the 2025 revisions', async () => {
  const legacy = await connectMcpClient(moduleRef, {
    token: 'support-token',
    era: 'legacy',
  });
  try {
    expect(legacy.getProtocolEra()).toBe('legacy');
    expect(
      (
        await legacy.callTool({
          name: 'find-order',
          arguments: { orderId: 'ord_123' },
        })
      ).isError,
    ).toBeFalsy();
  } finally {
    await legacy.close();
  }
});
提示

内存客户端从端点路由结束的地方开始:中间件,以及通过模块 decorators 给出的守卫都不会运行,ctx.request 是一个普通的 {{ '{' }} method, url, headers {{ '}' }} 对象。路由上会发生什么,请通过 HTTP 去测。

一次性覆盖每个原语

McpRegistry 保存模块启动时找到的内容。测试可以让每个工具都满足你自己定的规则,例如要求描述得能让模型用得上:

test/orders.e2e-spec.ts
import { McpRegistry } from '@nestjs/mcp';

it('describes every tool for the model', () => {
  for (const tool of moduleRef.get(McpRegistry).tools) {
    expect(
      tool.options.description?.length,
      `${tool.name} needs a description`,
    ).toBeGreaterThan(20);
  }
});

注册表在应用初始化时填充,connectMcpClient() 会做这件事;若没有它,请先调用 moduleRef.init()。

通过 HTTP

路由本身——全局前缀、中间件、CORS 和 Origin 检查——通过套接字来测。在空闲端口上启动应用,并向它发送请求:

test/mcp-endpoint.e2e-spec.ts
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module.js';

describe('MCP endpoint', () => {
  let app: INestApplication;
  let url: URL;

  const listTools = (headers: Record<string, string> = {}) =>
    fetch(url, {
      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' }),
    });

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleRef.createNestApplication();
    await app.listen(0);
    url = new URL('/mcp', await app.getUrl());
  });

  afterAll(() => app.close());

  it('points a client without a token at the metadata', async () => {
    const response = await listTools();
    expect(response.status).toBe(401);
    expect(response.headers.get('www-authenticate')).toContain(
      'resource_metadata=',
    );
  });

  it('refuses a page from another site', async () => {
    const response = await listTools({ origin: 'https://elsewhere.example' });
    expect(response.status).toBe(403);
  });
});

stdio 入口点

要像客户端那样测 stdio.ts,请构建应用,并用 SDK 的 stdio 传输启动它:

test/stdio.e2e-spec.ts
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';

it('serves the tools over stdio', async () => {
  const client = new Client({ name: 'stdio-e2e', version: '1.0.0' });
  await client.connect(
    new StdioClientTransport({
      command: process.execPath,
      args: ['dist/stdio.js'],
    }),
  );
  try {
    const { tools } = await client.listTools();
    expect(tools.map((tool) => tool.name)).toContain('find-order');
  } finally {
    await client.close();
  }
});

关闭客户端会关闭该进程的 stdin,应用随之关闭,与助手退出时一样。