Sandbox
@alpacahq/alpaca-mcp-server

Alpaca MCP server for trading and market data

This server exposes Alpaca Trading API and market data tools through MCP so an assistant can act on your account, orders, positions, watchlists, and market queries. It is built from OpenAPI specs with a FastMCP server, toolset filtering, and read-only documentation lookup tools.

955 stars306 forksPythonUpdated 13d ago
Who it's for

Builders who want their agent or IDE to query Alpaca, place trades, and inspect portfolio or market data without leaving chat.

What it delivers

You can trade, check positions, and analyze market data from your agent instead of switching to Alpaca’s web app.

What it does

Trading and order management

Place, replace, and cancel stock, crypto, and option orders, including bracket and trailing-stop orders.

Portfolio and account tools

Read account balances, buying power, account settings, portfolio history, activities, and open positions.

Market data tools

Fetch stock, crypto, and options bars, quotes, trades, snapshots, latest prices, and order books.

Watchlists and assets

Create and update watchlists and look up assets, option contracts, calendar data, and market clock status.

Documentation lookup

Search and fetch Alpaca docs and API specs from the server when a tool needs reference material.

Toolset filtering

Limit the exposed tools with `ALPACA_TOOLSETS` so the assistant only sees the capabilities you want.

How to get it

  1. 1Set environment variables
    ALPACA_API_KEY=your_alpaca_api_key
     ALPACA_SECRET_KEY=your_alpaca_secret_key
  2. 2Run
    claude mcp add alpaca --scope user --transport stdio uvx alpaca-mcp-server \
      --env ALPACA_API_KEY=your_alpaca_api_key \
      --env ALPACA_SECRET_KEY=your_alpaca_secret_key
  3. 3Run
    git clone https://github.com/alpacahq/alpaca-mcp-server.git
    cd alpaca-mcp-server
    docker build -t mcp/alpaca:latest .

README

Alpaca logo

X Reddit Slack LinkedIn Forum Docs Python SDK

A comprehensive Model Context Protocol (MCP) server for Alpaca's Trading API. Enable natural language trading operations through AI assistants like Claude, Cursor, and VS Code. Supports stocks, options, crypto, portfolio management, and real-time market data.

Alpaca MCP Server v2 is here. This version is a complete rewrite built with FastMCP and OpenAPI. If you're upgrading from v1, please read the Upgrade Guide — tool names, parameters, and configuration have changed.

Table of Contents


Upgrading from V1

V2 is a complete rewrite built with FastMCP and OpenAPI. None of the V1 tools exist in V2 — tool names, parameters, and schemas have changed. You cannot use V2 as a drop-in replacement if your setup depends on specific V1 tool names or parameters.

What changes

AspectV1V2
Tool namesHand-crafted (e.g. get_account_info)Spec-derived with overrides (e.g. get_account_info — names may overlap but schemas differ)
ParametersCustom schemasAligned with Alpaca API specs
Configuration.env + init commandEnv vars in MCP client config only
Tool filteringNot supportedALPACA_TOOLSETS env var
WhitelistingNot supportedUse ALPACA_TOOLSETS to restrict tools

How to avoid V1-style usage in V2

MCP clients discover tools dynamically from the server. There is no config file where you "whitelist" tool names — the client gets whatever tools the server exposes. To avoid your client or AI assistant using V2 incorrectly:

  1. Do not reuse V1 config — Treat V2 as a new server. Update your MCP client config with the new command/args; remove any .env or init-based setup.
  2. Clear tool caches — Restart your MCP client (Claude Desktop, Cursor, VS Code, etc.) after switching so it fetches the new tool list instead of using a stale one.
  3. Start a fresh chat/session — Existing conversations may have cached references to old tool names. Start a new chat so the LLM sees the current V2 tools and their schemas.
  4. Update custom instructions and rules — If you have Cursor rules, Claude instructions, or other prompts that mention specific V1 tool names (e.g. "use get_account_info"), update them to match V2 tool names or remove those references and let the LLM discover tools from context.
  5. Restrict tools with ALPACA_TOOLSETS — If you previously limited which capabilities your assistant could use, V2 supports server-side filtering via the ALPACA_TOOLSETS env var. See Configuration > Toolset Filtering for the list of toolsets.

Summary

Assume no backward compatibility with V1. Reconfigure your MCP client for V2, restart it, and use a fresh session. Check the Available Tools section for the current tool list.

If you had custom V1 workflows

If you documented allowed tools, wrote scripts that call tools by name, or built prompts around specific V1 tool/parameter shapes — treat them as obsolete. Recreate them using the Available Tools listed below and the current parameter schemas exposed by the server.

