# ๐ DhanHQ MCP Server - Project Overview
## What's Been Created
You now have a fully functional MCP (Model Context Protocol) server for DhanHQ APIs with a complete three-step OAuth authentication flow. This is the foundation for building your trading application.
## ๐๏ธ Project Structure
```
DhanMCPServer/
โโโ src/
โ โโโ index.ts # MCP server & tool handlers
โ โโโ authentication.ts # 3-step auth flow implementation
โ โโโ config.ts # Configuration management
โ โโโ types.ts # TypeScript interfaces
โโโ dist/ # Compiled JavaScript (auto-generated)
โโโ package.json # Project dependencies
โโโ tsconfig.json # TypeScript configuration
โโโ .env # Your API credentials (DO NOT COMMIT)
โโโ .env.example # Template for .env
โโโ README.md # Full documentation
โโโ QUICKSTART.md # Quick start guide
โโโ .gitignore # Files to exclude from git
```
## ๐ Authentication Flow (Complete)
The server implements all three steps of DhanHQ OAuth:
### Step 1: Generate Consent โ
- **Tool:** `start_authentication`
- **What it does:** Validates your API credentials and creates a temporary session
- **Returns:** `consentAppId` and login URL
- **Status:** READY
### Step 2: Browser-Based Login โ
- **Tool:** `get_login_instructions`
- **What it does:** Provides the URL for user login in browser
- **User Action:** Opens URL, enters credentials, completes 2FA
- **Returns:** `tokenId` (extracted from redirect URL)
- **Status:** READY (manual human intervention)
### Step 3: Consume Consent โ
- **Tool:** `complete_authentication`
- **What it does:** Exchanges tokenId for JWT access token
- **Returns:** `accessToken` and client details
- **Status:** READY
### Additional Tools โ
- **`check_auth_status`:** View current authentication state
- **`reset_authentication`:** Clear session and start fresh
## ๐ฆ Technology Stack
| Layer | Technology | Version |
|-------|-----------|---------|
| Runtime | Node.js | Latest LTS |
| Language | TypeScript | 5.3+ |
| Protocol | MCP (Model Context Protocol) | 1.0.0 |
| HTTP Client | Axios | 1.6.0 |
| Config | dotenv | 16.3.1 |
## ๐ How to Use
### 1. Configure Credentials
```bash
# Edit .env with your DhanHQ API credentials
DHAN_CLIENT_ID=your_id
DHAN_API_KEY=your_key
DHAN_API_SECRET=your_secret
```
### 2. Install & Build
```bash
npm install
npm run build
```
### 3. Debug with MCP Inspector
```bash
npm run inspector
```
### 4. Follow the Auth Flow
1. Call `start_authentication` โ Get login URL
2. Open URL in browser โ Get tokenId
3. Call `complete_authentication` with tokenId โ Get access token
4. Use access token for API requests
## ๐ ๏ธ Available Commands
```bash
npm install # Install dependencies
npm run build # Compile TypeScript
npm run dev # Build and start server
npm run watch # Watch mode (auto-compile)
npm run inspector # Launch MCP Inspector (recommended)
```
## ๐ก MCP Tools Available
### `start_authentication`
```
Description: Initiate the three-step auth flow (Step 1)
Input: None
Output: {
consentAppId: string,
loginUrl: string,
message: string
}
```
### `get_login_instructions`
```
Description: Get instructions for browser login (Step 2)
Input: {
consentAppId?: string // Optional, uses latest if not provided
}
Output: {
loginUrl: string,
instruction: string
}
```
### `complete_authentication`
```
Description: Complete auth with tokenId (Step 3)
Input: {
tokenId: string // Required - from redirect URL
}
Output: {
success: boolean,
message: string,
authToken: {
accessToken: string,
dhanClientId: string,
dhanClientName: string,
dhanClientUcc: string,
expiryTime: string,
givenPowerOfAttorney: boolean,
generatedAt: string
}
}
```
### `check_auth_status`
```
Description: Check current authentication status
Input: None
Output: {
authenticated: boolean,
hasValidToken: boolean,
accessToken: string | null,
authState: { ... }
}
```
### `reset_authentication`
```
Description: Clear authentication state and reset session
Input: None
Output: {
success: boolean,
message: string
}
```
## ๐ Security Notes
Current Implementation:
- โ
Credentials stored in environment variables
- โ
Access tokens are redacted in status checks
- โ
Credentials never logged to console
- โ ๏ธ Auth state stored in-memory (lost on restart)
Production Recommendations:
- Add HTTPS for callback URLs
- Use secure credential storage (vault/secrets manager)
- Persist auth tokens to database with encryption
- Implement token refresh mechanism
- Add rate limiting
- Use secure session management
## ๐ File Descriptions
### `src/index.ts` (297 lines)
- MCP server initialization
- Tool schema definitions
- Tool execution handlers
- Request/response formatting
### `src/authentication.ts` (180 lines)
- Step 1: generateConsent()
- Step 2: getStep2Instructions()
- Step 3: consumeConsent()
- Token validation & management
### `src/config.ts` (30 lines)
- Environment variable loading
- Configuration validation
- Config export
### `src/types.ts` (45 lines)
- TypeScript interfaces
- Auth flow types
- Token types
## ๐ Data Flow
```
User Interaction
โ
CLI/Inspector calls Tool
โ
MCP Server (index.ts)
โ
Authentication Module (authentication.ts)
โ
DhanHQ OAuth APIs
โ
Return response (json) โ User
โ
Store in-memory state
```
## ๐งช Testing
### Test with MCP Inspector
```bash
npm run inspector
```
Then interact with the tools through the web UI.
### Manual Testing
```bash
npm run build
node dist/index.js
```
## ๐ Next Steps (Roadmap)
### Phase 1: Authentication โ
COMPLETE
- โ
3-step OAuth flow
- โ
Token management
- โ
MCP tools
### Phase 2: Core Trading APIs
- [ ] Get holdings
- [ ] Get positions
- [ ] Get orders
- [ ] Place orders
- [ ] Cancel orders
### Phase 3: Market Data
- [ ] Get quotes
- [ ] Get historical data
- [ ] Get market depth
- [ ] Stream live prices
### Phase 4: React Frontend
- [ ] Dashboard UI
- [ ] Login flow UI
- [ ] Portfolio view
- [ ] Order placement UI
- [ ] Market data visualization
### Phase 5: Production Ready
- [ ] Database integration
- [ ] Token refresh mechanism
- [ ] Error handling & recovery
- [ ] Logging & monitoring
- [ ] Deployment setup
## ๐ Debugging
### Enable Verbose Logging
All console logs go to stderr when running with MCP Inspector.
Check the MCP Inspector console for:
- `[Auth Step 1]` - Consent generation logs
- `[Auth Step 3]` - Token consumption logs
- `[MCP] Executing:` - Tool execution logs
- `[MCP] Tool execution error:` - Error details
### Common Issues
**"Cannot find module 'axios'"**
- Run: `npm install`
**"Missing required configuration"**
- Check your `.env` file has all required variables
**"Invalid API Key/Secret"**
- Verify credentials in web.dhan.co match your `.env`
**"No consentAppId available"**
- Run `start_authentication` first
## ๐ Documentation Files
- **README.md** - Complete technical documentation
- **QUICKSTART.md** - Step-by-step quick start guide
- **PROJECT_OVERVIEW.md** - This file
## ๐ค Integration Points
Once authenticated, you can:
1. Use `accessToken` from `check_auth_status` for API requests
2. Add new tools for trading operations
3. Build UI around these tools
4. Scale to production use
## ๐ Architecture Summary
- **MCP Protocol:** For tool-based interaction
- **OAuth 2.0:** For secure user authentication
- **Stdio Transport:** For communication
- **TypeScript:** For type safety
- **Node.js:** For runtime
The server is ready for:
- Local development
- Testing with MCP Inspector
- Adding new API tools
- Building UI on top
- Production deployment (with enhancements)
---
**Status:** โ
**Authentication Layer Complete and Ready for Testing**
Next: Run `npm run inspector` and follow QUICKSTART.md to test the authentication flow!