关于 MockLoop MCP - AI-Native Testing Platform
MockLoop MCP 是面向 API 开发和验证团队的测试平台,支持 AI 工作流。它可从 OpenAPI 规范生成模拟服务,并提供场景测试、状态管理、日志和分析功能。
主要功能
- 01根据 OpenAPI 生成模拟服务
- 02生成并执行测试场景
- 03运行负载和安全测试
- 04管理有状态测试上下文
- 05分析日志和性能指标
- 06在模拟与真实 API 模式间切换
适用场景
- 01根据 OpenAPI 规范创建 API 模拟服务
- 02测试错误、安全或负载场景
- 03查看请求日志并比较测试运行结果
- 04在模拟 API 与真实 API 间路由请求
MCP 相关
它向 MCP 客户端提供测试工具、提示词和场景资源,包括模拟服务生成、测试执行、上下文管理和分析。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
注意:我们已 完整 实现 SchemaPin,以帮助抵御 GitHub 和其他地方出现的可疑项目副本。请务必确认你使用的是此仓库发布的版本,并可使用 SchemaPin 验证我们的工具架构:https://mockloop.com/.well-known/schemapin.json

MockLoop MCP - AI 原生测试平台
全球首个由模型上下文协议(MCP)驱动的 AI 原生 API 测试平台。MockLoop MCP 通过全面的 AI 驱动场景生成、自动化测试执行和智能分析能力,革新 API 测试。
**🚀 革新性能力:**5 个 AI 提示词 • 15 个场景资源 • 16 个测试工具 • 10 个上下文工具 • 4 个核心工具 • 完整的 MCP 集成
**📚 文档:**https://docs.mockloop.com
**📦 PyPI 软件包:**https://pypi.org/project/mockloop-mcp/
**🐙 GitHub 仓库:**https://github.com/mockloop/mockloop-mcp
🌟 MockLoop MCP 的革新之处
MockLoop MCP 为 API 测试带来了范式转变,推出全球首个 AI 原生测试架构,融合了:
- **🤖 AI 驱动的测试生成:**5 个专用 MCP 提示词,用于智能创建场景
- **📦 社区场景包:**15 个精选测试资源,采用社区架构
- **⚡ 自动化测试执行:**30 个全面的 MCP 工具,支持完整测试工作流(16 个测试工具 + 10 个上下文工具 + 4 个核心工具)
- **🔄 有状态测试:**通过 GlobalContext 和 AgentContext 实现高级上下文管理
- **📊 企业合规:**完整的审计日志和法规合规跟踪
- **🏗️ 双端口架构:**使用独立的模拟 API 端口和管理端口,消除
/admin路径冲突
🎯 AI 原生核心架构
MCP 审计日志
企业级合规与法规跟踪
- 完整的请求/响应审计记录
- 法规合规监控
- 性能指标与分析
- 安全事件日志
MCP 提示词(5 项 AI 驱动能力)
由 AI 驱动的智能场景生成
analyze_openapi_for_testing- 全面的 API 分析,用于制定测试策略generate_scenario_config- 动态测试场景配置optimize_scenario_for_load- 负载测试优化generate_error_scenarios- 错误条件模拟generate_security_test_scenarios- 安全漏洞测试
MCP 资源(15 个场景包)
由社区驱动、采用先进架构的测试场景
- 负载测试场景:高流量模拟
- 错误模拟包:全面测试错误条件
- 安全测试套件:漏洞评估场景
- 性能基准:标准化性能测试
- 集成测试包:跨服务测试场景
- 社区架构:协作共享和验证场景
MCP 工具(16 个自动化测试工具)
完整的自动化测试执行能力
场景管理(4 个工具)
validate_scenario_config- 场景验证与校验deploy_scenario- 自动化场景部署switch_scenario- 动态场景切换list_active_scenarios- 活动场景监控
测试执行(4 个工具)
execute_test_plan- 全面执行测试计划run_test_iteration- 单次测试迭代管理run_load_test- 执行负载测试run_security_test- 自动化安全测试
分析与报告(4 个工具)
analyze_test_results- 智能分析测试结果generate_test_report- 生成全面报告compare_test_runs- 比较测试运行结果和趋势get_performance_metrics- 收集性能指标
工作流管理(4 个工具)
create_test_session- 初始化测试会话end_test_session- 清理并结束会话schedule_test_suite- 自动安排测试monitor_test_progress- 实时监控进度
MCP 上下文管理(10 个有状态工作流工具)
用于复杂测试工作流的高级状态管理
上下文创建与管理
create_test_session_context- 测试会话状态管理create_workflow_context- 复杂工作流编排create_agent_context- AI Agent 状态管理
数据管理
get_context_data- 检索上下文数据update_context_data- 动态更新上下文list_contexts_by_type- 发现并列出上下文
快照与恢复
create_context_snapshot- 创建状态快照restore_context_snapshot- 支持回滚状态
全局上下文
get_global_context_data- 跨会话共享数据update_global_context_data- 管理全局状态
🚀 快速入门
开始使用全球最先进的 AI 原生测试平台:
# 1. Install MockLoop MCP
pip install mockloop-mcp
# 2. Verify installation
mockloop-mcp --version
# 3. Configure with your MCP client (Cline, Claude Desktop, etc.)
# See configuration examples below
📋 先决条件
- Python 3.10+
- Pip 包管理器
- Docker 和 Docker Compose(用于容器化模拟服务)
- 兼容 MCP 的客户端(Cline、Claude Desktop 等)
🔧 安装
选项 1:从 PyPI 安装(推荐)
# Install the latest stable version
pip install mockloop-mcp
# Or install with optional dependencies
pip install mockloop-mcp[dev] # Development tools
pip install mockloop-mcp[docs] # Documentation tools
pip install mockloop-mcp[all] # All optional dependencies
# Verify installation
mockloop-mcp --version
选项 2:开发环境安装
# Clone the repository
git clone https://github.com/mockloop/mockloop-mcp.git
cd mockloop-mcp
# Create and activate virtual environment
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install in development mode
pip install -e ".[dev]"
⚙️ 配置
MCP 客户端配置
Cline(VS Code 扩展)
添加到 Cline MCP 设置文件:
{
"mcpServers": {
"MockLoopLocal": {
"autoApprove": [],
"disabled": false,
"timeout": 60,
"command": "mockloop-mcp",
"args": [],
"transportType": "stdio"
}
}
}
Claude Desktop
添加到 Claude Desktop 配置:
{
"mcpServers": {
"mockloop": {
"command": "mockloop-mcp",
"args": []
}
}
}
虚拟环境安装
对于虚拟环境安装,请使用完整的 Python 路径:
{
"mcpServers": {
"MockLoopLocal": {
"command": "/path/to/your/venv/bin/python",
"args": ["-m", "mockloop_mcp"],
"transportType": "stdio"
}
}
}
🛠️ 可用的 MCP 工具
核心模拟生成
generate_mock_api
生成采用双端口架构的高级 FastAPI 模拟服务。
参数:
spec_url_or_path(字符串,必填):API 规范 URL 或本地文件路径output_dir_name(字符串,可选):输出目录名称auth_enabled(布尔值,可选):启用身份验证中间件(默认值:true)webhooks_enabled(布尔值,可选):启用 Webhook 支持(默认值:true)admin_ui_enabled(布尔值,可选):启用管理界面(默认值:true)storage_enabled(布尔值,可选):启用存储功能(默认值:true)
革新性的双端口架构:
- 模拟 API 端口:提供 API 端点服务(默认值:8000)
- 管理界面端口:独立的管理界面(默认值:8001)
- 冲突解决:消除 OpenAPI 规范中的
/admin路径冲突 - 增强安全性:基于端口的访问控制和隔离
高级分析
query_mock_logs
查询并分析请求日志,获取 AI 驱动的洞察。
参数:
server_url(字符串,必填):模拟服务 URLlimit(整数,可选):返回日志的最大数量(默认值:100)offset(整数,可选):分页偏移量(默认值:0)method(字符串,可选):按 HTTP 方法筛选path_pattern(字符串,可选):用于路径筛选的正则表达式time_from(字符串,可选):起始时间筛选条件(ISO 格式)time_to(字符串,可选):结束时间筛选条件(ISO 格式)include_admin(布尔值,可选):包含管理请求(默认值:false)analyze(布尔值,可选):执行 AI 分析(默认值:true)
AI 驱动的分析:
- 性能指标(P95/P99 响应时间)
- 错误率分析与分类
- 流量模式检测
- 自动调试建议
- 会话关联与追踪
discover_mock_servers
支持双端口架构的智能服务发现。
参数:
ports(数组,可选):要扫描的端口(默认为常用端口)check_health(布尔值,可选):执行健康检查(默认为true)include_generated(布尔值,可选):包含生成的模拟服务(默认为true)
高级发现功能:
- 自动检测架构(单端口或双端口)
- 健康状态监控
- 服务关联与匹配
- 端口使用情况分析
manage_mock_data
无需重启服务即可动态管理响应。
参数:
server_url(字符串,必填):模拟服务 URLoperation(字符串,必填):操作类型("update_response"、"create_scenario"、"switch_scenario"、"list_scenarios")endpoint_path(字符串,可选):API 端点路径response_data(对象,可选):新的响应数据scenario_name(字符串,可选):场景名称scenario_config(对象,可选):场景配置
动态能力:
- 实时更新响应
- 基于场景的测试
- 运行时配置管理
- 零停机修改
🌐 MCP 代理功能
MockLoop MCP 包含创新的代理能力,可在模拟环境和实时 API 环境之间无缝切换。这项强大功能通过提供以下能力,彻底改变您的测试工作流:
核心代理能力
- 🔄 无缝模式切换:无需更改代码即可在模拟、代理和混合模式之间切换
- 🎯 智能路由:根据可配置的规则和条件智能路由请求
- 🔐 通用身份验证:支持 API Key、Bearer Token、Basic Auth 和 OAuth2
- 📊 响应比较:自动比较模拟响应与实时 API 响应
- ⚡ 零停机切换:动态切换模式,不中断服务
运行模式
模拟模式(MOCK)
- 所有请求均由生成的模拟响应处理
- 提供可预测且一致的测试环境
- 适用于早期开发和隔离测试
- 无需外部依赖或网络调用
代理模式(PROXY)
- 所有请求均转发至实时 API 端点
- 提供实时数据和真实响应
- 支持完整的集成测试
- 运行时依赖网络和有效凭据
混合模式(HYBRID)
- 根据规则在模拟和代理之间智能路由
- 根据请求模式、标头或参数进行条件切换
- 从模拟环境逐步迁移至实时环境
- 支持 A/B 测试和选择性端点代理
快速入门示例
from mockloop_mcp.mcp_tools import create_mcp_plugin
# Create a proxy-enabled plugin
plugin_result = await create_mcp_plugin(
spec_url_or_path="https://api.example.com/openapi.json",
mode="hybrid", # Start with hybrid mode
plugin_name="example_api",
target_url="https://api.example.com",
auth_config={
"auth_type": "bearer_token",
"credentials": {"token": "your-token"}
},
routing_rules=[
{
"pattern": "/api/critical/*",
"mode": "proxy", # Critical endpoints use live API
"priority": 10
},
{
"pattern": "/api/dev/*",
"mode": "mock", # Development endpoints use mocks
"priority": 5
}
]
)
高级功能
- 🔍 响应验证:比较模拟响应与实时响应的一致性
- 📈 性能监控:跟踪不同模式下的响应时间和吞吐量
- 🛡️ 错误处理:提供优雅的回退机制和重试策略
- 🎛️ 动态配置:运行时切换模式并更新规则
- 📋 审计日志:完整跟踪所有模式下的请求和响应
身份验证支持
代理系统支持全面的身份验证方案:
- API Key:支持通过标头、查询参数或 Cookie 进行身份验证
- Bearer Token:支持 OAuth2 和 JWT 令牌
- Basic Auth:用户名和密码组合
- OAuth2:完整的 OAuth2 流程,支持令牌刷新
- 自定义:可扩展的身份验证处理程序,支持专有方案
使用场景
- 开发工作流:从模拟服务开始,逐步引入实时 API
- 集成测试:在保持测试隔离的同时,针对真实服务进行验证
- 性能测试:比较模拟 API 与实时 API 的性能特征
- 预发布验证:确保模拟响应符合生产 API 的行为
- 混合部署:将关键操作路由至实时 API,其余操作路由至模拟服务
📚 完整指南:有关详细配置、示例和最佳实践,请参阅 MCP 代理指南。
🤖 AI 框架集成
MockLoop MCP 可原生集成多种热门 AI 框架:
LangGraph 集成
from langgraph.graph import StateGraph, END
from mockloop_mcp import MockLoopClient
# Initialize MockLoop client
mockloop = MockLoopClient()
def setup_ai_testing(state):
"""AI-driven test setup"""
# Generate mock API with AI analysis
result = mockloop.generate_mock_api(
spec_url_or_path="https://api.example.com/openapi.json",
output_dir_name="ai_test_environment"
)
# Use AI prompts for scenario generation
scenarios = mockloop.analyze_openapi_for_testing(
api_spec=state["api_spec"],
analysis_depth="comprehensive",
include_security_tests=True
)
state["mock_server_url"] = "http://localhost:8000"
state["test_scenarios"] = scenarios
return state
def execute_ai_tests(state):
"""Execute AI-generated test scenarios"""
# Deploy AI-generated scenarios
for scenario in state["test_scenarios"]:
mockloop.deploy_scenario(
server_url=state["mock_server_url"],
scenario_config=scenario
)
# Execute load tests with AI optimization
results = mockloop.run_load_test(
server_url=state["mock_server_url"],
scenario_name=scenario["name"],
duration=300,
concurrent_users=100
)
# AI-powered result analysis
analysis = mockloop.analyze_test_results(
test_results=results,
include_recommendations=True
)
state["test_results"].append(analysis)
return state
# Build AI-native testing workflow
workflow = StateGraph(dict)
workflow.add_node("setup_ai_testing", setup_ai_testing)
workflow.add_node("execute_ai_tests", execute_ai_tests)
workflow.set_entry_point("setup_ai_testing")
workflow.add_edge("setup_ai_testing", "execute_ai_tests")
workflow.add_edge("execute_ai_tests", END)
app = workflow.compile()
CrewAI 多 Agent 测试
from crewai import Agent, Task, Crew
from mockloop_mcp import MockLoopClient
# Initialize MockLoop client
mockloop = MockLoopClient()
# AI Testing Specialist Agent
api_testing_agent = Agent(
role='AI API Testing Specialist',
goal='Generate and execute comprehensive AI-driven API tests',
backstory='Expert in AI-native testing with MockLoop MCP integration',
tools=[
mockloop.generate_mock_api,
mockloop.analyze_openapi_for_testing,
mockloop.generate_scenario_config
]
)
# Performance Analysis Agent
performance_agent = Agent(
role='AI Performance Analyst',
goal='Analyze API performance with AI-powered insights',
backstory='Specialist in AI-driven performance analysis and optimization',
tools=[
mockloop.run_load_test,
mockloop.get_performance_metrics,
mockloop.analyze_test_results
]
)
# Security Testing Agent
security_agent = Agent(
role='AI Security Testing Expert',
goal='Conduct AI-driven security testing and vulnerability assessment',
backstory='Expert in AI-powered security testing methodologies',
tools=[
mockloop.generate_security_test_scenarios,
mockloop.run_security_test,
mockloop.compare_test_runs
]
)
# Define AI-driven tasks
ai_setup_task = Task(
description='Generate AI-native mock API with comprehensive testing scenarios',
agent=api_testing_agent,
expected_output='Mock server with AI-generated test scenarios deployed'
)
performance_task = Task(
description='Execute AI-optimized performance testing and analysis',
agent=performance_agent,
expected_output='Comprehensive performance analysis with AI recommendations'
)
security_task = Task(
description='Conduct AI-driven security testing and vulnerability assessment',
agent=security_agent,
expected_output='Security test results with AI-powered threat analysis'
)
# Create AI testing crew
ai_testing_crew = Crew(
agents=[api_testing_agent, performance_agent, security_agent],
tasks=[ai_setup_task, performance_task, security_task],
verbose=True
)
# Execute AI-native testing workflow
results = ai_testing_crew.kickoff()
LangChain AI 测试工具
from langchain.agents import Tool, AgentExecutor, create_react_agent
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from mockloop_mcp import MockLoopClient
# Initialize MockLoop client
mockloop = MockLoopClient()
# AI-Native Testing Tools
def ai_generate_mock_api(spec_path: str) -> str:
"""Generate AI-enhanced mock API with intelligent scenarios"""
# Generate mock API
result = mockloop.generate_mock_api(spec_url_or_path=spec_path)
# Use AI to analyze and enhance
analysis = mockloop.analyze_openapi_for_testing(
api_spec=spec_path,
analysis_depth="comprehensive",
include_security_tests=True
)
return f"AI-enhanced mock API generated: {result}\nAI Analysis: {analysis['summary']}"
def ai_execute_testing_workflow(server_url: str) -> str:
"""Execute comprehensive AI-driven testing workflow"""
# Create test session context
session = mockloop.create_test_session_context(
session_name="ai_testing_session",
configuration={"ai_enhanced": True}
)
# Generate and deploy AI scenarios
scenarios = mockloop.generate_scenario_config(
api_spec=server_url,
scenario_types=["load", "error", "security"],
ai_optimization=True
)
results = []
for scenario in scenarios:
# Deploy scenario
mockloop.deploy_scenario(
server_url=server_url,
scenario_config=scenario
)
# Execute tests with AI monitoring
test_result = mockloop.execute_test_plan(
server_url=server_url,
test_plan=scenario["test_plan"],
ai_monitoring=True
)
results.append(test_result)
# AI-powered analysis
analysis = mockloop.analyze_test_results(
test_results=results,
include_recommendations=True,
ai_insights=True
)
return f"AI testing workflow completed: {analysis['summary']}"
# Create LangChain tools
ai_testing_tools = [
Tool(
name="AIGenerateMockAPI",
func=ai_generate_mock_api,
description="Generate AI-enhanced mock API with intelligent testing scenarios"
),
Tool(
name="AIExecuteTestingWorkflow",
func=ai_execute_testing_workflow,
description="Execute comprehensive AI-driven testing workflow with intelligent analysis"
)
]
# Create AI testing agent
llm = ChatOpenAI(temperature=0)
ai_testing_prompt = PromptTemplate.from_template("""
You are an AI-native testing assistant powered by MockLoop MCP.
You have access to revolutionary AI-driven testing capabilities including:
- AI-powered scenario generation
- Intelligent test execution
- Advanced performance analysis
- Security vulnerability assessment
- Stateful workflow management
Tools available: {tools}
Tool names: {tool_names}
Question: {input}
{agent_scratchpad}
""")
agent = create_react_agent(llm, ai_testing_tools, ai_testing_prompt)
agent_executor = AgentExecutor(agent=agent, tools=ai_testing_tools, verbose=True)
# Execute AI-native testing
response = agent_executor.invoke({
"input": "Generate a comprehensive AI-driven testing environment for a REST API and execute full testing workflow"
})
🏗️ 双端口架构
MockLoop MCP 引入了革命性的双端口架构,可消除常见冲突并增强安全性:
架构优势
- 🔒 增强安全性:完全分离模拟 API 和管理功能
- ⚡ 零冲突:消除 OpenAPI 规范中的 /admin 路径冲突
- 📊 清晰的分析数据:管理调用不会出现在模拟 API 指标中
- 🔄 独立扩展:分别扩展模拟 API 和管理服务
- 🛡️ 基于端口的访问控制:通过网络隔离增强安全性
端口配置
# Generate mock with dual-port architecture
result = mockloop.generate_mock_api(
spec_url_or_path="https://api.example.com/openapi.json",
business_port=8000, # Mocked API port
admin_port=8001, # Admin UI port
admin_ui_enabled=True
)
访问地址
- 模拟 API:
http://localhost:8000— 你的 API 端点 - 管理界面:
http://localhost:8001— 管理界面 - API 文档:
http://localhost:8000/docs— 交互式 Swagger UI - 健康检查:
http://localhost:8000/health— 服务状态
📊 企业级功能
合规与审计日志
MockLoop MCP 提供企业级合规功能:
- 完整审计追踪:记录每次请求/响应及其元数据
- 法规合规:支持 GDPR、SOX、HIPAA 合规
- 性能指标:P95/P99 响应时间、错误率
- 安全监控:威胁检测与分析
- 会话追踪:跨请求关联与分析
高级分析
- AI 驱动的洞察:智能分析与建议
- 流量模式检测:自动异常检测
- 性能优化:AI 驱动的性能建议
- 错误分析:智能错误分类与解决
- 趋势分析:历史性能与使用趋势
🔄 有状态测试工作流
MockLoop MCP 通过高级上下文管理支持复杂的有状态测试工作流:
上下文类型
- 测试会话上下文:在多次测试执行间保持状态
- 工作流上下文:复杂的多步骤测试编排
- Agent 上下文:AI Agent 状态管理与协调
- 全局上下文:跨会话数据共享与持久化
示例:有状态电商测试
# Create test session context
session = mockloop.create_test_session_context(
session_name="ecommerce_integration_test",
configuration={
"test_type": "integration",
"environment": "staging",
"ai_enhanced": True
}
)
# Create workflow context for multi-step testing
workflow = mockloop.create_workflow_context(
workflow_name="user_journey_test",
parent_context=session["context_id"],
steps=[
"user_registration",
"product_browsing",
"cart_management",
"checkout_process",
"order_fulfillment"
]
)
# Execute stateful test workflow
for step in workflow["steps"]:
# Update context with step data
mockloop.update_context_data(
context_id=workflow["context_id"],
data={"current_step": step, "timestamp": datetime.now()}
)
# Execute step-specific tests
test_result = mockloop.execute_test_plan(
server_url="http://localhost:8000",
test_plan=f"{step}_test_plan",
context_id=workflow["context_id"]
)
# Create snapshot for rollback capability
snapshot = mockloop.create_context_snapshot(
context_id=workflow["context_id"],
snapshot_name=f"{step}_completion"
)
# Analyze complete workflow results
final_analysis = mockloop.analyze_test_results(
test_results=workflow["results"],
context_id=workflow["context_id"],
include_recommendations=True
)
🚀 运行生成的模拟服务
使用 Docker Compose(推荐)
# Navigate to generated mock directory
cd generated_mocks/your_api_mock
# Start with dual-port architecture
docker-compose up --build
# Access points:
# Mocked API: http://localhost:8000
# Admin UI: http://localhost:8001
直接使用 Uvicorn
# Install dependencies
pip install -r requirements_mock.txt
# Start the mock server
uvicorn main:app --reload --port 8000
访问增强功能
- 管理界面:
http://localhost:8001— 增强的管理界面 - API 文档:
http://localhost:8000/docs— 交互式 Swagger UI - 健康检查:
http://localhost:8000/health— 服务状态和指标 - 日志分析:
http://localhost:8001/api/logs/search— 高级日志查询 - 性能指标:
http://localhost:8001/api/logs/analyze— AI 驱动的洞察 - 场景管理:
http://localhost:8001/api/mock-data/scenarios— 动态测试
📈 性能与可扩展性
MockLoop MCP 专为企业级性能而设计:
性能指标
- 响应时间:跟踪 P50、P95、P99 百分位数
- 吞吐量:监控每秒请求数
- 错误率:全面分析错误
- 资源使用情况:监控内存、CPU 和网络
- 并发:支持多用户负载测试
可扩展性功能
- 水平扩展:支持多实例部署
- 负载均衡:内置负载均衡能力
- 缓存:智能响应缓存
- 数据库优化:高效支持 SQLite 和 PostgreSQL
- 容器编排:支持 Kubernetes 和 Docker Swarm
🔒 安全功能
内置安全功能
- 身份验证中间件:可配置的身份验证机制
- 速率限制:防止滥用和 DoS 攻击
- 输入验证:全面的请求验证
- 安全标头:CORS、CSP 和安全标头
- 审计日志记录:完整记录安全事件
安全测试
- 漏洞评估:AI 驱动的安全测试
- 渗透测试:自动生成安全场景
- 合规性检查:验证是否符合安全标准
- 威胁建模:AI 驱动的威胁分析
- 安全报告:全面的安全分析
🔐 SchemaPin 集成 - 加密模式验证
MockLoop MCP 现已包含 SchemaPin 集成——业界首个面向 MCP 工具的加密模式验证系统,通过 ECDSA 签名验证和首次使用即信任(TOFU)密钥固定,防止「MCP Rug Pull」攻击。
革命性的安全增强
SchemaPin 集成让 MockLoop MCP 成为最安全的 MCP 测试平台,提供:
- 🔐 加密验证:ECDSA P-256 签名确保模式完整性
- 🔑 TOFU 密钥固定:自动发现并固定可信域的密钥
- 📋 策略执行:可配置的安全策略(enforce/warn/log 模式)
- 📊 全面审计:完整的验证日志,满足合规要求
- 🔄 平滑回退:无论是否安装 SchemaPin 库均可运行
- 🏗️ 混合架构:与现有 MockLoop 系统无缝集成
快速入门配置
from mockloop_mcp.schemapin import SchemaPinConfig, SchemaVerificationInterceptor
# Basic configuration
config = SchemaPinConfig(
enabled=True,
policy_mode="warn", # enforce, warn, or log
auto_pin_keys=False,
trusted_domains=["api.example.com"],
interactive_mode=False
)
# Initialize verification
interceptor = SchemaVerificationInterceptor(config)
# Verify tool schema
result = await interceptor.verify_tool_schema(
tool_name="database_query",
schema=tool_schema,
signature="base64_encoded_signature",
domain="api.example.com"
)
if result.valid:
print("✓ Schema verification successful")
else:
print(f"✗ Verification failed: {result.error}")
生产环境配置
# Production-ready configuration
config = SchemaPinConfig(
enabled=True,
policy_mode="enforce", # Block execution on verification failure
auto_pin_keys=True, # Auto-pin keys for trusted domains
key_pin_storage_path="/secure/path/keys.db",
discovery_timeout=60,
cache_ttl=7200,
trusted_domains=[
"api.corp.com",
"tools.internal.com"
],
well_known_endpoints={
"api.corp.com": "https://api.corp.com/.well-known/schemapin.json"
},
revocation_check=True,
interactive_mode=False
)
安全优势
MCP Rug Pull 防护
SchemaPin 可防止恶意行为者在不被察觉的情况下修改工具模式:
- 加密签名:每个工具模式都经过加密签名
- 密钥固定:TOFU 模型可防止中间人攻击
- 审计轨迹:完整的验证日志,便于安全分析
- 策略执行:可配置对验证失败的响应方式
合规与治理
- 法规合规:审计日志支持 GDPR、SOX、HIPAA 要求
- 企业安全:与现有安全框架集成
- 风险管理:针对不同环境配置安全策略
- 威胁检测:自动检测模式篡改企图
集成示例
基本工具验证
# Verify a single tool
from mockloop_mcp.schemapin import SchemaVerificationInterceptor
interceptor = SchemaVerificationInterceptor(config)
result = await interceptor.verify_tool_schema(
"api_call", tool_schema, signature, "api.example.com"
)
批量验证
# Verify multiple tools efficiently
from mockloop_mcp.schemapin import SchemaPinWorkflowManager
workflow = SchemaPinWorkflowManager(config)
results = await workflow.verify_tool_batch([
{"name": "tool1", "schema": schema1, "signature": sig1, "domain": "api.com"},
{"name": "tool2", "schema": schema2, "signature": sig2, "domain": "api.com"}
])
MCP 代理集成
# Integrate with MCP proxy for seamless security
class SecureMCPProxy:
def __init__(self, config):
self.interceptor = SchemaVerificationInterceptor(config)
async def proxy_tool_request(self, tool_name, schema, signature, domain, data):
# Verify schema before execution
result = await self.interceptor.verify_tool_schema(
tool_name, schema, signature, domain
)
if not result.valid:
return {"error": "Schema verification failed"}
# Execute tool with verified schema
return await self.execute_tool(tool_name, data)
策略模式
强制模式
config = SchemaPinConfig(policy_mode="enforce")
# Blocks execution on verification failure
# Recommended for production critical tools
警告模式
config = SchemaPinConfig(policy_mode="warn")
# Logs warnings but allows execution
# Recommended for gradual rollout
日志模式
config = SchemaPinConfig(policy_mode="log")
# Logs events without blocking
# Recommended for monitoring and testing
密钥管理
首次使用即信任(TOFU)
# Automatic key discovery and pinning
key_manager = KeyPinningManager("keys.db")
# Pin key for trusted tool
success = key_manager.pin_key(
tool_id="api.example.com/database_query",
domain="api.example.com",
public_key_pem=discovered_key,
metadata={"developer": "Example Corp"}
)
# Check if key is pinned
if key_manager.is_key_pinned("api.example.com/database_query"):
print("Key is pinned and trusted")
密钥发现
SchemaPin 会通过 .well-known 端点自动发现公钥:
https://api.example.com/.well-known/schemapin.json
预期格式:
{
"public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
"algorithm": "ES256",
"created_at": "2023-01-01T00:00:00Z"
}
审计与合规
全面日志记录
from mockloop_mcp.schemapin import SchemaPinAuditLogger
audit_logger = SchemaPinAuditLogger("audit.db")
# Verification events are automatically logged
stats = audit_logger.get_verification_stats()
print(f"Total verifications: {stats['total_verifications']}")
print(f"Success rate: {stats['successful_verifications'] / stats['total_verifications'] * 100:.1f}%")
合规报告
# Generate compliance reports
from mockloop_mcp.mcp_compliance import MCPComplianceReporter
reporter = MCPComplianceReporter("audit.db")
report = reporter.generate_schemapin_compliance_report()
print(f"Compliance score: {report['compliance_score']:.1f}%")
print(f"Verification coverage: {report['verification_statistics']['unique_tools']} tools")
文档与示例
- 📚 完整集成指南:
docs/guides/schemapin-integration.md - 🔧 基本用法示例:
examples/schemapin/basic_usage.py - ⚡ 高级模式:
examples/schemapin/advanced_usage.py - 🏗️ 架构文档:
SchemaPin_MockLoop_Integration_Architecture.md - 🧪 测试覆盖:56 项全面测试(42 项单元测试 + 14 项集成测试)
现有用户迁移
SchemaPin 集成 完全向后兼容:
- 选择启用配置:SchemaPin 默认禁用
- 无破坏性变更:现有工具可继续正常运行
- 逐步推出:从
log模式开始,再切换到warn,最后切换到enforce - 零停机时间:无需中断服务即可启用验证
# Migration example: gradual rollout
# Phase 1: Monitoring (log mode)
config = SchemaPinConfig(enabled=True, policy_mode="log")
# Phase 2: Warnings (warn mode)
config = SchemaPinConfig(enabled=True, policy_mode="warn")
# Phase 3: Enforcement (enforce mode)
config = SchemaPinConfig(enabled=True, policy_mode="enforce")
性能影响
SchemaPin 的设计力求将性能影响降至最低:
- 验证时间:每个工具约 5-15ms(使用缓存结果)
- 内存用量:额外内存 <10MB
- 网络开销:仅在首次使用时发现密钥
- 数据库大小:每个固定密钥约 1KB
使用场景
开发团队
- 安全开发:在开发过程中验证工具架构
- 代码审查:确保拉取请求中的架构完整性
- 测试:使用经过验证的架构检查工具行为
企业安全
- 威胁防范:阻止恶意架构修改
- 合规性:通过审计跟踪满足监管要求
- 风险管理:可配置的安全策略
- 事件响应:提供详细日志以进行安全分析
DevOps 和 CI/CD
- 流水线安全:在部署流水线中验证架构
- 环境晋级:确保各环境之间的架构一致性
- 监控:持续监控验证情况
- 自动化:自动执行安全策略
�️ 未来开发
即将推出的功能 🚧
增强的 AI 能力
- 高级 ML 模型:为 API 测试训练自定义模型
- 预测分析:由 AI 驱动的故障预测
- 智能测试生成:能够自我改进的测试场景
- 自然语言测试:使用通俗英语编写测试描述
扩展协议支持
- GraphQL 支持:原生 GraphQL API 测试
- gRPC 集成:支持 Protocol Buffer 测试
- WebSocket 测试:实时通信测试
- 事件驱动测试:异步和基于事件的 API 测试
企业集成
- CI/CD 集成:原生流水线集成
- 监控平台:集成 Datadog、New Relic、Prometheus
- 身份提供商:集成 SSO 和企业身份验证
- 合规框架:扩展监管合规支持
🤝 参与贡献
欢迎为 MockLoop MCP 贡献!详情请参阅我们的贡献指南。
开发环境设置
# Fork and clone the repository
git clone https://github.com/your-username/mockloop-mcp.git
cd mockloop-mcp
# Create development environment
python3 -m venv .venv
source .venv/bin/activate
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/
# Run quality checks
ruff check src/
bandit -r src/
社区
- GitHub 仓库:mockloop/mockloop-mcp
- 问题和 Bug 报告:GitHub Issues
- 功能请求:GitHub Issues
- 文档:docs.mockloop.com
📄 许可证
MockLoop MCP 基于 MIT License 许可。
🎉 立即开始!
准备好使用全球首个 AI 原生测试平台,革新你的 API 测试了吗?
pip install mockloop-mcp
加入 AI 原生测试革命,借助 MockLoop MCP 体验 API 测试的未来!
🚀 立即开始 →
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。