Staying on V1

If you need to stay on V1, pin to the last V1 release (e.g. uvx alpaca-mcp-server==1.x.x serve) in your MCP client config. V1 remains available on PyPI for existing setups.


Prerequisites

Getting Your API Keys

  1. Visit the Alpaca Dashboard
  2. Create a free paper trading account
  3. Generate API keys from the dashboard

Setup

Add the server to your MCP client config, then restart the client. No init command, no .env files — credentials are set in one place only.

Claude Desktop

Edit ~/Library/Application Support/Claude/claude_desktop_config.json (Mac) or %APPDATA%\Claude\claude_desktop_config.json (Windows):

{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": ["alpaca-mcp-server"],
      "env": {
        "ALPACA_API_KEY": "your_alpaca_api_key",
        "ALPACA_SECRET_KEY": "your_alpaca_secret_key"
      }
    }
  }
}

Claude Mobile

Alpaca does not provide a hosted remote MCP server. To use the MCP server on the Claude mobile app, host it remotely on a cloud provider, then add it as a custom connector in Claude. The connector syncs to the mobile app once connected on the web.

For hosting, deployment, and connector setup, see How to Deploy Alpaca's MCP Server Remotely on Claude Mobile App.

ChatGPT

Alpaca does not provide a hosted remote MCP server. To use the MCP server in ChatGPT, host it remotely on a cloud provider, then add it as a connector.

See Connectors in ChatGPT and the Claude Mobile deployment guide for hosting and setup steps.

Cursor

Install from the Cursor Directory in a few clicks, or add to ~/.cursor/mcp.json:

{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": ["alpaca-mcp-server"],
      "env": {
        "ALPACA_API_KEY": "your_alpaca_api_key",
        "ALPACA_SECRET_KEY": "your_alpaca_secret_key"
      }
    }
  }
}

VS Code

Create .vscode/mcp.json in your project root. See the official docs.

{
  "servers": {
    "alpaca": {
      "type": "stdio",
      "command": "uvx",
      "args": ["alpaca-mcp-server"],
      "env": {
        "ALPACA_API_KEY": "your_alpaca_api_key",
        "ALPACA_SECRET_KEY": "your_alpaca_secret_key"
      }
    }
  }
}

PyCharm

See the official guide.

  1. Go to File → Settings → Tools → Model Context Protocol (MCP)
  2. Add a new server:
  • Type: stdio
  • Command: uvx
  • Arguments: alpaca-mcp-server
  1. Set environment variables:
 ALPACA_API_KEY=your_alpaca_api_key
 ALPACA_SECRET_KEY=your_alpaca_secret_key

Claude Code

claude mcp add alpaca --scope user --transport stdio uvx alpaca-mcp-server \
  --env ALPACA_API_KEY=your_alpaca_api_key \
  --env ALPACA_SECRET_KEY=your_alpaca_secret_key

Verify with /mcp in the Claude Code CLI.

Antigravity CLI

See the Antigravity MCP docs.

Add to ~/.gemini/antigravity-cli/mcp_config.json (global) or .agents/mcp_config.json (workspace):

{
  "mcpServers": {
    "alpaca": {
      "command": "uvx",
      "args": ["alpaca-mcp-server"],
      "env": {
        "ALPACA_API_KEY": "your_alpaca_api_key",
        "ALPACA_SECRET_KEY": "your_alpaca_secret_key"
      }
    }
  }
}

Docker

git clone https://github.com/alpacahq/alpaca-mcp-server.git
cd alpaca-mcp-server
docker build -t mcp/alpaca:latest .

Add to your MCP client config:

{
  "mcpServers": {
    "alpaca": {
      "command": "docker",
      "args": [
        "run", "--rm", "-i",
        "-e", "ALPACA_API_KEY=your_key",
        "-e", "ALPACA_SECRET_KEY=your_secret",
        "-e", "ALPACA_PAPER_TRADE=true",
        "mcp/alpaca:latest"
      ]
    }
  }
}

Configuration

All configuration is through environment variables set in your MCP client config. No files are written to disk.

VariableRequiredDefaultDescription
ALPACA_API_KEYYesYour Alpaca API key
ALPACA_SECRET_KEYYesYour Alpaca secret key
ALPACA_PAPER_TRADENotrueSet to false for live trading
ALPACA_TOOLSETSNoallComma-separated list of toolsets to enable

Switching to Live Trading

Update the env block in your MCP client config and restart:

{
  "env": {
    "ALPACA_API_KEY": "your_live_api_key",
    "ALPACA_SECRET_KEY": "your_live_secret_key",
    "ALPACA_PAPER_TRADE": "false"
  }
}

