alpaka-mcp
¿Qué es esto?
alpaka-mcp es un servidor MCP + CLI listo para producción que conecta asistentes de IA (Claude Desktop, Cursor, VS Code Copilot) y tu terminal directamente a la API de Trading de Alpaca. Opera con acciones, ETFs y criptomonedas mediante lenguaje natural — o desde la línea de comandos.
Construido sobre alpaca-py y el SDK de Python para MCP.
Por defecto usa paper trading — datos reales del mercado, fondos simulados, cero dinero real en riesgo.
Related MCP server: FinClaw
Inicio rápido
1. Obtén tus claves de API de Alpaca (gratis)
Regístrate en alpaca.markets → Paper Trading → Claves de API
2. Instalación
git clone https://github.com/vikrambtech2025-png/alpaka-mcp.git
cd alpaka-mcp
uv sync3. Configuración
cp .env.example .env
# Add your API keys to .env4. Ejecución
uv run alpaka-mcp # MCP server (stdio for Claude/Cursor)
uv run alpaka account # CLI — check account
uv run mcp dev src/alpaka_mcp/server.py # MCP InspectorConectar con asistentes de IA
Añade a %AppData%\Claude\claude_desktop_config.json:
{
"mcpServers": {
"alpaka": {
"command": "uv",
"args": ["--directory", "C:\\path\\to\\alpaka-mcp", "run", "alpaka-mcp"],
"env": {
"ALPACA_API_KEY": "your_key",
"ALPACA_SECRET_KEY": "your_secret",
"ALPACA_PAPER": "true"
}
}
}
}Añade a .cursor/mcp.json en la raíz de tu proyecto:
{
"mcpServers": {
"alpaka": {
"command": "uv",
"args": ["--directory", "/path/to/alpaka-mcp", "run", "alpaka-mcp"],
"env": {
"ALPACA_API_KEY": "your_key",
"ALPACA_SECRET_KEY": "your_secret",
"ALPACA_PAPER": "true"
}
}
}
}Añade a .vscode/mcp.json:
{
"servers": {
"alpaka": {
"command": "uv",
"args": ["--directory", "/path/to/alpaka-mcp", "run", "alpaka-mcp"],
"env": {
"ALPACA_API_KEY": "your_key",
"ALPACA_SECRET_KEY": "your_secret",
"ALPACA_PAPER": "true"
}
}
}
}Herramientas MCP (16)
Herramienta | Descripción |
| Saldo, patrimonio, poder de compra, operaciones intradía |
| Todas las posiciones abiertas con P&L |
Herramienta | Descripción |
| Realiza una orden de compra (mercado/límite/stop/stop-límite) |
| Realiza una orden de venta (mercado/límite) |
| Lista órdenes por estado y símbolos |
| Cancela una orden específica |
| Cancela todas las órdenes abiertas |
Herramienta | Descripción |
| Detalles de una sola posición |
| Liquida (total o parcial) |
Herramienta | Descripción |
| Última cotización bid/ask |
| Barras OHLCV históricas |
| Instantánea completa (operación, cotización, diario, 1 min) |
Herramienta | Descripción |
| Último bid/ask de cripto |
| Barras OHLCV históricas de cripto |
Herramienta | Descripción |
| Busca acciones/ETFs/cripto por nombre o símbolo |
| Estado de apertura/cierre del mercado |
Comandos CLI (12)
alpaka account # Account balance & buying power
alpaka portfolio # Open positions with color-coded P&L
alpaka quote AAPL # Bid/ask quote (stocks or crypto)
alpaka buy AAPL --qty 10 # Buy 10 shares
alpaka buy BTC/USD -n 500 # Buy $500 of Bitcoin
alpaka sell AAPL --qty 5 # Sell 5 shares
alpaka orders # List open orders
alpaka orders --status closed # List filled orders
alpaka cancel <order-id> # Cancel specific order
alpaka cancel-all # Cancel everything open
alpaka bars AAPL --tf 1Day # Historical bars
alpaka clock # Is the market open?
alpaka search apple # Find tradeable assetsTodos los comandos admiten --json para una salida legible por máquina:
$ uv run alpaka account --json
{
"status": "ACTIVE",
"equity": "100000.00",
"buying_power": "200000.00",
"cash": "100000.00",
"portfolio_value": "100000.00",
"daytrade_count": 0,
"pattern_day_trader": false,
"mode": "paper"
}Características de producción
Característica | Cómo funciona |
Cliente resiliente | Un proxy transparente envuelve cada llamada a la API con limitación de frecuencia y reintentos |
Limitación de frecuencia | 3 cubos de tokens independientes (200 solicitudes/min cada uno) — trading, datos de acciones, cripto |
Reintentos + retroceso exponencial | 3 intentos con retroceso exponencial de 1s/2s/4s ante errores 429, 500 y de conexión |
Async sin bloqueo | Las herramientas MCP usan |
Registro estructurado | Rastro de auditoría JSON: |
Validación de entrada | Símbolos, cantidades, precios y tipos de orden validados antes de las llamadas a la API |
Protección de trading en vivo | Requiere |
Validación de configuración | Rechaza claves de API de ejemplo con instrucciones claras de configuración |
Seguridad de subprocesos | Inicialización de cliente con |
Gestión de errores CLI | Cada comando envuelto — errores limpios, sin tracebacks |
Arquitectura
src/alpaka_mcp/
├── server.py # MCP server entry point (stdio)
├── cli.py # 12 Typer commands + JSON output
├── config.py # pydantic-settings + credential validation
├── clients.py # ResilientClient proxy (rate limit + retry + async)
├── utils.py # Response formatting
├── logging.py # Structured JSON logging
├── rate_limiter.py # Token bucket rate limiters (sync + async)
├── retry.py # Exponential backoff (sync + async)
├── validation.py # Input validation
└── tools/ # 16 MCP tools
├── account.py # get_account, get_portfolio
├── trading.py # buy, sell, get_orders, cancel_order, cancel_all
├── positions.py # get_position, close_position
├── stock_data.py # get_stock_quote, get_stock_bars, get_stock_snapshot
├── crypto_data.py # get_crypto_quote, get_crypto_bars
└── discovery.py # search_assets, get_market_clockDocker
# MCP server
docker compose up alpaka-mcp
# CLI via docker
docker compose run --rm alpaka-cli account
docker compose run --rm alpaka-cli portfolioLos registros persisten en un volumen de Docker en /app/logs.
Variables de entorno
Variable | Por defecto | Descripción |
| (obligatoria) | Tu clave de API de Alpaca |
| (obligatoria) | Tu clave secreta de Alpaca |
|
| Modo paper trading |
|
| Debe ser |
|
| Directorio de archivos de registro |
|
| Verbosidad del registro |
Pruebas
# Unit tests (no API keys needed)
uv run pytest tests/ --ignore=tests/test_integration.py -v
# Integration tests (needs real paper API keys)
ALPACA_API_KEY=pk_xxx ALPACA_SECRET_KEY=sk_xxx uv run pytest tests/test_integration.py -vSeguridad
Paper trading por defecto — el dinero real requiere aceptación explícita
El trading en vivo requiere tanto
ALPACA_PAPER=falsecomoALPACA_LIVE_CONFIRM=trueCuenta atrás de 5 segundos al iniciar el trading en vivo
Todos los errores se formatean limpiamente — no se envían tracebacks a los LLMs
La limitación de frecuencia previene el uso indebido accidental de la API
Rastro de auditoría estructurado para cada operación
Licencia
MIT
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseDqualityDmaintenanceMCP server that exposes Alpaca Market Data & Broker API as tools, enabling access to financial data like stock bars, assets, market days, and news through the Message Control Protocol.4542ISC
- AlicenseNot gradedqualityDmaintenanceMCP server that provides AI agents with financial tools including real-time quotes, backtesting, technical analysis, and multi-exchange data via a simple CLI interface.1MIT
- AlicenseNot gradedqualityDmaintenanceAn MCP server implementation for Alpaca's Trading API that enables LLMs to interact with Alpaca's trading infrastructure using natural language, supporting stock, options, and crypto trading, portfolio management, watchlists, and market data.4MIT
- AlicenseAqualityAmaintenanceThis MCP server connects AI assistants to a Public.com brokerage account, enabling natural language trading of stocks, options, and crypto, along with portfolio management, quotes, and orders.3765Apache 2.0
Related MCP Connectors
MCP server for Gainium — manage trading bots, deals, and balances via AI assistants
MCP server exposing the Backtest360 engine API as tools for AI agents.
Alpaca MCP — real-time US stock market data via the Alpaca Market Data API
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/vikrambtech2025-png/alpaka-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server