Skip to main content
Glama
PROJECT_OVERVIEW.mdโ€ข8.13 kB
# ๐Ÿ“‹ 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!

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/harshitdynamite/DhanMCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server