Toolset Filtering

By default, all tools are enabled. To limit the server to specific toolsets, set ALPACA_TOOLSETS:

{
  "env": {
    "ALPACA_API_KEY": "...",
    "ALPACA_SECRET_KEY": "...",
    "ALPACA_TOOLSETS": "stock-data,crypto-data"
  }
}

Available toolsets:

ToolsetDescription
accountAccount info, config, portfolio history, activities
tradingOrders, positions, exercise options
watchlistsWatchlist CRUD operations
assetsAsset lookup, option contracts, calendar, clock
stock-dataStock bars, quotes, trades, snapshots, screeners
crypto-dataCrypto bars, quotes, trades, snapshots, orderbooks
options-dataOption bars, quotes, trades, snapshots, chain, exchange codes
corporate-actionsCorporate action announcements
newsNews articles for stocks and crypto
fixed-income-dataFixed income (bond/treasury) quotes
locatesShort-sale locate requests and quotes

ReadMe Docs MCP

Docs are scoped to the Trading API, Market Data API, and Authentication API specs; Broker API endpoint docs are intentionally excluded from this server.

If the ReadMe MCP lookup fails, tool responses include fallback links to Alpaca's public docs plus llms.txt and llms-full.txt.

Features

  • Market Data — Real-time quotes, trades, and price bars for stocks, crypto, and options. Historical data with flexible timeframes. Option Greeks and implied volatility.
  • Account Management — View balances, buying power, account status, and portfolio history.
  • Order Management — Place market, limit, stop, stop-limit, and trailing-stop orders for stocks, crypto, and options. Cancel orders individually or in bulk.
  • Options Trading — Search contracts by expiration/strike/type. Place single-leg or multi-leg strategies. Get latest quotes, Greeks, and IV.
  • Crypto Trading — Market, limit, and stop-limit orders with GTC/IOC. Quantity or notional-based.
  • Position Management — View, close, or liquidate positions. Exercise option contracts.
  • News — News articles filterable by ticker and date range.
  • Market Status — Market open/close times, calendar, corporate actions.
  • Watchlists — Create, update, and manage watchlists.
  • Asset Search — Query details for stocks, ETFs, crypto, and options with filtering.

Example Prompts

Basic Trading

  1. What's my current account balance and buying power on Alpaca?
  2. Show me my current positions in my Alpaca account.
  3. Buy 5 shares of AAPL at market price.
  4. Sell 5 shares of TSLA with a limit price of $300.
  5. Cancel all open stock orders.
  6. Cancel the order with ID abc123.
  7. Liquidate my entire position in GOOGL.
  8. Close 10% of my position in NVDA.
  9. Place a limit order to buy 100 shares of MSFT at $450.
  10. Place a market order to sell 25 shares of META.

Crypto Trading

  1. Place a market order to buy 0.01 ETH/USD.
  2. Place a limit order to sell 0.01 BTC/USD at $110,000.

Option Trading

  1. Show me available option contracts for AAPL expiring next month.
  2. Get the latest quote for the AAPL250613C00200000 option.
  3. Retrieve the option snapshot for the SPY250627P00400000 option.
  4. Liquidate my position in 2 contracts of QQQ calls expiring next week.
  5. Place a market order to buy 1 call option on AAPL expiring next Friday.
  6. What are the option Greeks for the TSLA250620P00500000 option?
  7. Find TSLA option contracts with strike prices within 5% of the current market price.
  8. Get SPY call options expiring the week of June 16th, 2025, within 10% of market price.
  9. Place a bull call spread using AAPL June 6th options: one with a 190.00 strike and the other with a 200.00 strike.
  10. Exercise my NVDA call option contract NVDA250919C001680.

Market Information

To access the latest 15-minute data, you need to subscribe to the Algo Trader Plus Plan.

  1. What are the market open and close times today?
  2. Show me the market calendar for next week.
  3. Show me recent cash dividends and stock splits for AAPL, MSFT, and GOOGL in the last 3 months.
  4. Get all corporate actions for SPY including dividends, splits, and any mergers in the past year.
  5. What are the upcoming corporate actions scheduled for SPY in the next 6 months?

Historical & Real-time Data

  1. Show me AAPL's daily price history for the last 5 trading days.
  2. What was the closing price of TSLA yesterday?
  3. Get the latest bar for GOOGL.
  4. What was the latest trade price for NVDA?
  5. Show me the most recent quote for MSFT.
  6. Retrieve the last 100 trades for AMD.
  7. Show me 1-minute bars for AMZN from the last 2 hours.
  8. Get 5-minute intraday bars for TSLA from last Tuesday through last Friday.
  9. Get a comprehensive stock snapshot for AAPL showing latest quote, trade, minute bar, daily bar, and previous daily bar all in one view.
  10. Compare market snapshots for TSLA, NVDA, and MSFT to analyze their current bid/ask spreads, latest trade prices, and daily performance.

