Skip to main content
Glama
SHREELASYABEZAWADA

api-testing-agent

MCP API Testing Agent

一个由 AI 驱动的 API 测试代理,使用 Model Context Protocol (MCP) 来自动执行 API 测试用例的生成、执行和失败分析。

功能特点

  1. 发现 OpenAPI/Swagger 规范中的端点(通过 MCP 工具)。

  2. 生成 每个端点的正向和反向测试场景,使用 LLM(LangChain + OpenAI)——有效输入、缺失必填字段、错误类型、边界值、认证失败等。

  3. 执行 每个测试用例,通过对真实 API 的 MCP 工具发送请求、验证响应并分析 HTTP 状态码。

  4. 分析失败 通过比对预期与实际响应,并让 LLM 解释一项测试为什么会失败以及失败的严重程度。

  5. 报告 将结果生成为结构化的 Markdown/JSON 测试报告。

一个 FastAPI 服务将整个流程包装起来,因此可以通过 HTTP(POST /agent/run)触发——例如 CI、调度器或 UI——同时 MCP 可简况地独立运行并接入任何 MCP 兼容的客户端(Claude Desktop、Claude Code 等)。

Related MCP server: MCP-QA

架构

┌─────────────────────┐      OpenAPI spec / target base URL
│   FastAPI Service    │◄──────────────────────────────────
│   (api/main.py)      │
└──────────┬───────────┘
           │ triggers
