Skip to main content
Glama
DhanHQ MCP Server

DhanHQ MCP Server

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:

  1. Step 1: Generate Consent - Creates a temporary session ID

  2. Step 2: Browser-Based Login - User authenticates with 2FA

  3. 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:

  1. Log in to web.dhan.co

  2. Navigate to My Profile → 'Access DhanHQ APIs'

  3. Toggle to 'API key'

  4. 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 install

2. Configure Environment Variables

Copy .env.example to .env and fill in your credentials:

cp .env.example .env
DHAN_CLIENT_ID=your_dhan_client_id
DHAN_API_KEY=your_api_key
DHAN_API_SECRET=your_api_secret
REDIRECT_URL=http://localhost:3000/callback

3. Build the Project

npm run build

Usage

Development Mode

npm run dev

The MCP Inspector provides an interactive interface to test the MCP tools:

npm run inspector

This will:

  1. Start the MCP server

  2. Open the MCP Inspector in your browser

  3. 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 tokenId parameter

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 interfaces

Security 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:

  1. Add API tools for trading operations

  2. Implement token refresh logic

  3. Add portfolio/holdings endpoints

  4. Implement order placement tools

  5. 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 tools
cancel_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

    A3.7/5.0

    Scored across 18 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count4/5

    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.

    Completeness5/5

    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

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables 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
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables 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.
      1
      MIT
    • A
      license
      B
      quality
      D
      maintenance
      Enables 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.
      24
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI models to interact with the Zerodha trading platform for portfolio management, trading, and account operations through natural language.
      3
      -