DhanHQ MCP Server
Enables authentication and interaction with DhanHQ trading APIs through OAuth-based login flow, allowing users to manage trading operations and access market data through natural language.
README
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
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 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
Using MCP Inspector (Recommended for Debugging)
The MCP Inspector provides an interactive interface to test the MCP tools:
npm run inspector
This 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 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:
- 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
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.
E2B
Using MCP to run code via e2b.