A server for interacting with the Alpaca trading API. Requires API credentials via environment variables.
A comprehensive implementation of the definitive MCP (Model Context Protocol) server architecture for professional trading operations, achieving 100% compliance with gold standard patterns documented in the Quick Data MCP reference architecture.
This implementation represents the definitive reference for professional MCP development, implementing all 7 core architectural patterns with 50+ tools spanning trading operations, advanced analytics, and universal data analysis capabilities.
Automatically classifies stocks and positions with intelligent role assignment:
Universal compatibility with ANY MCP client:
Conversation starters that reference your actual portfolio:
portfolio_first_look
- Analyzes your specific holdingstrading_strategy_workshop
- Customized to your portfolio compositionmarket_analysis_session
- Focused on your tracked symbolslist_mcp_capabilities
- Complete feature guideExecute custom analysis with subprocess isolation:
Sophisticated portfolio intelligence:
Beyond trading - works with ANY structured data:
Professional-grade error management:
{
"status": "error",
"message": "Human-readable error description",
"error_type": "ExceptionType",
"metadata": {"context": "additional_info"}
}
# Clone and setup
git clone <repository>
cd alpaca-mcp-gold-standard
# Install dependencies
uv sync
# Configure environment
cp .env.example .env
# Edit .env with your Alpaca API credentials
# Development mode
uv run python main.py
# Debug mode with verbose logging
LOG_LEVEL=DEBUG uv run python main.py
# Production mode with Docker
docker build -t alpaca-mcp-gold .
docker run -p 8000:8000 --env-file .env alpaca-mcp-gold
# Run all tests with coverage
uv run pytest tests/ -v --cov=src --cov-report=term-missing
# Test specific gold standard patterns
uv run pytest tests/test_resource_mirrors.py -v # Resource mirror pattern
uv run pytest tests/test_state_management.py -v # State management
uv run pytest tests/test_integration.py -v # Full workflows
Add to your Claude configuration:
{
"mcpServers": {
"alpaca-trading-gold": {
"command": "/path/to/uv",
"args": [
"--directory",
"/absolute/path/to/alpaca-mcp-gold-standard",
"run",
"python",
"main.py"
],
"env": {
"LOG_LEVEL": "INFO"
}
}
}
}
get_account_info_tool()
- Real-time account status with portfolio insightsget_positions_tool()
- Holdings with adaptive role classificationget_open_position_tool(symbol)
- Specific position detailsget_portfolio_summary_tool()
- Comprehensive analysis with AI suggestionsget_stock_quote_tool(symbol)
- Real-time quotes with spread analysisget_stock_trade_tool(symbol)
- Latest trade informationget_stock_snapshot_tool(symbols)
- Complete market data with volatilityget_historical_bars_tool(symbol, timeframe)
- Historical OHLCV dataplace_market_order_tool(symbol, side, quantity)
- Immediate executionplace_limit_order_tool(symbol, side, quantity, price)
- Price targetingplace_stop_loss_order_tool(symbol, side, quantity, stop_price)
- Risk managementget_orders_tool(status, limit)
- Order history and trackingcancel_order_tool(order_id)
- Order cancellationexecute_custom_trading_strategy_tool(code, symbols)
- Run custom algorithmsexecute_portfolio_optimization_strategy_tool(code, risk_tolerance)
- Optimize holdingsexecute_risk_analysis_strategy_tool(code, benchmarks)
- Risk analyticsgenerate_portfolio_health_assessment_tool()
- 100-point health scoringgenerate_advanced_market_correlation_analysis_tool(symbols)
- Correlation matricesexecute_custom_analytics_code_tool(dataset, code)
- Any dataset analysiscreate_sample_dataset_from_portfolio_tool()
- Convert portfolio to datasetEvery resource has a corresponding tool for universal compatibility:
resource_account_info_tool()
โ trading://account/info
resource_portfolio_summary_tool()
โ trading://portfolio/summary
clear_portfolio_state_tool()
- Reset state for testingsrc/mcp_server/
โโโ config/ # Environment-based configuration
โ โโโ settings.py # Pydantic settings management
โ โโโ simple_settings.py # Simplified config loader
โโโ models/ # Core business logic
โ โโโ schemas.py # Entity classification & state management
โ โโโ alpaca_clients.py # Singleton API client management
โโโ tools/ # 31 MCP tools by category
โ โโโ account_tools.py # Account operations
โ โโโ market_data_tools.py # Market data access
โ โโโ order_management_tools.py # Trading operations
โ โโโ custom_strategy_execution.py # Safe code execution
โ โโโ advanced_analysis_tools.py # Portfolio analytics
โ โโโ execute_custom_analytics_code_tool.py # Universal analytics
โ โโโ resource_mirror_tools.py # Compatibility layer
โโโ resources/ # URI-based data access
โ โโโ trading_resources.py # trading:// scheme handlers
โโโ prompts/ # Context-aware conversations
โ โโโ trading_prompts.py # 4 adaptive prompt generators
โโโ server.py # FastMCP registration (31 tools)
tests/
โโโ conftest.py # Mock Alpaca API & fixtures
โโโ test_account_tools.py # Account operation tests
โโโ test_market_data_tools.py # Market data tests
โโโ test_order_management_tools.py # Order operation tests
โโโ test_resources.py # Resource URI tests
โโโ test_resource_mirrors.py # Mirror consistency validation
โโโ test_state_management.py # Memory & state tests
โโโ test_integration.py # Complete workflow tests
Every stock/position is intelligently classified:
entity = EntityInfo(
symbol="AAPL",
suggested_role=EntityRole.GROWTH_CANDIDATE,
characteristics=["high_momentum", "tech_sector", "large_cap"],
confidence_score=0.85
)
# Automatic cleanup and tracking
StateManager.add_symbol("AAPL", entity_info)
memory_usage = StateManager.get_memory_usage() # Returns MB used
StateManager.clear_all() # Clean slate
# Safe execution with timeout
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)
# Context-aware suggestions based on actual holdings
"Your portfolio shows high concentration in tech stocks (65%).
Consider diversifying with healthcare or consumer staples for
better risk balance. Use get_stock_snapshot('JNJ,PG,KO') to
research defensive positions."
tools/category_tools.py
async def your_new_tool(param: str) -> Dict[str, Any]:
try:
# Implementation
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
with @mcp.tool()
decorator# Format code
uv run black src/ tests/
# Lint code
uv run ruff check src/ tests/
# Type checking
uv run mypy src/
# Run all quality checks
uv run black src/ tests/ && uv run ruff check src/ tests/ && uv run mypy src/
alpaca_py_sdk_reference.md
- Alpaca SDK guidemcp_server_sdk_reference.md
- MCP patterns guidearchitecture_overview.md
- Gold standard patternscustom_analytic_code.md
- Subprocess designpoc_init_generic.md
- Universal patternsresource_workaround.md
- Mirror pattern# Build production image
docker build -t alpaca-mcp-gold .
# Run with environment file
docker run -d \
--name alpaca-mcp \
-p 8000:8000 \
--env-file .env \
--restart unless-stopped \
alpaca-mcp-gold
# Required
ALPACA_API_KEY=your_api_key
ALPACA_SECRET_KEY=your_secret_key
# Optional
ALPACA_PAPER_TRADE=True # Use paper trading (recommended)
LOG_LEVEL=INFO # Logging verbosity
MCP_SERVER_NAME=alpaca-trading-gold
This project serves as the gold standard reference for MCP development. When contributing:
This is not just another MCP server - it's a masterclass in software architecture:
The architecture is designed for expansion:
This project is licensed under the same terms as the original Alpaca MCP server.
Built upon the foundation of the original Alpaca MCP server, implementing the comprehensive best practices documented in the parent repository's analysis of gold standard MCP patterns. Special thanks to the MCP and Alpaca communities for their excellent documentation and tools.
This is the definitive reference implementation for professional MCP development. Whether you're building trading systems, data analytics platforms, or any other MCP-powered application, this codebase demonstrates the patterns and practices that lead to production-ready, maintainable, and extensible systems.
Interact with Honeycomb observability data using the Model Context Protocol.
A remote MCP server deployable on Cloudflare Workers without authentication.
Query OpenAI models directly from Claude using MCP protocol
Access weather station data, observations, and forecasts using the WeatherXM PRO API.
An example project for deploying a remote MCP server on Cloudflare Workers without authentication.
Backs up Cloudflare projects to a specified GitHub repository.
An MCP server for accessing YouTube Analytics data, powered by the CData JDBC Driver.
A security-focused MCP server for performing safe operations on an Ubuntu system, featuring robust security controls and audit logging.
An MCP server deployed on Cloudflare Workers, featuring OAuth login and data storage via Cloudflare KV.
An MCP server for processing payments using stdio transport, configured via environment variables.