Skip to main content
Glama
DhanHQ MCP Server

DhanHQ MCP Server

by Vedhasagaran

DhanHQ MCP Server

A Model Context Protocol (MCP) server that provides access to DhanHQ trading platform APIs. This server allows AI assistants and other MCP clients to interact with your DhanHQ trading account.

Features

  • Holdings Summary: Fetch your current holdings from DhanHQ

  • Extensible architecture for adding more DhanHQ API endpoints

Related MCP server: Public.com MCP Server

Prerequisites

  • Python 3.10 or higher

  • DhanHQ account with API access

  • DhanHQ Client ID and Access Token

Installation

Option 1: Install from PyPI (when published)

pip install dhan-mcp-server

Option 2: Install from source

git clone https://github.com/Vedhasagaran/dhan-mcp-py.git
cd dhan-mcp-py
pip install -e .

Option 3: Direct installation from GitHub

pip install git+https://github.com/Vedhasagaran/dhan-mcp-py.git

Configuration

1. Set Environment Variables

The server requires DhanHQ credentials to be set as environment variables:

Windows (PowerShell):

$env:DHAN_CLIENT_ID="your_client_id"
$env:DHAN_ACCESS_TOKEN="your_access_token"

Windows (Command Prompt):

set DHAN_CLIENT_ID=your_client_id
set DHAN_ACCESS_TOKEN=your_access_token

Linux/Mac:

export DHAN_CLIENT_ID="your_client_id"
export DHAN_ACCESS_TOKEN="your_access_token"

Using .env file (recommended):

Create a .env file in your project directory:

DHAN_CLIENT_ID=your_client_id
DHAN_ACCESS_TOKEN=your_access_token

2. Configure MCP Client

Add the server to your MCP client configuration. The configuration file location varies by application:

  • Claude Desktop: %APPDATA%\Claude\claude_desktop_config.json (Windows) or ~/Library/Application Support/Claude/claude_desktop_config.json (Mac)

  • Other MCP Clients: Refer to your client's documentation

Example configuration:

{
  "mcpServers": {
    "dhan": {
      "command": "dhan-mcp-server",
      "env": {
        "DHAN_CLIENT_ID": "your_client_id",
        "DHAN_ACCESS_TOKEN": "your_access_token"
      }
    }
  }
}

Alternative using Python directly:

{
  "mcpServers": {
    "dhan": {
      "command": "python",
      "args": ["-m", "server"],
      "env": {
        "DHAN_CLIENT_ID": "your_client_id",
        "DHAN_ACCESS_TOKEN": "your_access_token"
      }
    }
  }
}

Usage

Starting the Server Manually

If you want to run the server directly:

dhan-mcp-server

Or with Python:

python -m server

The server communicates via stdio (standard input/output) using the MCP protocol.

Available Tools

Once connected via an MCP client, the following tools are available:

get_holdings_summary

Fetches your current holdings from DhanHQ.

Returns:

{
  "holdings": [
    // Array of holding objects
  ]
}

get_all_orders

Fetches all orders from your DhanHQ account.

Returns:

{
  "orders": [
    // Array of order objects with details like order ID, status, quantity, price, etc.
  ]
}

get_trade_history

Fetch trade history within a specific date range.

Parameters:

  • from_date: Start date in format YYYY-MM-DD (e.g., 2025-11-01)

  • to_date: End date in format YYYY-MM-DD (e.g., 2025-11-21)

Returns:

{
  "status": "success",
  "from_date": "2025-11-01",
  "to_date": "2025-11-21",
  "trades": [
    // Array of trade objects with details like trade ID, order ID, quantity, price, time, settlement status
  ]
}

renew_access_token

Renews your DhanHQ access token for another 24 hours. This is useful for extending your session without manually copying tokens from the web interface.

Important: Only works with tokens generated from Dhan Web (web.dhan.co). Tokens obtained via API key/secret cannot be renewed using this method.

Returns:

{
  "status": "success",
  "message": "Token renewed successfully...",
  "new_token": "eyJ0eXAiOiJKV1QiLCJhbGc...",
  "expires_in": "24 hours"
}