Orders

  1. Show me all my open and filled orders from this week.
  2. What orders do I have for AAPL?
  3. List all limit orders I placed in the past 3 days.
  4. Filter all orders by status: filled.
  5. Get me the order history for yesterday.

Watchlists

At this moment, you can only view and update trading watchlists created via Alpaca's Trading API through the API itself

  1. Create a new watchlist called "Tech Stocks" with AAPL, MSFT, and NVDA.
  2. Update my "Tech Stocks" watchlist to include TSLA and AMZN.
  3. What stocks are in my "Dividend Picks" watchlist?
  4. Remove META from my "Growth Portfolio" watchlist.
  5. List all my existing watchlists.

Asset Information

  1. Search for details about the asset 'AAPL'.
  2. Show me the top 5 tradable crypto assets by trading volume.
  3. Get all NASDAQ active US equity assets and filter the results to show only tradable securities

Combined Scenarios

  1. Get today's market clock and show me my buying power before placing a limit buy order for TSLA at $340.
  2. Place a bull call spread with SPY July 3rd options: sell one 5% above and buy one 3% below the current SPY price.

Available Tools

Account & Portfolio

  • get_account_info — Balance, margin, and account status
  • get_account_config — Trading restrictions, margin settings, PDT checks
  • update_account_config — Update account configuration settings
  • get_portfolio_history — Equity and P/L over time
  • get_account_activities — Fills, dividends, transfers
  • get_account_activities_by_type — Activities filtered by type

Trading (Orders)

  • get_orders — Retrieve orders with filters
  • get_order_by_id — Single order by ID
  • get_order_by_client_id — Single order by client order ID
  • replace_order_by_id — Replace an existing open order
  • cancel_order_by_id — Cancel a specific order
  • cancel_all_orders — Cancel all open orders
  • place_stock_order — Stocks/ETFs (market, limit, stop, stop-limit, trailing-stop, brackets)
  • place_crypto_order — Crypto (market, limit, stop-limit)
  • place_option_order — Options (single-leg or multi-leg)

Positions

  • get_all_positions — All current positions
  • get_open_position — Details for a specific position
  • close_position — Close a specific position
  • close_all_positions — Liquidate entire portfolio
  • exercise_options_position — Exercise a held option contract
  • do_not_exercise_options_position — Do-not-exercise instruction

Watchlists

  • create_watchlist — Create a new watchlist
  • get_watchlists — List all watchlists
  • get_watchlist_by_id — Get a specific watchlist
  • update_watchlist_by_id — Update a watchlist
  • delete_watchlist_by_id — Delete a watchlist
  • add_asset_to_watchlist_by_id — Add an asset to a watchlist
  • remove_asset_from_watchlist_by_id — Remove an asset from a watchlist

Assets & Market Info

  • get_all_assets — List assets with optional filtering
  • get_asset — Detailed info for a specific asset
  • get_option_contracts — Option contracts for underlying symbol(s)
  • get_option_contract — Single option contract by symbol or ID
  • get_calendar — Market calendar for a date range
  • get_clock — Current market status and next open/close
  • get_corporate_action_announcements — Corporate action announcements
  • get_corporate_action_announcement — Single announcement by ID

Stock Data

  • get_stock_bars — Historical OHLCV bars
  • get_stock_quotes — Historical bid/ask quotes
  • get_stock_trades — Historical trades
  • get_stock_latest_bar — Latest minute bar
  • get_stock_latest_quote — Latest quote
  • get_stock_latest_trade — Latest trade
  • get_stock_snapshot — Comprehensive snapshot
  • get_most_active_stocks — Most active by volume/trade count
  • get_market_movers — Top gainers and losers

Crypto Data

  • get_crypto_bars — Historical OHLCV bars
  • get_crypto_quotes — Historical quotes
  • get_crypto_trades — Historical trades
  • get_crypto_latest_bar — Latest minute bar
  • get_crypto_latest_quote — Latest quote
  • get_crypto_latest_trade — Latest trade
  • get_crypto_snapshot — Comprehensive snapshot
  • get_crypto_latest_orderbook — Latest orderbook

Options Data

  • get_option_bars — Historical OHLCV bars
  • get_option_trades — Historical trades
  • get_option_latest_trade — Latest trade
  • get_option_latest_quote — Latest quote with bid/ask and exchange info
  • get_option_snapshot — Snapshot with Greeks and IV
  • get_option_chain — Full option chain for an underlying
  • get_option_exchange_codes — Exchange code to name mapping

