Skip to content

yagop/alpaca-open-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

44 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ¦™ alpaca-open-api

mcp on npm core on npm MCP ready tools built with Bun license: MIT

  • πŸ€– MCP server β€” every Alpaca endpoint as an alpaca_<operationId> tool, via one npx.
  • ⚑ Typed clients β€” tradingApi, dataApi, brokerApi, authxApi, fully typed.
  • πŸ›°οΈ All four APIs β€” Trading, Data, Broker, AuthX β€” up to 273 tools.

πŸ€– MCP server (@alpaca-open-api/mcp)

πŸ”Œ Add it to your AI agent

πŸ’‘ Use your paper keys and ALPACA_ENV=paper while you experiment β€” the server defaults to live. See the safety note below.

Claude Code (CLI)
# requires npx (npm) installed
claude mcp add alpaca \
  --env ALPACA_API_KEY=your_paper_key \
  --env ALPACA_API_SECRET=your_paper_secret \
  --env ALPACA_ENV=paper \
  -- npx -y @alpaca-open-api/mcp

Add --scope user to make it available across all your projects. Verify with claude mcp list, then /mcp inside a session.

Claude Desktop

Edit claude_desktop_config.json (Settings β†’ Developer β†’ Edit Config):

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "alpaca": {
      "command": "npx",
      "args": ["-y", "@alpaca-open-api/mcp"],
      "env": {
        "ALPACA_API_KEY": "your_paper_key",
        "ALPACA_API_SECRET": "your_paper_secret",
        "ALPACA_ENV": "paper"
      }
    }
  }
}
Cursor

Create .cursor/mcp.json in your project (or ~/.cursor/mcp.json for all projects):

{
  "mcpServers": {
    "alpaca": {
      "command": "npx",
      "args": ["-y", "@alpaca-open-api/mcp"],
      "env": {
        "ALPACA_API_KEY": "your_paper_key",
        "ALPACA_API_SECRET": "your_paper_secret",
        "ALPACA_ENV": "paper"
      }
    }
  }
}
Any other MCP client (generic)

Most clients (Cline, Zed, Continue, …) accept the same stdio shape β€” point them at:

{
  "mcpServers": {
    "alpaca": {
      "command": "npx",
      "args": ["-y", "@alpaca-open-api/mcp"],
      "env": {
        "ALPACA_API_KEY": "your_paper_key",
        "ALPACA_API_SECRET": "your_paper_secret",
        "ALPACA_ENV": "paper"
      }
    }
  }
}

πŸ“Š Market data

Method Example output
stockSnapshots NVDA last trade $209.97, INTC $133.86, MU $1,139.94, MRVL $312.37, TSLA $399.81 (6/18 close)
stockLatestQuotes NVDA bid/ask 210.00 / 231.80; MSFT bid 359.90
stockBars NVDA 9 daily candles 6/8β†’6/18 (ranged ~$200–212)
movers Penny-stock dominated β€” ADTX +127%, INLF βˆ’64%
news 5 NVDA stories (FAB-10 ETF filing, semis whale activity, SpaceX/SPCX)
cryptoSnapshots / cryptoLatestQuotes BTC $63,610 / ETH $1,725 β€” live, 24/7
optionChain / optionSnapshots NVDA 6/22 call chain w/ quotes & greeks

🏦 Account & portfolio

Method Example output
getAccount ACTIVE, equity $99,931.66, cash $98,799.59, buying power $397,862.50, options level 3, not PDT
getAllOpenPositions 3 positions: AAPL 2sh long (βˆ’$24), NVDA 1sh short (βˆ’$32), SPY 1sh long (βˆ’$12)
getAllOrders Recent SPY bracket order, AAPL fills, NVDA short opened Nov 2025
getAccountPortfolioHistory ~flat near $99.9k over the past month
getAccountActivities Fills + CAT/TAF fees + initial $100k deposit (2024-02-07)

πŸ—“οΈ Reference

Method Example output
calendar Next trading day Mon 6/22, 09:30–16:00 ET
getV2Assets ~75 tradable crypto pairs (BTC, ETH, SOL, DOGE…)
getOptionsContracts 5 NVDA 6/22 call contracts
getV2CorporateActionsAnnouncements Works (no AAPL div/split in window β†’ empty)
getWatchlists None saved ([])

βš™οΈ Configuration

Everything is configured through environment variables:

Variable Required Default Purpose
ALPACA_API_KEY βœ… β€” API key (live and paper keys are different)
ALPACA_API_SECRET βœ… β€” API secret
ALPACA_ENV live paper or live. Selects paper/live (trading) and sandbox/production (broker, authx).
ALPACA_TOOLSETS trading,data Comma-separated subset to expose: trading,data,broker,authx. Add broker,authx for the full ~273-tool surface.
ALPACA_TRADING_URL / ALPACA_DATA_URL / ALPACA_BROKER_URL / ALPACA_AUTHX_URL per-API defaults Override the base URL for a specific API.

πŸ›Ÿ Safety

⚠️ The server allows all verbs in enabled toolsets and defaults to live β€” including real order placement in the default trading toolset. Provide live keys, or set ALPACA_ENV=paper (with your paper keys) to trade against the paper account. Live and paper API keys are different.

🧰 Tools

