MCP服务器测试工具

MCPSpec是一个用于测试和验证Model Context Protocol服务器的工具,提供录制、模拟、安全审计和CI集成功能。

  • by light-handle
  • TypeScript
  • 本地部署
  • 7 星标
  • 更新于
在 GitHub 查看 light-handle/mcpspec

使用说明

MCPSpec

Ship reliable MCP servers with confidence

Record sessions, generate mock servers, gate your CI pipeline, and catch Tool Poisoning — all without writing a single line of test code. The testing and reliability platform for Model Context Protocol servers.


为什么选择MCPSpec?

确定性。 与基于LLM的测试不同,MCPSpec运行快速且可重复。没有不稳定的测试,没有象征性的成本。非常适合CI。

安全。 抓住 工具中毒 (在工具说明中提示注入)和 过度代理 (没有防护措施的破坏性工具)在投入生产之前。

协同。 记录一次服务器交互,与团队共享模拟服务器。前端开发人员和CI管道可以针对mock进行测试——没有API密钥,没有实时依赖关系。


快速开始

# Install
npm install -g mcpspec

# Explore a server interactively
mcpspec inspect "npx @modelcontextprotocol/server-filesystem /tmp"

# Record a session — no test code needed
mcpspec record start "npx my-server"

# Generate a mock for your team
mcpspec mock my-recording --generate ./mocks/server.js

# Add CI gating in 30 seconds
mcpspec ci-init

30秒后试试 使用预先构建的社区集合——无需设置:

mcpspec test examples/collections/servers/filesystem.yaml
mcpspec test examples/collections/servers/time.yaml --tag smoke

查看全部 70次社区测试 适用于7个流行的MCP服务器。


记录与模拟

录制一次会话。回放它以捕捉回归。嘲笑CI。不需要API密钥。

# 1. Record a session against your real server
mcpspec record start "npx my-server"
mcpspec> .call get_user {"id": "1"}
mcpspec> .call list_items {}
mcpspec> .save my-api

# 2. Replay against a new version — catch regressions instantly
mcpspec record replay my-api "npx my-server-v2"

# 3. Start a mock server — drop-in replacement, zero dependencies
mcpspec mock my-api

# 4. Generate a standalone .js file — commit to your repo
mcpspec mock my-api --generate ./mocks/server.js
node ./mocks/server.js

回放输出 确切地显示了发生了什么变化:

Replaying 3 steps...

  1/3 get_user (id=1)...       [OK] 42ms → {"name": "Alice"}
  2/3 list_items...            [CHANGED] 38ms → {"items": [...]}
  3/3 create_item (name=test)  [OK] 51ms → {"id": "abc"}

Summary: 2 matched, 1 changed, 0 added, 0 removed

模拟选项:

选项 效果
--mode match (默认) 每个工具先进行精确输入匹配,然后进行排队响应
--mode sequential 磁带/盒式磁带——按记录顺序送达的回复
--latency original 模拟原始响应时间
--latency 100 固定100ms延迟
--on-missing empty 对于未记录的工具,返回空值而不是错误
--generate <path> 独立输出 .js 文件(仅需要 @modelcontextprotocol/sdk)

管理录制:

mcpspec record list                    # List saved recordings
mcpspec record delete my-session       # Delete a recording

CI/CD集成

ci-init 生成即用型流水线配置。确定性退出代码和JUnit/JSON/TAP报告器,实现无缝CI集成。

mcpspec ci-init                                 # Interactive wizard
mcpspec ci-init --platform github               # GitHub Actions
mcpspec ci-init --platform gitlab               # GitLab CI
mcpspec ci-init --platform shell                # Shell script
mcpspec ci-init --checks test,audit,score       # Choose checks
mcpspec ci-init --fail-on medium                # Audit severity gate
mcpspec ci-init --min-score 70                  # MCP Score threshold
mcpspec ci-init --force                         # Overwrite/replace existing

