Skip to main content
Glama

Quick Start Guide - Upstox MCP Server

Step 1: Get Upstox API Credentials

  1. Visit https://upstox.com/developer/

  2. Create/login to your account

  3. Generate API Key and API Secret

  4. Set Redirect URI: http://localhost:3000/callback

Step 2: Clone/Create Project

Note Edit .env with your credentials:

Step 3: Run with Docker

docker-compose up

Note: Replace the environment variable values in the docker-compose.yml

Related MCP server: vibetrader-mcp

References

  • MCP Protocol and Server concepts

  • Integration with Perplexity and other LLM APIs

  • Portfolio rebalancing strategies with AI inference

  • Perplexity Local MCP integration

Architecture

  • Node.js MCP Server: Implements MCP Protocol for communication.

  • LLM Integration Module: Handles calls to external LLMs such as Perplexity for inference.

  • Docker Container: Provides isolated, reproducible run environment.

Development

Running Locally

  1. Install dependencies:

    npm install

  2. Start the application:

    npm run start / dev

Testing

Run tests with:

npx @modelcontextprotocol/inspector node dist/server.js

Connecting a Locally Running MCP to Perplexity

Configure Perplexity to Connect to MCP

  1. Go to below path Settings -> Connectors -> + Add Connector

  2. Provide a Name "Robinhood" so your LLM targets the mcp

  3. Under advanced tab

    Copy paste the perplexity.config.json content in Advanced tab in connectors

    Update your Perplexity environment variables to point to your MCP instance

  4. Save and exit. You should be able to see your MCP showing runnng with number of tools.

Start Using and happy trading

Once connected, you can use Perplexity to send commands and queries to your local MCP seamlessly. and you should be able to see the mcp under sources

Note: Replace the environment variable values in perplexity.config.json

Daily token renewal

Upstox access tokens expire every day at 03:30 IST and the OAuth flow returns no refresh token, so the server renews the token itself. Strategy order (renew_token tool / scheduler / 401 recovery):

  1. TOTP login (recommended, fully local, no public URL).

    • In Upstox account security settings, enable TOTP and save the base32 key shown during setup. If you didn't save it, reset TOTP to see a new key.

    • Set UPSTOX_TOTP_SECRET=<base32 key> and UPSTOX_PIN=<6-digit PIN> in .env.

    • Warning: .env then holds everything needed to log in to your account (API key/secret, TOTP key, PIN). chmod 600 .env and never commit it. The values are never logged or returned by any tool.

    • TOTP login revokes the currently active token, so it only runs when the token is missing, expired or rejected. Limits: at most one auto attempt per 2 minutes, and auto attempts pause after 3 consecutive failures until the next IST day (or a manual renew_token with force=true). A .env lock (UPSTOX_RENEW_LOCK_UNTIL) keeps parallel docker exec processes from logging in simultaneously.

  2. Access Token Request + Notifier webhook (optional, UPSTOX_NOTIFIER_ENABLED=1). Upstox sends an approval prompt to the Upstox app/WhatsApp; after you approve, it POSTs the token to your registered Notifier Webhook URL. That URL must be public HTTPS reaching container port 9082 at /notifier/<UPSTOX_NOTIFIER_SECRET> (a Cloudflare Tunnel on a stable domain works; Upstox blocks dynamic-DNS and proxy domains). Tools: request_access_token.

  3. OAuth login at http://localhost:9082/login (manual fallback).

The scheduler (checks every 5 min, plus a daily run at UPSTOX_TOKEN_REQUEST_TIME_IST) runs only in the process that owns the auth port. Other tools: get_token_status, logout.

Env var

Default

Purpose

UPSTOX_TOTP_SECRET, UPSTOX_PIN

unset

Enable TOTP login

UPSTOX_NOTIFIER_ENABLED

0

Enable Access Token Request path + /notifier route

UPSTOX_NOTIFIER_SECRET

unset

If set, webhook is served only at /notifier/<secret>

UPSTOX_AUTO_TOKEN_REQUEST

