这是一个全面实现专业交易操作的最终MCP(模型上下文协议)服务器架构,完全符合Quick Data MCP参考架构中记录的金标准模式。
此实现代表了专业MCP开发的权威参考,实现了所有7个核心架构模式,并提供了涵盖交易操作、高级分析和通用数据分析能力的50多种工具。
自动分类股票和仓位,并进行智能角色分配:
与任何MCP客户端通用兼容:
引用您实际投资组合的对话启动器:
portfolio_first_look - 分析您的具体持仓trading_strategy_workshop - 根据您的投资组合组成定制market_analysis_session - 关注您跟踪的符号list_mcp_capabilities - 完整的功能指南在子进程隔离下执行自定义分析:
复杂的投资组合智能:
超越交易——适用于任何结构化数据:
专业级错误管理:
{
"status": "error",
"message": "人类可读的错误描述",
"error_type": "异常类型",
"metadata": {"context": "附加信息"}
}
# 克隆并设置
git clone <仓库>
cd alpaca-mcp-gold-standard
# 安装依赖
uv sync
# 配置环境
cp .env.example .env
# 使用您的Alpaca API凭证编辑.env
# 开发模式
uv run python main.py
# 带详细日志的调试模式
LOG_LEVEL=DEBUG uv run python main.py
# 生产模式使用Docker
docker build -t alpaca-mcp-gold .
docker run -p 8000:8000 --env-file .env alpaca-mcp-gold
# 运行所有测试并生成覆盖率报告
uv run pytest tests/ -v --cov=src --cov-report=term-missing
# 测试特定的金标准模式
uv run pytest tests/test_resource_mirrors.py -v # 资源镜像模式
uv run pytest tests/test_state_management.py -v # 状态管理
uv run pytest tests/test_integration.py -v # 完整工作流
添加到您的Claude配置:
{
"mcpServers": {
"alpaca-trading-gold": {
"command": "/path/to/uv",
"args": [
"--directory",
"/绝对路径/to/alpaca-mcp-gold-standard",
"run",
"python",
"main.py"
],
"env": {
"LOG_LEVEL": "INFO"
}
}
}
}
get_account_info_tool() - 实时账户状态及投资组合洞察get_positions_tool() - 持仓及自适应角色分类get_open_position_tool(symbol) - 特定仓位详情get_portfolio_summary_tool() - 全面分析及AI建议get_stock_quote_tool(symbol) - 实时报价及价差分析get_stock_trade_tool(symbol) - 最新交易信息get_stock_snapshot_tool(symbols) - 完整市场数据及波动性get_historical_bars_tool(symbol, timeframe) - 历史OHLCV数据place_market_order_tool(symbol, side, quantity) - 即时执行place_limit_order_tool(symbol, side, quantity, price) - 价格目标place_stop_loss_order_tool(symbol, side, quantity, stop_price) - 风险管理get_orders_tool(status, limit) - 订单历史及追踪cancel_order_tool(order_id) - 订单取消execute_custom_trading_strategy_tool(code, symbols) - 运行自定义算法execute_portfolio_optimization_strategy_tool(code, risk_tolerance) - 优化持仓execute_risk_analysis_strategy_tool(code, benchmarks) - 风险分析generate_portfolio_health_assessment_tool() - 100分健康评分generate_advanced_market_correlation_analysis_tool(symbols) - 相关矩阵execute_custom_analytics_code_tool(dataset, code) - 任意数据集分析create_sample_dataset_from_portfolio_tool() - 将投资组合转换为数据集每个资源都有一个对应的工具以确保通用兼容性:
resource_account_info_tool() → trading://account/inforesource_portfolio_summary_tool() → trading://portfolio/summaryclear_portfolio_state_tool() - 重置状态用于测试src/mcp_server/
├── config/ # 基于环境的配置
│ ├── settings.py # Pydantic设置管理
│ └── simple_settings.py # 简化的配置加载器
├── models/ # 核心业务逻辑
│ ├── schemas.py # 实体分类及状态管理
│ └── alpaca_clients.py # 单例API客户端管理
├── tools/ # 按类别划分的31个MCP工具
│ ├── account_tools.py # 账户操作
│ ├── market_data_tools.py # 市场数据访问
│ ├── order_management_tools.py # 交易操作
│ ├── custom_strategy_execution.py # 安全代码执行
│ ├── advanced_analysis_tools.py # 投资组合分析
│ ├── execute_custom_analytics_code_tool.py # 通用分析
│ └── resource_mirror_tools.py # 兼容层
├── resources/ # 基于URI的数据访问
│ └── trading_resources.py # trading://方案处理器
├── prompts/ # 上下文感知对话
│ └── trading_prompts.py # 4个自适应提示生成器
└── server.py # FastMCP注册(31个工具)
tests/
├── conftest.py # 模拟Alpaca API及固定装置
├── test_account_tools.py # 账户操作测试
├── test_market_data_tools.py # 市场数据测试
├── test_order_management_tools.py # 订单操作测试
├── test_resources.py # 资源URI测试
├── test_resource_mirrors.py # 镜像一致性验证
├── test_state_management.py # 内存及状态测试
└── test_integration.py # 完整工作流测试
每个股票/仓位都被智能分类:
entity = EntityInfo(
symbol="AAPL",
suggested_role=EntityRole.GROWTH_CANDIDATE,
characteristics=["high_momentum", "tech_sector", "large_cap"],
confidence_score=0.85
)
# 自动清理和跟踪
StateManager.add_symbol("AAPL", entity_info)
memory_usage = StateManager.get_memory_usage() # 返回已使用的MB数
StateManager.clear_all() # 清空
# 带超时的安全执行
async def execute_custom_code(code: str) -> str:
process = await asyncio.create_subprocess_exec(
'uv', 'run', '--with', 'pandas', '--with', 'numpy',
'python', '-c', execution_code,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT
)
stdout, _ = await asyncio.wait_for(process.communicate(), timeout=30)
# 基于实际持仓的上下文感知建议
"您的投资组合显示科技股高度集中(65%)。考虑通过医疗保健或消费品来分散风险,以获得更好的风险平衡。使用get_stock_snapshot('JNJ,PG,KO')来研究防御性位置。"
tools/category_tools.py中创建函数async def your_new_tool(param: str) -> Dict[str, Any]:
try:
# 实现
return {
"status": "success",
"data": result_data,
"metadata": {"operation": "your_new_tool"}
}
except Exception as e:
return {
"status": "error",
"message": str(e),
"error_type": type(e).__name__
}
server.py中使用@mcp.tool()装饰器注册# 格式化代码
uv run black src/ tests/
# 代码检查
uv run ruff check src/ tests/
# 类型检查
uv run mypy src/
# 运行所有质量检查
uv run black src/ tests/ && uv run ruff check src/ tests/ && uv run mypy src/
alpaca_py_sdk_reference.md - Alpaca SDK指南mcp_server_sdk_reference.md - MCP模式指南architecture_overview.md - 金标准模式custom_analytic_code.md - 子进程设计poc_init_generic.md - 通用模式resource_workaround.md - 镜像模式# 构建生产镜像
docker build -t alpaca-mcp-gold .
# 使用环境文件运行
docker run -d \
--name alpaca-mcp \
-p 8000:8000 \
--env-file .env \
--restart unless-stopped \
alpaca-mcp-gold
# 必需
ALPACA_API_KEY=your_api_key
ALPACA_SECRET_KEY=your_secret_key
# 可选
ALPACA_PAPER_TRADE=True # 使用模拟交易(推荐)
LOG_LEVEL=INFO # 日志详细程度
MCP_SERVER_NAME=alpaca-trading-gold
该项目作为MCP开发的金标准参考。当贡献时:
这不仅仅是另一个MCP服务器——它是软件架构的大师课:
架构设计为扩展:
本项目根据原始Alpaca MCP服务器的相同条款许可。
基于原始Alpaca MCP服务器的基础,实现了父存储库分析中记录的全面最佳实践。特别感谢MCP和Alpaca社区提供的优秀文档和工具。
这是专业MCP开发的权威参考实现。 不论您是在构建交易系统、数据分析平台还是任何其他MCP驱动的应用程序,这个代码库都展示了引领生产就绪、可维护和可扩展系统的模式和实践。