Connect Alpaca to Claude: Manage Brokerage Accounts & Asset Trading
Learn how to build a secure, managed MCP server to connect Alpaca to Claude. Automate trading workflows, manage brokerage accounts, and stream market data.
If you need to connect Alpaca to Claude to automate stock and crypto trading, manage brokerage accounts, or analyze live market data, you need a Model Context Protocol (MCP) server. This server acts as the translation layer between Claude's natural language tool calls and Alpaca's complex REST APIs. You can either build and maintain this infrastructure yourself, or use a managed integration platform like Truto to dynamically generate a secure, authenticated MCP server URL. If your team uses ChatGPT, check out our guide on connecting Alpaca to ChatGPT or explore our broader architectural overview on connecting Alpaca to AI Agents.
Giving a Large Language Model (LLM) read and write access to a live brokerage environment is a serious engineering challenge. You must handle stringent authentication, map highly specific financial data schemas to MCP tool definitions, and deal with Alpaca's strict market data quotas. Every time Alpaca introduces a new asset class or modifies a trading parameter, you have to update your server code, redeploy, and test the integration.
This guide breaks down exactly how to use Truto to generate a secure, managed MCP server for Alpaca, connect it natively to Claude, and execute complex financial workflows using natural language.
The Engineering Reality of the Alpaca API
A custom MCP server is a self-hosted integration layer. While the open MCP standard provides a predictable way for models to discover tools over JSON-RPC 2.0, the reality of implementing it against Alpaca's infrastructure is painful. You are not just integrating a simple REST API - you are bridging the gap between an LLM and a high-frequency trading backend.
If you decide to build a custom MCP server for Alpaca, you own the entire API lifecycle. Here are the specific challenges you will face:
The Dual-Domain API Architecture Alpaca physically separates its APIs into distinct domains: the Trading API (orders, positions, account management) and the Market Data API (historical bars, real-time quotes, trades). These systems have different base URLs, different authentication requirements, and different data models. An LLM has no inherent context on which domain to use for a given prompt. You must build an abstraction layer that presents a unified set of operations to Claude, hiding the underlying endpoint fragmentation so the model doesn't hallucinate API routes.
Complex Market Data Formatting Alpaca's market data endpoints require highly specific data formats that LLMs struggle to generate consistently. Timestamps must strictly follow RFC3339 format. Fetching historical data requires understanding conditions, tape codes (A, B, C), and SIP (Securities Information Processor) rules. Passing raw Alpaca market data parameters to Claude will result in malformed requests. A managed MCP server translates plain JSON Schema into exactly what Alpaca expects.
Handling Pagination and Cursors
Alpaca handles massive market data sets (like tick-by-tick trades) using distinct pagination schemes heavily reliant on page_token. If you expose raw pagination tokens directly to Claude without strict system instructions, the model will frequently hallucinate token values or attempt to decode them. Truto normalizes this across all Alpaca endpoints into a standard limit and next_cursor schema, explicitly instructing the LLM to pass cursor values back unchanged.
Factual Note on Rate Limits
Financial APIs aggressively rate limit requests. It is critical to understand how this is handled at the MCP layer: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Alpaca API returns an HTTP 429 (Too Many Requests), Truto passes that error directly to the caller. Truto normalizes the upstream rate limit info into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF spec. The AI agent or calling framework is strictly responsible for implementing its own retry and backoff logic.
How to Generate an Alpaca MCP Server with Truto
Truto's MCP implementation is dynamic and documentation-driven. Instead of hand-coding tool definitions for Alpaca, Truto derives them directly from the integration's underlying resources and schema definitions.
Each MCP server is scoped to a single connected Alpaca account. The server URL contains a cryptographic token that encodes the account identity and allowed configurations. You can create this server in two ways.
Method 1: Via the Truto UI
For quick prototyping or manual setup, you can generate an MCP server directly from the dashboard.
- Navigate to the Integrated Accounts page in your Truto dashboard and select your connected Alpaca connection (Paper or Live).
- Click the MCP Servers tab.
- Click Create MCP Server.
- Select your desired configuration (e.g., name the server "Alpaca Live Trading", restrict methods to "read" and "write", and optionally set an expiration date).
- Copy the generated MCP server URL (e.g.,
https://api.truto.one/mcp/a1b2c3d4e5f6...).
Method 2: Via the Truto API
For production deployments and programmatic generation, you can create an MCP server via a REST call. This is ideal for provisioning agent access on the fly.
POST /integrated-account/:id/mcp
{
"name": "Claude Trading Agent MCP",
"config": {
"methods": ["read", "write"],
"tags": ["market_data", "trading"]
},
"expires_at": "2025-12-31T23:59:59Z"
}The API validates that the Alpaca integration has AI-ready tools available, generates a secure, hashed token stored in Cloudflare KV, and returns the ready-to-use URL.
{
"id": "mcp-alp-987",
"name": "Claude Trading Agent MCP",
"config": {
"methods": ["read", "write"],
"tags": ["market_data", "trading"]
},
"expires_at": "2025-12-31T23:59:59Z",
"url": "https://api.truto.one/mcp/a1b2c3d4e5f67890"
}Connecting the Alpaca MCP Server to Claude
Once you have the Truto MCP URL, you need to configure Claude to use it. The setup process varies depending on whether you are using the desktop app or the web interface.
Method A: Via the Claude UI (Desktop/Web)
If you are using Claude Desktop (or ChatGPT with custom connectors), you can add the server directly through the settings panel.
- Open Claude Desktop and navigate to Settings -> Integrations -> Add MCP Server (In ChatGPT, navigate to Settings -> Apps -> Advanced settings -> Developer mode -> Custom connectors).
- Give the connector a name (e.g., "Alpaca Trading Server").
- Paste the Truto MCP URL you generated in the previous step.
- Click Add or Save.
Claude will immediately perform a JSON-RPC 2.0 handshake (initialize), request the tool definitions (tools/list), and make the Alpaca operations available for use.
Method B: Via Manual Config File
For automated deployments or advanced local configurations of Claude Desktop, you can modify the claude_desktop_config.json file directly. Because Truto's MCP servers are served over HTTP, you bridge the local standard I/O requirement using the @modelcontextprotocol/server-sse package.
{
"mcpServers": {
"alpaca-trading": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sse",
"--url",
"https://api.truto.one/mcp/a1b2c3d4e5f67890"
]
}
}
}Restart Claude Desktop. The application will execute the command, bridging local JSON-RPC calls over Server-Sent Events to the Truto API.
Essential Alpaca Tools for Claude
Truto automatically generates descriptive, snake_case tool names from Alpaca's endpoints, combining robust JSON Schemas for both query and body parameters into a flat LLM-friendly namespace.
Here are the highest-leverage hero tools to expose to Claude for trading automation.
list_all_alpaca_stock_snapshots
Market data is the foundation of any trading decision. This tool fetches a comprehensive market snapshot for a single stock symbol, including the latest trade, latest quote, minute bar, daily bar, and previous daily bar.
"Get the current market snapshot for TSLA. I need the latest trade price and yesterday's daily bar close to check if the stock is gapping up."
create_a_alpaca_account_order
This is the core execution tool. It creates a new order in the Alpaca trading account. Claude handles the complexity of specifying the symbol, quantity, side (buy/sell), order type (market, limit), and time in force.
"Submit a market order to buy 25 shares of NVDA. Set the time in force to day."
list_all_alpaca_positions
Before executing trades or rebalancing a portfolio, the LLM must know what assets are currently held. This tool lists all open long and short positions in the connected account.
"List all my current open positions. Summarize the unrealized profit and loss for each asset."
get_single_alpaca_account_position_by_id
When Claude needs deep context on a specific holding - such as cost basis, average entry price, or market value - it uses this tool by passing the asset symbol or ID.
"Check my specific position for AAPL. What is my average entry price, and how many shares do I currently hold?"
list_all_alpaca_crypto_bars_latests
Alpaca provides extensive crypto market data. This tool fetches the latest OHLCV (Open, High, Low, Close, Volume) bar data for multiple crypto symbols simultaneously, which is perfect for cross-asset screening.
"Get the latest minute bars for BTC/USD and ETH/USD. Compare their trading volume over the last minute."
list_all_alpaca_accounts
For fintech platforms building on top of Alpaca's Broker API, this tool manages end-user accounts. It lists all brokerage accounts, allowing Claude to filter by status or creation date.
"List all active brokerage accounts created in the last 7 days."
For the complete tool inventory and schema details, visit the Alpaca integration page.
Workflows in Action
Once the MCP server is connected, Claude transforms from a text generator into a sophisticated algorithmic trading assistant. Here are two real-world workflows.
Scenario 1: Pre-Market Analysis and Automated Rebalancing
A quantitative analyst wants to adjust their portfolio based on overnight price action relative to their current holdings.
"Check my current open positions. Then, get the market snapshots for any tech stocks I hold. If any position is up more than 5% from its average entry price, submit an order to sell 50% of the shares to lock in profits."
Step-by-step execution:
- Claude calls
list_all_alpaca_positionsto retrieve the user's current holdings and identifies tech stocks (e.g., AAPL, MSFT). - Claude loops through the identified symbols, calling
list_all_alpaca_stock_snapshotsfor each to get the latest quote and trade data. - Claude performs the math: comparing the
avg_entry_pricefrom the position data to thelatestTrade.p(price) from the snapshot. - Identifying that AAPL is up 6.2%, Claude calculates 50% of the
qtyheld. - Claude calls
create_a_alpaca_account_orderwithsymbol: "AAPL",side: "sell",qty: [calculated amount],type: "market", andtime_in_force: "day".
The user receives a summary of the analysis and confirmation of the executed sell order.
sequenceDiagram
participant User as User
participant Claude as Claude Desktop
participant MCP as Truto MCP Server
participant Alpaca as Alpaca API
User->>Claude: "Check positions, analyze tech stocks, sell if up > 5%"
Claude->>MCP: Call list_all_alpaca_positions
MCP->>Alpaca: GET /v2/positions
Alpaca-->>MCP: Returns [AAPL, MSFT, SPY]
MCP-->>Claude: JSON Array of positions
Claude->>MCP: Call list_all_alpaca_stock_snapshots (AAPL)
MCP->>Alpaca: GET /v2/stocks/snapshots?symbols=AAPL
Alpaca-->>MCP: Returns latest trade & quote
MCP-->>Claude: JSON snapshot
Claude->>Claude: Calculates AAPL is up 6.2%
Claude->>MCP: Call create_a_alpaca_account_order
MCP->>Alpaca: POST /v2/orders (Sell AAPL)
Alpaca-->>MCP: Returns Order ID 9876
MCP-->>Claude: Execution confirmation
Claude-->>User: "Analysis complete. AAPL sold to lock in 6.2% profit."Scenario 2: Brokerage Operations and Money Movement
An operations manager at a fintech app uses Claude to oversee user funding and account setup.
"Check the status of the newest Alpaca brokerage accounts. If any account is active but has no completed ACH transfers, draft a summary of those accounts so we can email them a funding reminder."
Step-by-step execution:
- Claude calls
list_all_alpaca_accountsusing query parameters to filter forstatus: "ACTIVE"and sorting by recent creation. - For each returned account, Claude extracts the
id. - Claude calls
list_all_alpaca_account_transfersfor each account ID, looking for transfers withstatus: "COMPLETE". - Claude filters out the accounts that have successfully funded.
- Claude outputs a structured list of Account IDs and creation dates that require a follow-up email.
Security and Access Control
Giving an LLM access to a live trading account requires strict security boundaries. Truto's MCP servers are designed with multiple layers of access control, ensuring the server acts exactly as you intend.
- Method Filtering: You can restrict the MCP token to only specific HTTP methods. Passing
config: { methods: ["read"] }during creation ensures Claude can only fetch data (like quotes and positions) and physically cannot execute aPOSTrequest to create an order. - Tag Filtering: By passing
config: { tags: ["market_data"] }, the MCP server will only generate tools associated with market data resources, hiding account management and trading tools from the LLM entirely. - API Token Authentication: For zero-trust environments, setting
require_api_token_auth: trueforces the MCP client to pass a valid Truto API token in theAuthorizationheader. The URL alone is no longer enough to access the tools. - Automatic Expiration: You can set an
expires_attimestamp. Truto enforces this at the database and KV layer, automatically tearing down the MCP server when the timestamp is reached, ensuring temporary AI access doesn't turn into a permanent backdoor.
Moving Fast in Modern Finance
Connecting Claude to Alpaca opens up entirely new possibilities for algorithmic trading, portfolio analysis, and back-office operations. But managing the underlying API infrastructure - dealing with rate limits, pagination cursors, and disparate API domains - drains engineering resources.
By leveraging Truto's managed MCP architecture, you replace months of custom integration code with a single dynamic server URL. Your AI agents get immediate, secure access to the data they need, and your engineering team gets to focus on building better trading strategies.
FAQ
- How does Claude access my Alpaca trading account securely?
- Claude connects through a Model Context Protocol (MCP) server. Truto generates a dynamic, token-secured MCP server URL scoped to your specific Alpaca account. This ensures Claude only accesses the tools and endpoints you explicitly allow, without exposing raw API keys directly to the model.
- Can I restrict the AI agent to read-only market data?
- Yes. When generating the MCP server in Truto, you can configure method filtering (e.g., allowing only 'read' operations) and tag filtering (e.g., allowing only 'market_data' tagged tools). This prevents the LLM from executing trades or modifying account configurations.
- How does the integration handle Alpaca API rate limits?
- Truto does not retry, throttle, or apply backoff on rate limit errors. When the Alpaca API returns an HTTP 429, Truto passes that error to Claude. Truto normalizes the rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset), and the caller must implement their own retry logic.
- Does this work with both Alpaca paper trading and live trading?
- Yes. The environment you connect in Truto dictates the access. You can connect a paper trading account to test your AI workflows safely before authenticating a live brokerage account.