on

0 disables the scheduler

UPSTOX_TOKEN_REQUEST_TIME_IST

08:00

Daily renewal check time (skips if token has >12h left)

UPSTOX_TOKEN_REQUEST_COOLDOWN_MIN

30

Dedupe window for Access Token Requests

UPSTOX_ENV_PATH

../.env

Alternate env file (testing)

UPSTOX_BASE_URL

https://api.upstox.com

API base override (testing)

AUTH_PORT

9080

Auth/notifier server port

State written to .env by the server: UPSTOX_ACCESS_TOKEN, UPSTOX_TOKEN_EXPIRES_AT, UPSTOX_TOKEN_SIG, plus bookkeeping (UPSTOX_RENEW_LOCK_UNTIL, UPSTOX_TOTP_*, UPSTOX_TOKEN_REQUEST*).

Available Tools

59 tools
authorize_market_feedA

Get a one-time wss:// URL for the v3 market data feed. Not cached; single use.

Inputs: no named parameters.

authorize_portfolio_feedA

Get a one-time wss:// URL for the portfolio stream feed. update_types: comma list of order,gtt_order,position,holding. Not cached.

Inputs: update_types.

calculate_marginC

Calculate required margin for instruments (max 20).

Inputs: instruments (required).

cancel_orderC

Cancel a pending order.

Inputs: order_id (required).

convert_positionC

Convert position product type (e.g., intraday to delivery).

Inputs: quantity (required), new_product (required), old_product (required), instrument_token (required), +1 more.

exit_positionsB

Exit all open positions (square off).

Inputs: no named parameters.

get_brokerageC

Get brokerage charges for a trade.

Inputs: price (required), product (required), quantity (required), instrument_token (required), +1 more.

get_change_in_oiC

Change in option OI over N days (GET /v2/market/change-oi).

Inputs: date (required), expiry (required), interval (required), instrument_key (required).

get_dii_activityB

DII activity (GET /v2/market/dii), cash segment only. 1D: up to 30 trading days; 1M: up to 12 months.

Inputs: interval (required), from, data_type.

get_exchange_statusB

Current trading status of an exchange (e.g. NSE, BSE, NFO, BFO, MCX).

Inputs: exchange (required).

get_expired_expiriesC

List expired expiry dates available for an underlying instrument.

Inputs: instrument_key (required).

get_expired_future_contractsC

Expired future contracts for an underlying on a given expiry.

Inputs: expiry_date (required), instrument_key (required).

get_expired_historical_candlesB

Historical candles for an expired instrument key (from the expired contract listings).

Inputs: to_date (required), interval (required), from_date (required), expired_instrument_key (required).

get_expired_option_contractsC

Expired option contracts for an underlying on a given expiry.

Inputs: expiry_date (required), instrument_key (required).

get_fii_activityA

FII activity (GET /v2/market/fii). 1D: up to 30 trading days; 1M: up to 12 months; data from 2026-04-01.

Inputs: interval (required), data_type (required), from.

get_full_quote_v3C

Full market quote (OHLC, depth, volume) via v3, up to 500 instruments.

Inputs: instrument_keys (required).

get_funds_marginA

Get available funds and margin. version v3 (default) = GET /v3/user/get-funds-and-margin (Api-Version 3.0); v2 supports the optional segment SEC (equity) or COM (commodity).

Inputs: segment, version.

get_gtt_ordersA

Read-only: list GTT orders, or fetch one by gtt_order_id.

Inputs: gtt_order_id.

get_historical_candlesA

Get historical OHLCV candles (Upstox v3). Returns [timestamp, open, high, low, close, volume]. Use interval (legacy names) OR unit+interval_value. Units: minutes 1-300, hours 1-5, days/weeks/months 1. Max range per request: 1 month for minutes 1-15; 1 quarter for minutes >15 and hours; 1 decade for days. from_date is optional (defaults to to_date).

Inputs: to_date (required), instrument_key (required), unit, interval, +2 more.

get_historical_tradesC