Usage: After renewal, update your DHAN_ACCESS_TOKEN environment variable with the new token, or update your MCP client configuration.

Development

Setting Up Development Environment

# Clone the repository
git clone https://github.com/Vedhasagaran/dhan-mcp-py.git
cd dhan-mcp-py

# Create virtual environment
python -m venv venv

# Activate virtual environment
# Windows:
venv\Scripts\activate
# Linux/Mac:
source venv/bin/activate

# Install in editable mode with dependencies
pip install -e .

Adding New Tools

To add new DhanHQ API endpoints:

  1. Add a new function in server.py decorated with @mcp.tool()

  2. Follow this pattern:

@mcp.tool()
def your_new_tool() -> dict:
    """
    Description of what this tool does.
    """
    client = dhanhq(client_id, access_token)
    result = client.your_api_method()
    return {"data": result}

Security Notes

  • Never commit credentials: The .gitignore file excludes .env files

  • Keep tokens secure: Access tokens provide full access to your DhanHQ account

  • Use environment variables: Always load credentials from environment variables

  • Rotate tokens regularly: Follow DhanHQ's security best practices

Troubleshooting

"Missing DHAN_CLIENT_ID or DHAN_ACCESS_TOKEN"

Ensure environment variables are set correctly. Check with:

# Windows PowerShell
echo $env:DHAN_CLIENT_ID

# Linux/Mac
echo $DHAN_CLIENT_ID

MCP Client Can't Find Server

Verify the installation:

pip show dhan-mcp-server
which dhan-mcp-server  # Linux/Mac
where dhan-mcp-server  # Windows

License

MIT License - see LICENSE file for details

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Resources

Available Tools

4 tools
get_all_ordersA

Fetch all orders from DhanHQ account. Returns a list of all orders with their details including order ID, status, quantity, price, etc.

Inputs: no named parameters. Returns: object

get_holdings_summaryB

Fetch holdings summary via DhanHQ SDK.

Inputs: no named parameters. Returns: object

get_trade_historyA

Fetch trade history within a date range.

Parameters:

  • from_date: Start date in format 'YYYY-MM-DD' (e.g., '2024-11-01')

  • to_date: End date in format 'YYYY-MM-DD' (e.g., '2024-11-21')

Returns all trades executed within the specified date range with details including: trade ID, order ID, quantity, price, time, and settlement status.

Inputs: to_date (required), from_date (required). Returns: object

renew_access_tokenA

Renew the DhanHQ access token for another 24 hours. This expires the current token and provides a new token with 24 hours validity. Note: Only works with tokens generated from Dhan Web (web.dhan.co). Returns the new access token that should be updated in your environment variables.

Inputs: no named parameters. Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 4 tools

    Disambiguation5/5

    Each tool has a distinct purpose: holdings summary, order list, trade history, and token renewal. There is no overlap or ambiguity between them.

    Naming Consistency5/5

    All tool names follow a clear verb_noun pattern: get_holdings_summary, get_all_orders, get_trade_history, and renew_access_token all use a consistent style. The slight verb variation is appropriate for different actions.

    Tool Count5/5

    Four tools is well within the ideal range and the scope is tightly focused on retrieval plus one maintenance operation. No unnecessary bloat.

    Completeness4/5

    The core read operations are covered (summaries, orders, trades) plus token renewal, but missing functionality like account balance or positions could be expected. Still, the surface is reasonably complete for a read-only-style server.

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      D
      maintenance
      An MCP server for the Groww trading platform. This enables LLM applications to interact with your Groww trading account.
      5
      -
    • A
      license
      A
      quality
      B
      maintenance
      This MCP server connects AI assistants to a Public.com brokerage account, enabling natural language trading of stocks, options, and crypto, along with portfolio management, quotes, and orders.
      46
      914 PyPI
      67
      Apache 2.0
    • A
      license
      Not graded
      quality
      D
      maintenance
      A production-ready MCP server for algorithmic trading with Dhan broker API, providing market data, order management, portfolio tracking, and real-time trading capabilities.
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server that lets you talk to your AI trading assistant in plain English to research stocks, generate trade recommendations, manage a portfolio, and execute trades through natural language.
      MIT