mcp检测试剂盒

测试MCP服务器所需的测试库。
概述
mcp-testing-kit 提供实用程序进行测试 模型上下文协议(MCP) 服务器。它允许您连接到MCP服务器实例,发送请求,接收通知,并在测试中断言服务器行为。
特性
- 适用于任何测试框架(vitest、jest等)
- 轻量级,提供“刚好足够”的实用程序来测试MCP服务器。
- 打字稿
安装
$ npm i -D mcp-testing-kit示例
假设您在中定义了MCP服务器 example/basic/src/index.ts:
// mcp-server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
const server = new McpServer({ name: 'simple-mcp-server', version: '1.0.0' });
server.tool(
'add',
'Add two numbers MCP style',
{
a: z.number().describe('first number'),
b: z.number().describe('second number')
},
async ({ name }) => ({
messages: [
{ role: 'user', content: { type: 'text', text: String(a + b) } }
]
})
);
export default server;您可以使用以下命令编写测试 mcp-testing-kit 这样地:
// mcp-server.test.js
import server from "../src/index.js";
// Use your favorite testing framework.
import { describe, it, expect, afterEach } from "vitest";
import { connect, close } from "../../../index.js";
describe("Basic MCP server", () => {
afterEach(async () => {
await close(server);
});
it("Should return correct sum when `sum` is called", async () => {
// Connect to the server and create a mock client.
const client = await connect(server);
const result = await client.callTool("greeting-template", { a: 10, b: 2 });
expect(result.content[0].text).toEqual("12");
});
});运作原理
- 创建一个虚拟传输层,直接连接到MCP服务器,而不依赖于HTTP/SSE。
- 提供抽象,用于直接在服务器上调用工具/资源/提示。
API
connect(server: Server)
连接到MCP服务器实例,并使用以下方法返回客户端:
| 方法 | 签名 | 描述 |
|---|---|---|
listTools | `(): Promise | |
| ` | 列出服务器上注册的所有工具。 | |
callTool | (tool: string, params?: any): Promise | 使用可选参数按名称调用工具。 |
listResources | `(): Promise | |
| ` | 列出服务器上注册的所有资源。 | |
listPrompts | `(): Promise | |
| ` | 列出服务器上注册的所有提示。 | |
getPrompt | (prompt: string, params?: any): Promise | 使用可选参数按名称获取提示。 |
onNotification | (cb: (message: JSONRPCMessage) => void): void | 为来自服务器的通知注册回调。 |
onError | (cb: (message: JSONRPCMessage) => void): void | 为来自服务器的错误消息注册回调。 |
onProgress | (cb: (message: JSONRPCMessage) => void): void | 为来自服务器的进度通知注册回调。 |
sendToServer | (message: Request): Promise | 向服务器发送原始JSON-RPC请求。 |
close(server: Server)
关闭MCP服务器实例。
更多示例
看 example/basic 用于功能齐全的MCP服务器和相应的测试。
许可证
麻省理工学院