Historical executed trades between two dates (paginated).

Inputs: end_date (required), page_size (required), start_date (required), page_number (required), +1 more.

get_holdingsB

Retrieve long-term DEMAT holdings.

Inputs: no named parameters.

get_intraday_candlesA

Get today's intraday candles (Upstox v3). Use interval (legacy names) OR unit+interval_value (minutes 1-300, hours 1-5, days 1).

Inputs: instrument_key (required), unit, interval, interval_value.

get_iposC

IPO listings. status: open|closed|listed|upcoming; records max 30.

Inputs: status, records, issue_type, page_number.

get_key_ratiosA

Company key ratios vs sector (P/E, P/B, ROA, ROE, ROCE, EV/EBITDA) by ISIN (GET /v2/fundamentals/{isin}/key-ratios).

Inputs: isin (required).

get_kill_switch_statusC

Kill-switch status per segment.

Inputs: no named parameters.

get_ltp_quotesC

Last Traded Price for up to 1000 instruments (v3).

Inputs: instrument_keys (required).

get_market_holidaysB

Get list of market holidays, or only the given date (path segment /v2/market/holidays/{date}).

Inputs: date.

get_market_quoteB

Full market quote with OHLC, depth, volume. Up to 500 instruments.

Inputs: instrument_keys (required).

get_market_timingsB

Get exchange market timings.

Inputs: date.

get_max_painC

Max pain with intraday insights (GET /v2/market/max-pain). bucket_interval is minutes between points (e.g. 60).

Inputs: date (required), expiry (required), instrument_key (required), bucket_interval (required).

get_mf_holdingsC

Mutual fund holdings.

Inputs: no named parameters.

get_mtf_positionsB

Get Margin Trade Funding positions.

Inputs: no named parameters.

get_newsC

News feed. category: instrument_keys (requires instrument_keys, max 30), positions, or holdings.

Inputs: category (required), page_size, page_number, instrument_keys.

get_ohlc_quotesC

OHLC quotes for up to 1000 instruments (v3). interval: 1d (default), I1 (1-minute) or I30 (30-minute).

Inputs: instrument_keys (required), interval.

get_open_interestC

Option OI by strike for an underlying (GET /v2/market/oi).

Inputs: date (required), expiry (required), instrument_key (required).

get_option_chainC

Get put/call option chain.

Inputs: expiry_date (required), instrument_key (required).

get_option_contractsC

Get option contracts for an underlying instrument.

Inputs: instrument_key (required), expiry_date.

get_option_greeksB

Option greeks (delta, gamma, theta, vega, IV) for up to 50 option instruments.

Inputs: instrument_keys (required).

get_order_bookA

Get all orders for the day (open, pending, filled, cancelled).

Inputs: no named parameters.

get_order_detailsC

Get details of a specific order by order_id.

Inputs: order_id (required).

get_order_historyC

Get order state history by order_id or tag.

Inputs: tag, order_id.

get_order_tradesC

Get trades for a specific order.

Inputs: order_id (required).

get_pcrC

Put-call ratio with intraday insights (GET /v2/market/pcr). bucket_interval is minutes between points (e.g. 60).

Inputs: date (required), expiry (required), instrument_key (required), bucket_interval (required).

get_pnl_chargesC

Charges and taxes breakdown for realised P&L in a segment and financial year.

Inputs: segment (required), financial_year (required), to_date, from_date.

get_pnl_metadataC

Trade P&L metadata (counts/totals) for a segment and financial year.

Inputs: segment (required), financial_year (required), to_date, from_date.

get_positionsB

Get current intraday and delivery positions with P/L.

Inputs: no named parameters.

get_profileB

Get user profile information.

Inputs: no named parameters.

get_static_ipsC

Static IPs registered for the account/app.

Inputs: no named parameters.

get_token_statusB

Token health: preview, expiry (ISO + IST), expired flag, renewal strategy, pending request, auth-port ownership, scheduler state. Never returns secrets.

Inputs: no named parameters.

get_trade_pnlC