自动检测平台 .github/ 或 .gitlab-ci.ymlGitLab --force 通过手术仅替换mcpspec作业块,保留其他作业。

GitHub操作示例 (由 mcpspec ci-init --platform github):

name: MCP Server Tests
on: [push, pull_request]

jobs:
  mcpspec:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '22'
      - run: npm install -g mcpspec
      - name: Run tests
        run: mcpspec test --ci --reporter junit --output results.xml
      - name: Security audit
        run: mcpspec audit "npx my-server" --fail-on high
      - name: Quality gate
        run: mcpspec score "npx my-server" --min-score 80
      - uses: mikepenz/action-junit-report@v4
        if: always()
        with:
          report_paths: results.xml

退出代码:

代码 含义
0 成功
1 测试失败
2 运行时错误
3 配置错误
4 连接错误
5 超时
6 安全调查结果高于阈值
7 验证错误
130 中断(Ctrl+C)

记者: 控制台(默认)、JSON、JUnit、HTML、点击。


安全审计

防止工具中毒。8条安全规则,涵盖传统漏洞和LLM特定威胁。安全过滤器自动跳过破坏性工具,以及 --dry-run 扫描前预览目标。

mcpspec audit "npx my-server"                        # Passive (safe)
mcpspec audit "npx my-server" --mode active           # Active probing
mcpspec audit "npx my-server" --fail-on medium        # CI gate
mcpspec audit "npx my-server" --exclude-tools delete  # Skip tools
mcpspec audit "npx my-server" --dry-run               # Preview targets

安全规则:

规则 模式 它检测到什么
工具中毒 被动 描述中的LLM提示注入、隐藏Unicode、跨工具操作
过度代理 被动 没有确认参数的破坏性工具,任意代码执行
路径遍历 被动 ../../etc/passwd 样式目录逃逸攻击
输入验证 被动 工具输入缺少约束(枚举、模式、最小/最大)
信息披露 被动 工具描述中的泄漏路径、堆栈跟踪、API密钥
资源耗尽 活动 无边界循环、大分配、递归
身份验证绕过 活动 缺少身份验证检查,硬编码凭据
注入 活动 工具输入中的SQL和命令注入

扫描模式:

  • 被动的 (默认)--5条规则,仅分析元数据,不调用工具。安全生产。
  • 活跃的 --所有8条规则都发送测试有效载荷。需要确认提示。
  • 激进的 --所有8条规则都有更详尽的探测。需要确认提示。

主动/攻击模式自动跳过与破坏性模式匹配的工具(delete_*, drop_*, destroy_*等),并要求明确确认,除非 --acknowledge-risk 已通过。

每个发现都包括严重性(信息/低/中/高/关键)、描述、证据和补救建议。


测试集

使用10种断言类型、环境、变量提取、标签、重试和并行执行在YAML中编写测试。

name: Filesystem Tests
server: npx @modelcontextprotocol/server-filesystem /tmp

tests:
  - name: Read a file
    call: read_file
    with:
      path: /tmp/test.txt
    expect:
      - exists: $.content
      - type: [$.content, string]

  - name: Handle missing file
    call: read_file
    with:
      path: /tmp/nonexistent.txt
    expectError: true

高级功能 --环境、标签、重试、变量提取、表达式:

schemaVersion: "1.0"
name: Advanced Tests

server:
  command: npx
  args: ["my-mcp-server"]
  env:
    NODE_ENV: test

environments:
  dev:
    variables:
      BASE_PATH: /tmp/dev
  staging:
    variables:
      BASE_PATH: /tmp/staging

defaultEnvironment: dev

tests:
  - id: create-data
    name: Create data
    tags: [smoke, write]
    timeout: 5000
    retries: 2
    call: create_item
    with:
      name: "test-item"
    assertions:
      - type: schema
      - type: exists
        path: $.id
      - type: latency
        maxMs: 1000
    extract:
      - name: itemId
        path: $.id

  - id: verify-data
    name: Verify created data
    tags: [smoke, read]
    call: get_item
    with:
      id: "{{itemId}}"
    assertions:
      - type: equals
        path: $.name
        value: "test-item"
      - type: expression
        expr: "response.id == itemId"