Every enabled Alpaca operation is registered as its own tool, alpaca_<operationId>. By default the server registers the trading and data toolsets (118 tools); set ALPACA_TOOLSETS=trading,data,broker,authx to expose the full 273-tool surface across all four APIs. Each tool's input is a Zod schema generated from the OpenAPI spec, with arguments grouped into pathParams, queryParams, and bodyParams, and validated before the call:

Tool Example arguments
alpaca_getAccount (none)
alpaca_stockLatestQuoteSingle { "pathParams": { "symbol": "AAPL" }, "queryParams": { "feed": "iex" } }
alpaca_postOrder { "bodyParams": { "symbol": "AAPL", "side": "buy", "qty": "1", "type": "market", "time_in_force": "day" } }

Host and auth are resolved automatically per API.


πŸ“¦ Packages

Package Description
@alpaca-open-api/mcp A Model Context Protocol server exposing the entire Alpaca API to AI agents. Installable as the alpaca-mcp CLI.
@alpaca-open-api/core Typed fetch clients and model types for all four Alpaca APIs (Trading, Market Data, Broker, AuthX), generated by Orval.

Every Alpaca call β€” from the MCP tools and the library clients alike β€” routes through one small shared mutator (packages/core/src/mutator.ts) that resolves the host and authentication per API. It is the only hand-written HTTP code in the project.


πŸ“š Library (@alpaca-open-api/core)

npm install @alpaca-open-api/core

Typed fetch clients, one namespace per API. Credentials and environment come from the same variables the MCP server uses (ALPACA_API_KEY, ALPACA_API_SECRET, ALPACA_ENV; live by default), read by the shared mutator.

import { tradingApi, dataApi, tradingModel } from '@alpaca-open-api/core';

// Each call returns { data, status, headers }; `data` is typed from the spec.
const { data: account } = await tradingApi.getAccount();
console.log(account?.cash);

const { data: quote } = await dataApi.stockLatestQuoteSingle('AAPL', { feed: 'iex' });
console.log(quote?.quote?.ap);

// Place an order (uses the live account unless ALPACA_ENV=paper):
await tradingApi.postOrder({ symbol: 'AAPL', side: 'buy', qty: '1', type: 'market', time_in_force: 'day' });

// Schema types are exported per API as `*Model` namespaces:
type Account = tradingModel.Account;

Client namespaces are tradingApi, dataApi, brokerApi, authxApi; the matching model (schema) types are tradingModel, dataModel, brokerModel, authxModel. makeMutator and API_ROUTING are also exported if you need to customize routing.


πŸ› οΈ Development

Prerequisites

  • Bun (v1.0+). A dev container with Bun pre-installed is included (.devcontainer).
  • Alpaca Markets API credentials (alpaca.markets).

Setup

bun install          # install all workspace dependencies
bun run generate     # generate the clients + Zod schemas from the OpenAPI specs (Orval)
bun run build        # generate, then build both packages to dist/ (core lib + MCP CLI)
bun run test         # run the unit tests

Run the MCP server from source during development:

bun run mcp          # = bun run src/mcp.ts in packages/mcp

🧬 Code generation

bun run generate runs Orval (one project per API, see orval.config.ts) to produce, into packages/*/src/generated/ (git-ignored, rebuilt on demand):

  • the MCP tool surface for @alpaca-open-api/mcp β€” per-operation handlers and Zod input schemas, plus a generated register<Api>Tools function per API that statically registers each operation onto the single stdio server composed in packages/mcp/src/compose.ts;
  • the typed fetch clients and model types for @alpaca-open-api/core.

A post-step (packages/mcp/scripts/postgen.ts) injects the mutator import, removes the unused generated server.ts, and emits the per-API registration. Orval is run under the Bun runtime (bunx --bun), since its CLI uses APIs missing from older Node.

Scripts

Root

  • bun run generate β€” regenerate all clients and schemas from the OpenAPI specs
  • bun run build β€” generate, then build both packages to dist/ (the core library and the MCP CLI)
  • bun run mcp β€” start the MCP server from source
  • bun run test β€” run the unit tests

@alpaca-open-api/core

  • bun run build β€” bundle src/index.ts β†’ dist/index.js (ESM, node target) and emit dist/*.d.ts via tsc

@alpaca-open-api/mcp

  • bun run build β€” bundle src/mcp.ts β†’ dist/mcp.js (shebang + node target; SDK and zod external)
  • bun run start / bun run dev β€” run the server (with --watch for dev)

πŸš€ Releasing

Releases are cut with the /release [version] Claude Code skill (.claude/skills/release): it drafts a GitHub Release with a changelog since the last tag, opens a version-bump PR, waits for you to merge it, tags main (which triggers the release workflow to publish both packages to npm), and finalizes the Release.


πŸ“‚ Examples

See packages/core/examples:

ALPACA_ENV=paper bun run packages/core/examples/basic-usage.ts

πŸ”— Resources

πŸ“„ License

MIT License β€” see LICENSE for details.


⚠️ Disclaimer

This is an unofficial, community-built project and is not affiliated with, endorsed by, or sponsored by Alpaca or its affiliates.
It is provided "as is", without warranty of any kind (see LICENSE). Nothing here is financial, investment, or trading advice.
Trading involves substantial risk of loss. The server defaults to live and can place real orders β€” always test with paper trading (ALPACA_ENV=paper) first.
You are solely responsible for safeguarding your API keys and for any activity performed with them.

Made with πŸ¦™ + Bun + Orval

About

πŸ¦™ Alpaca Markets API + MCP

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Packages

 
 
 

Contributors