Corporate Actions

  • get_corporate_actions — Corporate action announcements from market data

News

  • get_news — News articles for stocks and crypto

Fixed Income Data

  • get_fixed_income_latest_quotes — Latest quotes for fixed income securities by ISIN

Locates (Short Selling)

  • get_locates — List locate requests filtered by status, symbol, or date range
  • create_locate — Create a locate request for a short sale
  • get_locate — Get a single locate request by ID
  • get_locate_quotes — Get locate availability and pricing for symbols

Documentation

  • search_alpaca_docs — Search Alpaca documentation pages and guides
  • fetch_alpaca_doc — Fetch one Alpaca ReadMe documentation page by page ID
  • search_alpaca_api_specs — Search Alpaca API reference endpoints by topic, path, parameter, or schema term
  • list_alpaca_api_endpoints — List endpoints for one allowed Alpaca OpenAPI spec
  • get_alpaca_endpoint_docs — Fetch reference docs for one exact Alpaca API endpoint by method and path

Testing

The project includes a multi-layered test suite that runs in CI on every pull request:

  • Integrity tests — Validate consistency between OpenAPI specs, toolset definitions, and tool name/description overrides. No network or credentials required.
  • Server construction tests — Build the server with mocked credentials and verify the correct number of tools are exposed. No network required.
  • Paper API integration tests — Execute real calls against the Alpaca paper trading API, covering account info, market data, order lifecycle, watchlists, positions, and more. Requires ALPACA_API_KEY and ALPACA_SECRET_KEY.
  • ReadMe integration tests — Execute live documentation lookup calls against Alpaca's ReadMe MCP. Requires ALPACA_RUN_README_INTEGRATION=true when run locally.

Run the full suite locally:

# Core tests (no credentials needed)
pytest tests/test_integrity.py tests/test_server_construction.py -v

# Integration tests (requires paper API keys)
ALPACA_API_KEY=... ALPACA_SECRET_KEY=... pytest tests/ -m integration -v

# ReadMe docs integration tests (requires network, no Alpaca credentials)
ALPACA_RUN_README_INTEGRATION=true pytest tests/test_readme_integration.py -v

Project Structure

alpaca-mcp-server/
├── src/
│   └── alpaca_mcp_server/
│       ├── __init__.py
│       ├── cli.py            ← CLI entry point
│       ├── server.py         ← FastMCP server built from OpenAPI specs
│       ├── tool_registry.py  ← Tool names, descriptions, and output risk classifications
│       ├── toolsets.py       ← Toolset → operationId allowlists
│       ├── overrides.py      ← Hand-crafted tools for complex trading endpoints
│       ├── market_data_overrides.py ← Hand-crafted tools for historical data
│       ├── readme_docs.py    ← Read-only proxy tools for Alpaca ReadMe docs
│       └── specs/
│           ├── trading-api.json
│           └── market-data-api.json

Files in the repo

Repository payload18 top-level entries
  • .github
  • .well-known
  • assets
  • charts
  • scripts
  • src
  • tests
  • .dockerignore
  • .gitignore
  • AGENTS.md
  • Dockerfile
  • LICENSE
  • pyproject.toml
  • README.md
  • requirements.txt
  • server.json
  • server.yaml
  • uv.lock

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More connectors

Real-time global intelligence dashboard. AI-powered news aggregation, geopolitical monitoring, and infrastructure tracking in a unified situational awareness interface

86k

High-performance code intelligence MCP server. Indexes codebases into a persistent knowledge graph — average repo in milliseconds. 158 languages, sub-ms queries, 99% fewer tokens. Single static binary, zero dependencies.

43k

Universal provider proxy for OpenAI Codex & Claude Code — use any LLM (Claude, Gemini, Grok, DeepSeek, Ollama…) with Codex CLI, App, SDK, and Claude Code

14k
okf-memory/
okf-agent-memory

Git-native persistent memory for AI coding agents. Implements Google OKF v0.2 with sub-300µs in-memory BM25 search, embedded MCP server, and progressive disclosure. Slashes token bloat by 80% with zero external databases or dependencies. Built in pure Go.

547
2akouwu/
reverify

Stop your AI from making things up — it proposes, deterministic tools decide, every claim checked against ground truth with evidence. Grounded facts and context survive resets. Reverse engineering is the proving ground. MCP server + CLI.

1.1k
t8y2/dbxConnectors

20 MB lightweight cross-platform database client for 90+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 90+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP Server。

19k