断言类型:

类型 描述 示例
schema 验证响应结构 type: schema
equals 精确匹配(深度比较) path: $.id, value: 123
contains 数组或字符串包含值 path: $.tags, value: "active"
exists 路径存在且不为空 path: $.name
matches 正则表达式模式匹配 path: $.email, pattern: ".*@.*"
type 类型检查 path: $.count, expected: number
length 数组/字符串长度 path: $.items, operator: gt, value: 0
latency 响应时间阈值 maxMs: 1000
mimeType 内容类型验证 expected: "image/png"
expression 安全表达式eval expr: "response.total > 0"

表达式使用 expr评估 --比较、逻辑运算符、属性访问、数学。没有任意代码执行。

速记格式 对于常见断言:

expect:
  - exists: $.field
  - equals: [$.id, 123]
  - contains: [$.tags, "active"]
  - matches: [$.email, ".*@.*"]

运行选项:

mcpspec test ./tests.yaml              # Specific file
mcpspec test --env staging             # Switch environment
mcpspec test --tag @smoke              # Filter by tag
mcpspec test --parallel 4              # Parallel execution
mcpspec test --reporter junit --output results.xml
mcpspec test --baseline main           # Compare against baseline
mcpspec test --watch                   # Re-run on file changes
mcpspec test --ci                      # CI mode (no colors)

MCP评分

5个加权类别的0-100质量评级,带有固执己见的模式梳理。用作CI门或为README生成徽章。

mcpspec score "npx my-server"
mcpspec score "npx my-server" --badge badge.svg       # Generate SVG badge
mcpspec score "npx my-server" --min-score 80          # Fail if below threshold

评分类别:

类别(重量) 它测量什么
文档(25%) 带有描述的工具和资源的百分比
架构质量(25%) 属性类型、描述、必填字段、约束(枚举/模式/最小/最大)、命名约定
错误处理(20%) 结构化错误响应(isError: true)与输入错误导致的崩溃相比
反应性(15%) 中位潜伏期:<100ms=100,<500ms=80,<1s=60,<5s=40
安全性(15%) 被动安全扫描结果:0=100,<=2=70,<=5=40

模式质量使用6个子标准:结构(20%)、属性类型(20%),描述(20%)和必填字段(15%),约束(15%)和命名约定(10%)。

这 --badge flag为您的README生成一个shields.io风格的SVG徽章。


更多功能

交互式检查器

连接到任何MCP服务器,并在实时REPL中探索其功能。

mcpspec inspect "npx @modelcontextprotocol/server-filesystem /tmp"
命令 描述
.tools 列出所有可用工具及其说明
.resources 列出所有可用资源(URI)
.call <tool> <json> 使用JSON输入调用工具
.schema <tool> 显示工具的JSON模式输入规范
.info 显示服务器信息(名称、版本、功能)
.help 显示帮助
.exit 断开连接并退出

性能基准

通过数百次迭代的统计分析来测量延迟和吞吐量。

mcpspec bench "npx my-server"                         # 100 iterations
mcpspec bench "npx my-server" --iterations 500
mcpspec bench "npx my-server" --tool read_file
mcpspec bench "npx my-server" --warmup 10

输出包括最小/最大/平均/中值/P95/P99延迟、标准偏差和吞吐量(呼叫/秒)。预热迭代(默认值:5)不包括在测量中。

文档生成器

从服务器自检自动生成Markdown或HTML文档。零手工书写。

mcpspec docs "npx my-server"                   # Markdown to stdout
mcpspec docs "npx my-server" --format html      # HTML output
mcpspec docs "npx my-server" --output ./docs    # Write to directory

Web仪表板

一个完整的React UI,用于管理服务器、运行测试、查看审计结果等。包括黑暗模式。

