DhanHQ MCP Server
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@DhanHQ MCP Server start authentication for my DhanHQ account"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
DhanHQ MCP Server
An MCP (Model Context Protocol) server for DhanHQ APIs with OAuth-based authentication for Individual Traders.
Overview
This server implements the complete three-step DhanHQ authentication flow that generates a JWT access token for API requests. The authentication process involves:
Step 1: Generate Consent - Creates a temporary session ID
Step 2: Browser-Based Login - User authenticates with 2FA
Step 3: Consume Consent - Exchanges tokenId for access token
Related MCP server: Schwab MCP Server
Prerequisites
Before you begin, you need to generate your API Key and Secret:
Log in to web.dhan.co
Navigate to My Profile → 'Access DhanHQ APIs'
Toggle to 'API key'
Enter your:
App name
Redirect URL (e.g.,
http://localhost:3000/callback)Optional Postback URL
Note: Generated API Keys and Secrets are valid for 12 months.
Setup
1. Install Dependencies
npm install2. Configure Environment Variables
Copy .env.example to .env and fill in your credentials:
cp .env.example .envDHAN_CLIENT_ID=your_dhan_client_id
DHAN_API_KEY=your_api_key
DHAN_API_SECRET=your_api_secret
REDIRECT_URL=http://localhost:3000/callback3. Build the Project
npm run buildUsage
Development Mode
npm run devUsing MCP Inspector (Recommended for Debugging)
The MCP Inspector provides an interactive interface to test the MCP tools:
npm run inspectorThis will:
Start the MCP server
Open the MCP Inspector in your browser
Allow you to call tools and see responses in real-time
Authentication Flow
Step 1: Start Authentication
Call the start_authentication tool. This will:
Validate your API credentials
Create a temporary session (consentAppId)
Return a login URL
Step 2: Browser Login
Open the provided login URL in your browser:
Log in with your Dhan credentials
Complete 2FA verification (OTP/PIN/Password)
You'll be redirected to your configured Redirect URL with a
tokenIdparameter
Example redirect URL:
http://localhost:3000/callback?tokenId=abc123def456...Step 3: Complete Authentication
Call the complete_authentication tool with the tokenId from Step 2:
Exchanges the tokenId for a JWT access token
Stores token details (expiry, client info, etc.)
Returns the access token for use in subsequent API calls
Check Status
Use check_auth_status to view:
Current authentication state
Token validity
Client information
Token expiry time
Available MCP Tools
start_authentication
Initiates the DhanHQ authentication flow (Step 1).
Input: None
Output: consentAppId, loginUrl, instructions
get_login_instructions
Gets the login instructions and URL for Step 2.
Input: consentAppId (optional)
Output: loginUrl, detailed instructions
complete_authentication
Completes authentication with the tokenId from Step 2 (Step 3).
Input: tokenId (required)
Output: authToken with accessToken and client details
check_auth_status
Checks the current authentication status.
Input: None
Output: Authentication state and token validity
reset_authentication
Clears the current authentication state.
Input: None
Output: Success message
API Architecture
Framework: Node.js with TypeScript
Protocol: Model Context Protocol (MCP)
Transport: Stdio
Auth API: DhanHQ OAuth endpoints
HTTP Client: Axios
Project Structure
src/
├── index.ts # MCP server and tool handlers
├── authentication.ts # Authentication logic (3-step flow)
├── config.ts # Configuration management
└── types.ts # TypeScript interfacesSecurity Considerations
API credentials are stored in environment variables
Access tokens are stored in-memory (session-based)
For production, use:
Secure credential storage
Database for token persistence
Token refresh mechanisms
HTTPS for callbacks
The MCP Inspector output redacts sensitive tokens
Error Handling
The server includes comprehensive error handling:
API request validation
Network error handling
Configuration validation
Token expiry checking
Next Steps
After authentication is working:
Add API tools for trading operations
Implement token refresh logic
Add portfolio/holdings endpoints
Implement order placement tools
Add market data tools
Development Notes
Logs are printed to stderr for debugging
Authentication state is stored in-memory (lost on restart)
For production, migrate to persistent storage
MCP Inspector is recommended for interactive testing and debugging
License
MIT
Available Tools
18 toolscancel_orderA
Cancels a pending order. Requires authentication and a valid order ID.
Inputs: orderId (required).
cancel_super_order_legB
Cancels a specific leg of a super order (ENTRY_LEG, TARGET_LEG, or STOP_LOSS_LEG). Requires authentication.
Inputs: orderId (required), orderLeg (required).
check_auth_statusA
Checks the current authentication status and returns details about the active access token if available.
Inputs: no named parameters.
complete_authenticationA
Completes the authentication flow (Step 3). Takes the tokenId from the redirect URL after browser login and exchanges it for an access token.
Inputs: tokenId (required).
get_fund_limitA
Retrieves account fund limit information including available balance, margins, collateral, and withdrawable balance. Requires authentication.
Inputs: no named parameters.
get_login_instructionsA
Gets the login instructions and URL for Step 2 (browser-based login). You must complete this step manually by opening the URL in your browser.
Inputs: consentAppId.
get_order_bookB
Retrieves all orders placed during the day with their current status. Requires authentication.
Inputs: no named parameters.
get_order_by_correlation_idB
Retrieves order status using the user-specified correlation ID. Requires authentication.
Inputs: correlationId (required).
get_order_by_idC
Retrieves the details and status of a specific order by order ID. Requires authentication.
Inputs: orderId (required).
get_order_tradesB
Retrieves all trades for a specific order. Useful for partial fills or bracket/cover orders. Requires authentication.
Inputs: orderId (required).
get_super_order_bookB
Retrieves all super orders placed during the day with nested leg details. Requires authentication.
Inputs: no named parameters.
get_trade_bookA
Retrieves all trades executed during the day. Useful for tracking fills and execution prices. Requires authentication.
Inputs: no named parameters.
modify_orderC
Modifies a pending order. Can change price, quantity, order type, and other parameters. Requires authentication.
Inputs: orderId (required), dhanClientId (required), orderType (required), quantity, +3 more.
modify_super_orderC
Modifies any leg of a pending or part-traded super order. Requires authentication.
Inputs: orderId (required), dhanClientId (required), legName (required), orderType (required), +5 more.
place_orderC
Places a new order on DhanHQ. Requires authentication. Supports MARKET, LIMIT, STOP_LOSS, and STOP_LOSS_MARKET orders.
Inputs: dhanClientId (required), correlationId (required), transactionType (required), exchangeSegment (required), +12 more.
place_super_orderC
Places a smart super order combining entry, target, and stop-loss legs. Supports trailing stop loss. Requires authentication.
Inputs: dhanClientId (required), correlationId (required), transactionType (required), exchangeSegment (required), +8 more.
reset_authenticationB
Clears the current authentication state and resets the session.
Inputs: no named parameters.
start_authenticationA
Initiates the DhanHQ authentication flow (Step 1). Returns a login URL that you must open in your browser to authenticate.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Each tool has a clearly distinct purpose with no ambiguity. Tools are well-organized into authentication, order management, and super order categories, with clear boundaries between similar tools like get_order_book vs get_super_order_book and cancel_order vs cancel_super_order_leg.
All tools follow a consistent verb_noun pattern with snake_case throughout. Authentication tools use verbs like start, complete, check, reset; order tools use get, place, modify, cancel; and naming is predictable across the entire set.
18 tools is slightly high but reasonable for a comprehensive trading API server. The count covers authentication, order placement, modification, cancellation, and status retrieval thoroughly without obvious bloat, though it's at the upper end of typical scoping.
The tool set provides complete coverage for the trading domain with full authentication flow, CRUD operations for orders and super orders, status retrieval, and trade tracking. There are no apparent gaps in the surface for the stated purpose.
Maintenance
Related MCP Connectors
Connect brokerage accounts to AI assistants: holdings, orders, asset lookup, and approved trading.
OAuth LeanTrading tools for eligible Pro, Elite, Blueprint, and Admin users.
OpenFinance gives any AI agent easy trading across every major market through one hosted MCP server. Trade crypto spot and perpetuals on Hyperliquid with market, limit and TWAP orders, leverage and margin control. Trade stocks, indices, commodities, forex and pre-IPO names as Hyperliquid HIP-3 perps. Trade Polymarket prediction markets with odds, order books, positions, PnL and trader leaderboards. Swap and bridge across 40+ EVM chains and Solana with Relay and Jupiter, find memecoins across 200+ chains, launch tokens on Robinhood Chain and Solana, and buy crypto with card, bank or UPI. Write actions are designed to ask for your confirmation first. Connect with OAuth (sign in to OpenFinance and approve) or an API key. Works with Claude, ChatGPT, Cursor, VS Code, Codex and any MCP client. No install. Home: https://openfinance.tech/agents · Docs: https://docs.openfinance.tech · GitHub: https://github.com/openfinance-tech/mcp
AI agents backtest, paper trade and live trade via your broker. Free to connect; OAuth.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with the Zerodha trading platform for placing stock orders, viewing portfolio holdings, and managing mutual fund investments. Provides secure OAuth authentication and real-time trading capabilities through Zerodha's official API.1-
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to securely interact with Charles Schwab accounts through OAuth authentication, providing access to account balances, real-time market quotes, options chains, transaction history, order management, and comprehensive market data.1MIT
- AlicenseBqualityDmaintenanceEnables trading and portfolio management on Zerodha Kite Connect through natural language. Supports placing orders, viewing positions/holdings, accessing real-time market data, and managing GTT orders.24MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI models to interact with the Zerodha trading platform for portfolio management, trading, and account operations through natural language.3-