使用说明
MCP工具厂
生成与以下对象兼容的通用MCP服务器 任何 AI代理框架。
一次构建,随处运行:Claude、OpenAI、Google ADK、LangChain、CrewAI等等。
为什么选择MCP?
MCP(模型上下文协议)是人工智能工具的通用标准:
- 由Anthropic创建(2024年11月)
- OpenAI采纳(2025年3月)
- 由谷歌、LangChain、CrewAI、LlamaIdex提供支持
- 捐赠给Linux基金会(2025年12月)
一个MCP服务器=适用于所有框架。
特性
| 特性 | 描述 |
|---|---|
| 自然语言 | 用简单的英语描述工具,获取可用代码 |
| OpenAPI导入 | 使用身份验证支持自动转换REST API |
| 数据库CRUD | 从SQLite/PPostgreSQL模式生成工具 |
| 多供应商 | Anthropic、OpenAI、谷歌Gemini支持 |
| 网页搜索 | 在生成代码之前研究API |
| 身份验证注入 | 内置API密钥管理 |
| 健康检查 | 监控服务器和身份验证状态 |
| CI/CD就绪 | 包括GitHub操作工作流 |
| 完整日志记录 | 完整的执行跟踪 |
快速开始
安装
pip install mcp-tool-factory
安装您首选的LLM提供程序:
# Anthropic Claude (recommended)
pip install mcp-tool-factory[anthropic]
# OpenAI GPT
pip install mcp-tool-factory[openai]
# Google Gemini
pip install mcp-tool-factory[google]
# All providers
pip install mcp-tool-factory[all-providers]
设置API密钥
cp .env.example .env
编辑 .env:
# Choose one:
ANTHROPIC_API_KEY=sk-ant-api03-xxxxx
# OPENAI_API_KEY=sk-xxxxx
# GOOGLE_API_KEY=xxxxx
获取API密钥:
- 人类学:https://console.anthropic.com/
- OpenAI:https://platform.openai.com/api-keys
- 谷歌https://aistudio.google.com/apikey
用法
1.从自然语言生成
# Basic generation
mcp-factory generate "Create a tool that fetches weather data for any city"
# With web search for API docs
mcp-factory generate "Stock price API using Alpha Vantage" --web-search
# With API key injection
mcp-factory generate "Weather API" --auth WEATHER_API_KEY --auth BACKUP_KEY
# Disable health check
mcp-factory generate "Simple calculator" --no-health-check
# Use specific provider
mcp-factory generate "Date utilities" --provider openai --model gpt-5.2
2.根据OpenAPI规范生成
# Auto-detect base URL and auth from spec
mcp-factory from-openapi petstore.yaml
# Override base URL
mcp-factory from-openapi api.json --base-url https://api.example.com
# Custom server name
mcp-factory from-openapi spec.yaml --name MyAPIServer
支持的身份验证类型:
- API密钥(头、查询、cookie)
- 承载令牌
- OAuth2
- 基本认证
3.从数据库生成
# SQLite database
mcp-factory from-database ./myapp.db
# Specific tables only
mcp-factory from-database ./data.db --tables users --tables orders
# PostgreSQL
mcp-factory from-database "postgresql://user:pass@host/db" --type postgresql
生成的CRUD工具:
get_<table>-按主键获取记录list_<table>-带过滤和分页的列表create_<table>-插入新记录update_<table>-更新现有记录delete_<table>-删除记录
4.测试和服务
# Run tests
mcp-factory test ./servers/my-server
# Start server for testing
mcp-factory serve ./servers/my-server
# With SSE transport
mcp-factory serve ./servers/my-server --transport sse --port 8080
生成的输出
每一代都会创建一个完整的服务器包:
servers/my-server/
├── server.py # FastMCP server with all tools
├── tests/
│ ├── __init__.py
│ └── test_tools.py # Pytest tests
├── .github/
│ └── workflows/
│ └── ci.yml # GitHub Actions CI/CD
├── Dockerfile # Container config with HEALTHCHECK
├── pyproject.toml # Package configuration
├── README.md # Usage documentation
├── skill.md # Claude Code skill file
├── EXECUTION_LOG.md # Full generation trace
└── execution_log.json # Machine-readable log
与AI框架一起使用
克劳德代码/克劳德桌面
添加 .claude/mcp.json:
{
"mcpServers": {
"my-tools": {
"command": "python",
"args": ["./servers/my-server/server.py"],
"env": {
"API_KEY": "your-api-key"
}
}
}
}
OpenAI代理SDK
from agents import Agent
from agents.mcp import MCPServerStdio
async with MCPServerStdio(
command="python",
args=["./servers/my-server/server.py"],
env={"API_KEY": "your-key"}
) as mcp:
agent = Agent(name="MyAgent", mcp_servers=[mcp])
LangChain
from langchain_mcp_adapters import load_mcp_tools
tools = await load_mcp_tools(
command="python",
args=["./servers/my-server/server.py"]
)
agent = create_react_agent(llm, tools)
谷歌ADK
from google.adk.tools import MCPToolAdapter
adapter = MCPToolAdapter(
command="python",
args=["./servers/my-server/server.py"]
)
agent = Agent(tools=[adapter])
CLI 参考
# Natural language generation
mcp-factory generate "description" [OPTIONS]
--output, -o Output directory (default: ./servers)
--name, -n Server name
--provider, -p LLM provider: claude_code, anthropic, openai, google
--model, -m Model to use
--web-search, -w Search web for API docs first
--auth, -a Auth env vars (repeatable)
--health-check Include health check (default: enabled)
# OpenAPI generation
mcp-factory from-openapi OPENAPI_PATH [OPTIONS]
--base-url, -u API base URL (auto-detected if not set)
--output, -o Output directory
--name, -n Server name (auto-generated if not set)
# Database generation
mcp-factory from-database DATABASE_PATH [OPTIONS]
--type, -t Database type: sqlite, postgresql
--output, -o Output directory
--name, -n Server name
--tables, -T Specific tables (repeatable)
# Testing & serving
mcp-factory test SERVER_PATH
mcp-factory serve SERVER_PATH [--transport stdio|sse] [--port 8000]
# Info
mcp-factory info
配置
支持的供应商和型号
拟人克劳德(推荐)
| 型号ID | 描述 |
|---|---|
claude-sonnet-4-5-20241022 |
Sonnet 4.5-最适合代理(默认) |
claude-opus-4-5-20251101 |
Opus 4.5-最智能 |
claude-haiku-4-5-20241022 |
俳句4.5-最快 |
claude-opus-4-20250514 |
Opus 4-优秀的编码 |
开放人工智能
| 型号ID | 描述 |
|---|---|
gpt-5.2 |
GPT-5.2-最新旗舰(默认) |
gpt-5.1 |
GPT-5.1-增强个性化 |
gpt-4.1 |
GPT-4.1-1M上下文,出色的编码 |
o3 |
o3-最佳推理 |
o4-mini |
o4-mini-快速推理 |
谷歌双子座
| 型号ID | 描述 |
|---|---|
gemini-3-flash |
Gemini 3闪光灯(默认) |
gemini-3-pro |
Gemini 3 Pro-能力最强 |
gemini-2.5-flash |
Gemini 2.5闪光灯-物超所值 |
程序化使用
from tool_factory import ToolFactoryAgent
from tool_factory.config import FactoryConfig, LLMProvider
# Auto-detect provider from environment
agent = ToolFactoryAgent()
# Explicit configuration
config = FactoryConfig(
provider=LLMProvider.ANTHROPIC,
model="claude-sonnet-4-5-20241022",
api_key="your-api-key",
)
agent = ToolFactoryAgent(config=config)
# Generate server
result = agent.generate_from_description_sync(
description="Create a currency converter tool",
server_name="CurrencyServer",
web_search=True,
auth_env_vars=["EXCHANGE_API_KEY"],
include_health_check=True,
)
# Write to disk
result.write_to_directory("./servers/currency")
OpenAPI程序化使用
import asyncio
import yaml
agent = ToolFactoryAgent()
with open("api.yaml") as f:
spec = yaml.safe_load(f)
result = asyncio.run(agent.generate_from_openapi(
openapi_spec=spec,
base_url="https://api.example.com", # Optional, auto-detected
server_name="MyAPIServer",
))
数据库编程使用
from tool_factory.database import (
DatabaseType,
DatabaseIntrospector,
DatabaseServerGenerator,
)
# Introspect schema
introspector = DatabaseIntrospector(
DatabaseType.SQLITE,
"./myapp.db"
)
tables = introspector.get_tables()
# Generate server
generator = DatabaseServerGenerator(
DatabaseType.SQLITE,
"./myapp.db",
tables=tables,
)
server_code = generator.generate_server_code("MyDBServer")
建筑
┌─────────────────────────────────────────────────────────────────────────┐
│ MCP TOOL FACTORY │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────────┐ │
│ │ INPUT │ │ PROCESSING │ │ OUTPUT │ │
│ ├──────────────────┤ ├──────────────────┤ ├──────────────────────┤ │
│ │ • Natural Lang │ │ • Web Search │ │ • MCP Server │ │
│ │ • OpenAPI Spec │ → │ • LLM Generation │ → │ • Tests │ │
│ │ • Database │ │ • Code Gen │ │ • Dockerfile │ │
│ │ │ │ • Validation │ │ • CI/CD Workflow │ │
│ └──────────────────┘ └──────────────────┘ │ • Documentation │ │
│ │ • Execution Log │ │
│ └──────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────────────────┐ │
│ │ LLM PROVIDERS │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │ │
│ │ │ Anthropic│ │ OpenAI │ │ Google │ │ Claude Agent SDK │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────────────┘ │ │
│ └──────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
│
▼
Works with ALL MCP-compatible frameworks
┌──────────┬──────────┬──────────┬──────────┬──────────┐
│ Claude │ OpenAI │ Google │ LangChain│ CrewAI │
│ Code │ Agents │ ADK │ │ │
└──────────┴──────────┴──────────┴──────────┴──────────┘
例子
天气API与Auth
mcp-factory generate "Weather API using OpenWeatherMap" \
--web-search \
--auth OPENWEATHER_API_KEY \
--name WeatherServer
生成 server.py 包括:
# Auth configuration
AUTH_CONFIG = {
"OPENWEATHER_API_KEY": os.environ.get("OPENWEATHER_API_KEY"),
}
@mcp.tool()
def health_check() -> dict:
"""Check server health and auth status."""
return {
"status": "healthy",
"auth_config": {"OPENWEATHER_API_KEY": "configured"},
...
}
@mcp.tool()
def get_weather(city: str) -> dict:
"""Get current weather for a city."""
api_key = require_auth("OPENWEATHER_API_KEY")
...
来自OpenAPI的REST API
mcp-factory from-openapi petstore.yaml
为每个端点自动生成工具,包括:
- 路径参数插值
- 查询参数处理
- 请求身体支持
- 身份验证标头
- 错误处理
数据库CRUD
mcp-factory from-database ./ecommerce.db --tables products --tables orders
生成完整的CRUD操作:
@mcp.tool()
def get_products(id: int) -> dict: ...
@mcp.tool()
def list_products(name: str = None, price: float = None, limit: int = 100) -> dict: ...
@mcp.tool()
def create_products(name: str, price: float, ...) -> dict: ...
@mcp.tool()
def update_products(id: int, name: str = None, price: float = None) -> dict: ...
@mcp.tool()
def delete_products(id: int) -> dict: ...
支持的框架
| 框架 | 支持 | 集成 |
|---|---|---|
| Claude代码 | 原生 | 内置MCP客户端 |
| Claude Desktop | 原生 | 内置MCP客户端 |
| OpenAI代理SDK | 原生 | mcp_servers 参数 |
| Google ADK | Native | MCP工具适配器 |
| LangChain | 本地 | langchain-mcp-adapters |
| CrewAI | 原生 | MCP集成 |
| LlamaIndex | 原生 | MCP工具规范 |
发展
# Clone and install
git clone https://github.com/HeshamFS/mcp-tool-factory
cd mcp-tool-factory
pip install -e ".[dev]"
# Run tests
pytest
# Type check
mypy src/
# Format
black src/
ruff check src/
项目结构
mcp-tool-factory/
├── src/tool_factory/
│ ├── __init__.py
│ ├── agent.py # Main ToolFactoryAgent
│ ├── cli.py # CLI commands
│ ├── config.py # Configuration & providers
│ ├── models.py # Data models
│ ├── prompts.py # LLM prompts
│ ├── openapi.py # OpenAPI parser & validator
│ ├── database.py # Database introspection & CRUD
│ ├── web_search.py # Web search integration
│ ├── execution_logger.py # Full execution logging
│ ├── production.py # Rate limiting, metrics
│ ├── validation.py # Generated code validation
│ ├── auth/ # OAuth2/PKCE authentication
│ │ ├── oauth2.py
│ │ ├── pkce.py
│ │ └── providers.py
│ ├── generators/
│ │ ├── server.py # Server code generator
│ │ ├── docs.py # Documentation generator
│ │ └── tests.py # Test generation
│ ├── middleware/
│ │ └── validation.py # Request/response validation
│ ├── observability/
│ │ └── telemetry.py # OpenTelemetry integration
│ ├── providers/ # LLM provider implementations
│ │ ├── anthropic.py
│ │ ├── openai.py
│ │ ├── google.py
│ │ └── claude_code.py
│ ├── security/
│ │ └── scanner.py # Security vulnerability scanning
│ ├── utils/
│ │ ├── input_validation.py
│ │ └── dependencies.py # Package versioning
│ └── templates/
│ └── server.py.jinja
├── tests/ # 498 tests
├── servers/ # Generated servers
├── pyproject.toml
├── .env.example
└── README.md
生产特点
OAuth2/PKCE身份验证
生成支持OAuth2身份验证的服务器:
from tool_factory.auth import OAuth2Config, PKCECodeVerifier
# Configure OAuth2
config = OAuth2Config(
client_id="your-client-id",
authorization_url="https://example.com/oauth/authorize",
token_url="https://example.com/oauth/token",
scopes=["read", "write"],
pkce_enabled=True, # RFC 7636
)
# Generate PKCE verifier/challenge
verifier = PKCECodeVerifier.generate()
auth_url = config.get_authorization_url(
code_challenge=verifier.challenge,
code_challenge_method="S256",
)
速率限制
内置内存或Redis后端的速率限制:
from tool_factory.production import ProductionConfig, RateLimitBackend
config = ProductionConfig(
rate_limit_enabled=True,
rate_limit_requests=100,
rate_limit_window_seconds=60,
rate_limit_backend=RateLimitBackend.REDIS, # or MEMORY
redis_url="redis://localhost:6379",
)
开放遥测集成
生产服务器的跟踪和指标:
from tool_factory.observability import TelemetryConfig, TelemetryExporter
config = TelemetryConfig(
enabled=True,
service_name="my-mcp-server",
exporter_type=TelemetryExporter.OTLP, # OTLP, Jaeger, Zipkin, Azure
endpoint="http://localhost:4317",
)
安全扫描
扫描生成的代码以查找漏洞:
from tool_factory.security import scan_code, scan_file
# Scan code string
issues = scan_code('password = "hardcoded123"')
# Scan file
issues = scan_file("./servers/my-server/server.py")
for issue in issues:
print(f"[{issue.severity}] {issue.message}")
检测到的问题包括:
- 硬编码凭证
- SQL注入模式
- 命令注入(eval、exec、os.system)
- 不安全密码学(MD5、SHA-1)
- 不安全的反序列化(pickle、yaml.load)
- SSL验证已禁用
输入验证
生成服务器的标准化验证实用程序:
from tool_factory.utils import (
validate_string,
validate_email,
validate_url,
validate_finite,
sanitize_string,
)
# Validate inputs
result = validate_email(user_input, "email")
if not result.is_valid:
raise ValueError(result.error)
# Sanitize against XSS
safe_text = sanitize_string(user_input)
故障排除
常见错误
找不到API密钥
Error: ANTHROPIC_API_KEY not set
解决方案:在中设置API密钥 .env 或环境:
export ANTHROPIC_API_KEY=sk-ant-api03-xxxxx
超出费率限制
Error: Rate limit exceeded. Retry after 60 seconds.
解决方案:
- 等待速率限制窗口重置
- 使用Redis后端进行分布式速率限制
- 降低请求频率
生成的服务器语法错误
SyntaxError: invalid syntax in server.py
解决方案:
- 检查生成的代码中是否缺少导入
- 跑
python -m py_compile server.py验证语法 - 报告导致该问题的工具描述问题
OpenAPI验证失败
Error: OpenAPI spec validation failed: missing required field 'paths'
解决方案:
- 确保你的OpenAPI规范有所有必填字段(OpenAPI、info、path)
- 使用OpenAPI 3.0+格式
- 验证方式
openapi-spec-validator进口前
数据库连接失败
Error: Could not connect to database
解决方案:
- 验证数据库路径/URL是否正确
- 检查SQLite的文件权限
- 确保PostgreSQL正在运行且可访问
提供商特定问题
Anthropic
| 问题 | 解决方案 |
|---|---|
invalid_api_key |
验证密钥以开头 sk-ant-api03- |
overloaded_error |
使用指数回退重试 |
context_length_exceeded |
减小输入大小或使用更大的模型 |
开放人工智能
| 问题 | 解决方案 |
|---|---|
invalid_api_key |
验证密钥以开头 sk- |
rate_limit_exceeded |
等待或升级API层 |
model_not_found |
检查型号名称(例如。, gpt-4,不 gpt4) |
谷歌
| 问题 | 解决方案 |
|---|---|
PERMISSION_DENIED |
在Google Cloud中启用Generative AI API |
INVALID_ARGUMENT |
检查型号名称格式 |
RESOURCE_EXHAUSTED |
等待配额重置 |
限速最佳实践
- 单个实例:使用内存后端(默认)
- 多个实例:使用Redis后端
- 建议限值:
- 开发:100个请求/分钟
- 生产:Redis每分钟1000个请求
from tool_factory.production import ProductionConfig, RateLimitBackend
# For production with multiple instances
config = ProductionConfig(
rate_limit_enabled=True,
rate_limit_backend=RateLimitBackend.REDIS,
redis_url="redis://localhost:6379",
)
更新日志
v0.3.0(当前)
- OAuth2/PKCE身份验证:支持PKCE的完整OAuth2流(RFC 7636)
- 速率限制:内存和Redis支持的滑动窗口速率限制
- 开放遥测:与多个导出器(OTLP、Jaeger、Zipkin、Azure)进行跟踪和度量
- 安全扫描:检测生成代码中的漏洞
- 输入验证:标准化验证实用程序
- 请求/响应验证:JSON模式验证中间件
- 提供商架构:将LLM提供者重构为单独的模块
- 依赖关系版本控制:所有软件包的真实版本约束
- 增强的测试生成:具有模拟支持的功能测试
- 498次测试 代码覆盖率为68%
v0.2.0版本
- 添加
from-databaseSQLite/PPostgreSQL CRUD生成命令 - 使用auth(API密钥、Bearer、OAuth2、Basic)增强了对OpenAPI的支持
- 添加
--authAPI密钥注入的标志 - 为所有生成的服务器添加了健康检查端点
- 添加了GitHub Actions CI/CD工作流生成
- 根据OpenAPI规范自动检测基本URL和身份验证
- 使用完整的原始数据改进执行日志记录
v0.1.0
- 初始版本
- 自然语言到MCP服务器生成
- 基本的OpenAPI支持
- 多提供商LLM支持(Anthropic、OpenAI、谷歌)
- API文档的Web搜索
许可证
麻省理工学院
链接
- github:https://github.com/HeshamFS/mcp-tool-factory
- MCP规范:https://modelcontextprotocol.io
- FastMCP:https://github.com/jlowin/fastmcp