mcpspec ui                    # Opens localhost:6274
mcpspec ui --port 8080        # Custom port
mcpspec ui --no-open          # Don't auto-open browser

10页:仪表板、服务器、集合、运行、检查器、录制、审核、基准、文档、分数。

基线和比较

将测试运行保存为基线,并检测版本之间的回归。

mcpspec baseline save main                      # Save current run
mcpspec baseline list                           # List all baselines
mcpspec test --baseline main                    # Compare against baseline
mcpspec compare --baseline main                 # Explicit comparison
mcpspec compare <run-id-1> <run-id-2>           # Compare two runs

运输

MCPSpec支持连接到MCP服务器的3种传输类型:

运输 用例 连接
标准 本地进程 生成子进程,通过stdin/stdout进行通信
上海证券交易所 服务器发送事件 连接到HTTP SSE端点
超文本传输协议 流式HTTP 向HTTP端点发送POST请求
# stdio (default)
server:
  command: npx
  args: ["my-mcp-server"]

# SSE
server:
  transport: sse
  url: http://localhost:3000/sse

# HTTP
server:
  transport: http
  url: http://localhost:3000/mcp

命令

命令 描述
mcpspec record start <server> 记录检查员会议-- .call, .save, .steps
mcpspec record replay <name> <server> 重放录音并与原始录音进行比较
mcpspec mock <recording> 从录制中模拟服务器-- --mode, --latency, --on-missing, --generate
mcpspec test [collection] 使用以下命令运行测试集合 --env, --tag, --parallel, --reporter, --watch, --ci
mcpspec audit <server> 安全扫描-- --mode, --fail-on, --exclude-tools, --dry-run
mcpspec score <server> 质量分数(0-100)-- --badge badge.svg, --min-score
mcpspec ci-init 生成CI配置-- --platform github|gitlab|shell, --checks, --fail-on, --force
mcpspec inspect <server> 交互式REPL-- .tools, .call, .schema, .resources, .info
mcpspec bench <server> 性能基准-- --iterations, --tool, --args, --warmup
mcpspec docs <server> 生成文档-- --format markdown|html, --output <dir>
mcpspec compare 比较试运行或 --baseline <name>
mcpspec baseline save <name> 保存/列出回归检测的基线
mcpspec record list 列出已保存的录音
mcpspec record delete <name> 删除已保存的录制
mcpspec init [dir] 脚手架工程-- --template minimal|standard|full
mcpspec ui 在上启动web仪表板 localhost:6274

社区收藏

为流行的MCP服务器预构建的测试套件 examples/collections/servers/:

集合 服务器 测试
文件系统.yaml @modelcontextprotocol/server文件系统 12
memory.yaml @modelcontextprotocol/服务器内存 10
一切。yaml @modelcontextprotocol/server一切 11
fetch.yaml @modelcontextprotocol/server获取 7
time.yaml @modelcontextprotocol/服务器时间 10
chrome-devtools.yaml chrome开发工具mcp 11
github.yaml @modelcontextprotocol/server github 9

70次测试 涵盖工具发现、读/写操作、错误处理、安全边缘情况和延迟。

mcpspec test examples/collections/servers/filesystem.yaml
mcpspec test examples/collections/servers/time.yaml --tag smoke

建筑

包装 描述
@mcpspec/shared 类型、Zod模式、常量
@mcpspec/core MCP客户端、测试运行器、断言、安全扫描程序(8条规则)、分析器、文档生成器、评分器、记录/回放、模拟服务器
@mcpspec/cli 使用Commander.js构建的13个CLI命令
@mcpspec/server 带REST API+WebSocket的Hono HTTP服务器
@mcpspec/ui React SPA——TanStack路由器、TanStack查询、顺风、shadcn/ui

发展

git clone https://github.com/light-handle/mcpspec.git
cd mcpspec
pnpm install && pnpm build
pnpm test   # 334 tests across core + server

许可证

麻省理工学院