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 Servershow my current holdings"
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
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-serverOption 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.gitConfiguration
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_tokenLinux/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_token2. 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-serverOr with Python:
python -m serverThe 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 formatYYYY-MM-DD(e.g.,2025-11-01)to_date: End date in formatYYYY-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:
Add a new function in
server.pydecorated with@mcp.tool()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
.gitignorefile excludes.envfilesKeep 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_IDMCP Client Can't Find Server
Verify the installation:
pip show dhan-mcp-server
which dhan-mcp-server # Linux/Mac
where dhan-mcp-server # WindowsLicense
MIT License - see LICENSE file for details
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Resources
Available Tools
4 toolsget_all_ordersA
Fetch all orders from DhanHQ account. Returns a list of all orders with their details including order ID, status, quantity, price, etc.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of behavioral disclosure. It does disclose the return type (a list of orders with fields like ID, status, quantity, price), which is useful. However, it does not explicitly state read-only behavior, authentication needs, or potential limits such as pagination, so it is only partially transparent.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is concise, with two sentences that front-load the primary action and follow with a useful detail about the return content. There is no unnecessary repetition or filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the simplicity (zero parameters) and the presence of an output schema (which covers return structure), the description adequately conveys the core function. It could mention that it returns all orders without filtering, or note potential pagination, but for this tool it is reasonably complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The input schema has zero parameters, so the baseline of 4 applies. The description correctly has no parameter information to add, and the schema is already 100% covered by virtue of having no required or optional parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Fetch') and a specific resource ('all orders from DhanHQ account'), clearly stating the tool's scope. It distinguishes itself from siblings like get_trade_history (focused on trade history) and get_holdings_summary (holdings summary), making the purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus alternatives such as get_trade_history or get_holdings_summary. There are no exclusions, prerequisites, or conditions mentioned, leaving the agent to infer usage context.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_holdings_summaryB
Fetch holdings summary via DhanHQ SDK.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure, but it only says 'Fetch holdings summary.' It discloses no details about authentication requirements, data scope, return structure, or side effects, leaving the agent without essential behavioral context.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, compact sentence with no filler. 'Fetch holdings summary' is direct, and 'via DhanHQ SDK' adds useful implementation context without verbosity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The tool is simple (no parameters) and has an output schema, but the description is minimal. It does not explain prerequisites, response contents, or typical use cases, making it the bare minimum viable. Annotations would have compensated, but none are provided.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has no parameters, so the schema fully covers parameter semantics (coverage 100%). The description correctly adds nothing about parameters, and the baseline for zero-parameter tools is 4.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states a specific action ('Fetch') and a specific resource ('holdings summary'). This distinguishes it from the sibling tools which operate on orders, trade history, and token renewal, making the purpose unambiguous.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides no guidance on when to use this tool versus the sibling alternatives. It does not mention conditions, exclusions, or refer to other tools, so an agent must infer usage solely from the tool name.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
| to_date | Yes | ||
| from_date | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description discloses return details (trade ID, order ID, quantity, price, time, settlement status) and implies a read-only operation via 'Fetch.' However, it lacks explicit mention of auth requirements or pagination behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with a concise purpose sentence, parameter explanations, and return details. Every sentence adds value without unnecessary fluff.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple tool with an output schema, the description covers purpose, parameters, and returns sufficiently. It omits usage alternatives and auth context, but the tool's simplicity keeps it adequate.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema provides no descriptions (0% coverage) beyond string types, but the description fully compensates by specifying 'YYYY-MM-DD' format and examples for both from_date and to_date.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states 'Fetch trade history within a date range,' identifying a specific verb, resource, and scope. It naturally distinguishes from sibling tools like get_all_orders (orders) and get_holdings_summary (holdings).
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description provides a clear context for use (trade history in a date range) but does not explicitly mention alternatives or when not to use this tool. Sibling tools exist but are not referenced.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
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.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
No output parameters | ||
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries full burden. It clearly discloses that the tool expires the current token (destructive effect) and provides a new token, plus instructs to update environment variables. This goes beyond typical descriptions.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Three sentences, each serving a distinct purpose: action, effect, and limitation/instruction. No fluff; the main action is front-loaded.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description covers purpose, behavioral effect, return value, and a key restriction. With zero params and an output schema present, it is fully sufficient for an AI agent to invoke the tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
There are no parameters, so the baseline is 4. The description does not need to add parameter details, and it correctly omits them.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb 'renew' with a clear resource 'DhanHQ access token' and defines the exact duration (24 hours). It also implicitly distinguishes itself from the sibling tools, which are data retrieval operations.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The note 'Only works with tokens generated from Dhan Web' explicitly states a when-not-to-use condition. The context of token renewal for a fixed expiry window gives a clear reason to use the tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
4 tool updates
v0.4.0- First observed
get_all_orders - First observed
get_holdings_summary - First observed
get_trade_history - First observed
renew_access_token
TDQS
Scored across 4 tools
Each tool has a distinct purpose: holdings summary, order list, trade history, and token renewal. There is no overlap or ambiguity between them.
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.
Four tools is well within the ideal range and the scope is tightly focused on retrieval plus one maintenance operation. No unnecessary bloat.
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.
Maintenance
Related MCP Connectors
MCP server for Gainium — manage trading bots, deals, and balances via AI assistants
MCP server for OpenMM — exposes market data, account, trading, and strategy tools to AI agents
MCP server exposing the Backtest360 engine API as tools for AI agents.
Open-source MCP server for Zerodha Kite Connect. Portfolio, market data, backtesting, alerts.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceAn MCP server for the Groww trading platform. This enables LLM applications to interact with your Groww trading account.4-
- AlicenseAqualityAmaintenanceThis 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.37808 PyPI65Apache 2.0
- AlicenseNot gradedqualityDmaintenanceA production-ready MCP server for algorithmic trading with Dhan broker API, providing market data, order management, portfolio tracking, and real-time trading capabilities.1MIT
- AlicenseNot gradedqualityBmaintenanceAn 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