Get trade-wise profit and loss data.

Inputs: segment (required), financial_year (required), page_size, page_number.

get_tradesB

Get all executed trades for the day.

Inputs: no named parameters.

logoutA

Log out: DELETE /v2/logout (invalidates the access token) and clear it from .env. With auto-renewal enabled, the scheduler may obtain a new token shortly after.

Inputs: no named parameters.

modify_orderC

Modify an existing open order.

Inputs: order_id (required), price, quantity, validity, +3 more.

place_orderC

Place a new order (market, limit, stop-loss, bracket).

Inputs: price (required), product (required), quantity (required), validity (required), +7 more.

renew_tokenA

Renew the access token now using the configured strategy: TOTP login (UPSTOX_TOTP_SECRET+UPSTOX_PIN) -> Access Token Request (UPSTOX_NOTIFIER_ENABLED=1) -> OAuth login URL. WARNING: TOTP login revokes the current token. force=true bypasses the 2-minute throttle and the 3-failure pause.

Inputs: force.

request_access_tokenA

Send an Access Token Request (v3): you approve a notification in the Upstox app/WhatsApp, then Upstox POSTs the token to the Notifier Webhook (needs UPSTOX_NOTIFIER_ENABLED=1 and a registered public webhook URL). force=true resends even if one is pending.

Inputs: force.

search_instrumentsC

Search instruments by text. exchanges/segments/instrument_types are comma-separated lists; records max 30.

Inputs: query (required), expiry, records, segments, +4 more.

start_auth_serverA

Start the embedded auth helper (OAuth /login + /callback, /status) on AUTH_PORT (currently 9080). Returns the login URL. Only one process sharing the .env can own the port; owns_port tells you whether this one does. Stays up until stop_auth_server or process exit.

Inputs: no named parameters.

stop_auth_serverA

Stop the embedded auth helper in this process if it owns it, releasing AUTH_PORT (currently 9080) and stopping the token-renewal scheduler.

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    C2.9/5.0

    Scored across 59 tools

    Disambiguation3/5

    Most tools target clear resource+action pairs, but several clusters overlap heavily: get_market_quote vs get_full_quote_v3 (near-identical v1/v3 full quotes), get_ltp_quotes/get_ohlc_quotes, and get_order_book vs get_order_details vs get_order_history vs get_trades vs get_order_trades require careful reading to select correctly. The auth cluster (renew_token, request_access_token, start_auth_server, get_token_status) is distinguishable but dense. Descriptions help, but an agent can easily pick the wrong quote or trade-listing tool.

    Naming Consistency4/5

    Strong, predictable snake_case verb_noun pattern throughout (get_*, place_*, modify_*, cancel_*, convert_*, authorize_*), with only minor deviations like get_full_quote_v3 and get_mtf_positions embedding version/qualifier tokens. Readable and largely uniform.

    Tool Count2/5

    59 tools is far beyond a comfortable surface for one agent to navigate, and the count is inflated by versioned duplicates (get_market_quote vs get_full_quote_v3) and many narrow single-endpoint wrappers (get_pcr, get_max_pain, get_change_in_oi, get_fii_activity, get_dii_activity, get_key_ratios). The domain is broad, but the surface is over-fragmented rather than consolidated.

    Completeness4/5

    Coverage is unusually broad for a broker server: order lifecycle (place/modify/cancel), positions, holdings, funds, margin, quotes, candles, options/greeks, fundamentals, news, IPOs, MF holdings, and auth/token management are all present. Gaps remain: GTT orders are read-only (no create/modify/cancel), and streaming is limited to one-time URL authorization rather than actual subscription tools.

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Integrates with Robinhood API and LLMs like Perplexity to provide AI-powered portfolio rebalancing recommendations and trading analytics without executing trades directly.
      MIT
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables LLM agents to analyze portfolios and execute orders on the Indian stock market via Upstox API v2 using natural language.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables interaction with the Upstox trading API via natural language to fetch user profile, funds, holdings, positions, orders, and trades.
      -