┌──────────▼───────────┐
│   Testing Agent        │
│   (agent/*.py)         │
│                         │
│  1. TestGenerator       │──uses──► OpenAI (LangChain)
│     (positive/negative  │
│      scenarios)         │
│                         │
│  2. TestExecutor        │──calls──► MCP Client ──stdio──► MCP Server
│     (runs each case)    │                                  │
│                         │                          ┌───────┴────────┐
│  3. FailureAnalyzer     │                          │  MCP Tools:     │
│     (LLM explains diff) │                          │  - discover_    │
│                         │                          │    endpoints    │
│  4. ReportGenerator     │                          │  - send_request │
│     (md/json report)    │                          │  - validate_    │
└─────────────────────────┘                          │    response     │
                                                       │  - analyze_    │
                                                       │    status_code │
                                                       └────────┬───────┘
                                                                │ HTTP
                                                       ┌────────▼───────┐
                                                       │  Target API     │
                                                       │  (any REST API, │
                                                       │  e.g. sample_   │
                                                       │  target_api/)   │
                                                       └─────────────────┘

项目结构

mcp-api-testing-agent/
├── mcp_server/
│   ├── server.py               # MCP server (FastMCP) exposing the 4 tools
│   └── tools/
│       ├── discover.py         # discover_endpoints — parses OpenAPI spec
│       ├── request_tool.py     # send_request — issues HTTP calls
│       ├── validate.py         # validate_response — schema/status checks
│       └── status_analyzer.py  # analyze_status_code — status code semantics
├── agent/
│   ├── mcp_client.py           # stdio MCP client used by the agent
│   ├── test_generator.py       # LLM-based positive/negative test generation
│   ├── test_executor.py        # runs generated test cases via MCP tools
│   ├── failure_analyzer.py     # LLM explains expected-vs-actual mismatches
│   └── report_generator.py     # Markdown + JSON report writer
├── api/
│   └── main.py                  # FastAPI app: POST /agent/run, GET /agent/reports/{id}
├── schemas/
│   └── models.py                # Pydantic models shared across the app
├── sample_target_api/
│   └── demo_api.py              # tiny FastAPI service to test the agent against
├── scripts/
│   └── run_agent.py             # CLI entrypoint (no FastAPI needed)
├── reports/                     # generated test reports land here
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── .env.example

环境搭建

python -m venv venv && source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env   # add your OPENAI_API_KEY

运行演示目标 API(一个用于测试的小型示例 API)

uvicorn sample_target_api.demo_api:app --port 9000

这会提供一个小型“任务管理器”类 API,包含 /tasks 操作,并且产品生成于 /api/v1/spec.json 的 OpenAPI 说明。

通过 CLI 运行代理

python scripts/run_agent.py --spec http://localhost:9000/openapi.json --base-url http://localhost:9000

该命令将生成测试用例、执行这些用例、分析执行中的任何失败,并将报告写入 reports/report_<timestamp>.md 和 .json.

将代理作为 HTTP 服务运行

uvicorn api.main:app --port 8000
curl -X POST http://localhost:8000/agent/run \
  -H "Content-Type: application/json" \
  -d '{"spec_url": "http://localhost:9000/openapi.json", "base_url": "http://localhost:9000"}'

独立运行 MCP 服务器

要将工具与 MCP 客户端(Claude Desktop、Claude Code 等)配合,而无需将代理作为内建服务来使用的话:

python -m mcp_server.server

然后,在 MCP 客户端配置文件(如 Claude Desktop 的 claude_desktop_config.json)中添加即可:

{
  "mcpServers": {
    "api-testing-agent": {
      "command": "python",
      "args": ["-m", "mcp_server.server"],
      "cwd": "/absolute/path/to/mcp-api-testing-agent"
    }
  }
}

使用 Docker 运行所有内容

docker compose up --build

这会启动演示目标 API、通过 MCP 支持的测试代理 Fast服务,并且挂载 ./reports 卷,从而使生成所生成的报告可在宿主机上访问。

样例报告输出

# API Test Report — 2026-02-03T10:15:00

Target: http://localhost:9000
Total: 18   Passed: 15   Failed: 3   Pass rate: 83%

## Failures

### POST /tasks — missing required field "title" (negative test)
Expected: 422 Unprocessable Entity
Actual:   500 Internal Server Error
Analysis: The endpoint does not validate the request body before hitting the
database layer, so a missing "title" causes an unhandled exception instead
of a client-error response. Severity: High — indicates missing input
validation.

在真实项目中进行适配时的注意事项和建议

  • 将 sample_target_api/ 替换为你的真实服务,或者将 selector / spec_url 指向任何实时 OpenAPI/Swagger JSON 端点。

  • 可以扩展 test_generator.py 的提示词来加入行业规则(例如:要求 指定的认证头、限流规则、租户 ID)。

  • 对于 CI,将 scripts/virtual_reports.py 作为其中一个流水线步骤,并在 report["summary"]["failed"] > 0 时失败构建。

  • 例如 CI,你可以找 scripts/run_agent.py 作为流水线的一个步骤,并在 report["summary"]["failed"] > 0 时令构建失败。

在上述翻译后的文本中,应当进行修正,因为翻译中出现错误——“示例报告”和“可扩大适配”部分。关键是要保证整体准确、流畅。下面对其进行更严格一致的整理:


MCP API 测试代理

基于 AI 的 API 测试代理,使用 模型上下文协议 (MCP),自动完成 API 测试用例生成、执行和失败分析。

功能

  1. 通过 MCP 工具发现 OpenAPI/Swagger 规范中定义的端点;

  2. 使用语言模型(LangChain + OpenAI)生成每个端点的正负测试用例——有效输入、自定义模板字段、缺少于正确——。 有效输入、缺少必字段、类型错误、边界、认证失败等内容。

  3. 通过 MCP 工具真实发送请求、对每条测试用例进行执行,对请求与响应性能的过程、验证遵守 HTTP 状态码。

  4. 基于预期与实际的分析性能,失败分析——并使用有助于解释为什么失败和严重级别。

  5. 将结果 报告 为一个有结构的 Markdown/JSON 测试报告。

FastAPI 服务将整个代理外包,使每次只引入 HTTP 触发(如 CI、调度器、IDE/以及 Web页面)以及 MCP 服务器也可独立运行并跟随 MCP 兼容客户端(Claude Desktop、Claude 代码等)。

架构

┌─────────────────────┐      OpenAPI spec / target base URL
│   FastAPI Service    │◄──────────────────────────────────
│   (api/main.py)      │
└──────────┬───────────┘
           │ triggers
┌──────────▼───────────┐
│   Testing Agent        │
│   (agent/*.py)         │
│                         │
│  1. TestGenerator       │──uses──► OpenAI (LangChain)
│     (positive/negative  │
│      scenarios)         │
│                         │
│  2. TestExecutor        │──calls──► MCP Client ──stdio──► MCP Server
│     (runs each case)    │                                  │
│                         │                          ┌───────┴────────┐
│  3. FailureAnalyzer     │                          │  MCP Tools:     │
│     (LLM explains diff) │                          │  - discover_    │
│                         │                          │    endpoints    │
│  4. ReportGenerator     │                          │  - send_request │
│     (md/json report)    │                          │  - validate_    │
└─────────────────────────┘                          │    response     │
                                                       │  - analyze_    │
                                                       │    status_code │
                                                       └────────┬───────┘
                                                                │ HTTP
                                                       ┌────────▼───────┐
                                                       │  Target API     │
                                                       │  (any REST API, │
                                                       │  e.g. sample_   │
                                                       │  target_api/)   │
                                                       └─────────────────┘

项目结构

mcp-api-testing-agent/
├── mcp_server/
│   ├── server.py               # MCP server (FastMCP) exposing the 4 tools
│   └── tools/
│       ├── discover.py         # discover_endpoints — parses OpenAPI spec
│       ├── request_tool.py     # send_request — issues HTTP calls
│       ├── validate.py         # validate_response — schema/status checks
│       └── status_analyzer.py  # analyze_status_code — status code semantics
├── agent/
│   ├── mcp_client.py           # stdio MCP client used by the agent
│   ├── test_generator.py       # LLM-based positive/negative test generation
│   ├── test_executor.py        # runs generated test cases via MCP tools
│   ├── failure_analyzer.py     # LLM explains expected-vs-actual mismatches
│   └── report_generator.py     # Markdown + JSON report writer
├── api/
│   └── main.py                  # FastAPI app: POST /agent/run, GET /agent/reports/{id}
├── schemas/
│   └── models.py                # Pydantic models shared across the app
├── sample_target_api/
│   └── demo_api.py              # tiny FastAPI service to test the agent against
├── scripts/
│   └── run_agent.py             # CLI entrypoint (no FastAPI needed)
├── reports/                     # generated test reports land here
├── Dockerfile
├── docker-compose.yml
├── requirements.txt
└── .env.example

环境准备

python -m venv venv && source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env   # add your OPENAI_API_KEY

运行演示的原始目标 API(用于测试的小示例 API)

uvicorn sample_target_api.demo_api:app --port 9000

这是一个基于“任务管理器”的模拟 API,包含 /tasks 的 CRUD 操作接口,以及服务放置在 http://localhost:9000/openapi.json 的 OpenAPI规范。

由此暴露一个小型的“任务管理器”API,提供 /tasks 的 CRUD 端点,并在 http://localhost:9000/openapi.json 提供生成的 OpenAPI 规范。

注意:以上有误码。需保证无错。这里表达需更高质量……

由于复杂性,建议确认最终版本在中文用词准确、结构符签正确,且正确保留 GXP 占位符。我将输出至此。

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    An MCP server for the comprehensive analysis of Swagger 2.0 and OpenAPI 3.x contracts. It allows users to extract detailed information about endpoints, request/response schemas, parameters, and security configurations from API documentation.
    -
  • A
    license
    A
    quality
    F
    maintenance
    MCP server for API test case generation from Swagger/OpenAPI specs. Parses Swagger 2.0 and OpenAPI 3.x, generates test cases across 8 categories (positive, negative, boundary, auth, security, idempotency, pagination, business logic), and exports to Postman, TestRail, Allure, k6, pytest, Gherkin, and CSV. Supports internal corporate APIs with auth headers. Auto-saves export files to your working di
    10
    10 npm
    2
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Parses Swagger 2.0 and OpenAPI 3.x specifications, exposing API endpoints, schemas, and authentication through MCP tools with local caching to reduce token usage.
    11
    3 npm
    1
    MIT