๐น This is code for Zerodha MCP โ you can use it to trade live on the Indian Stock Market ๐ฎ๐ณ๐๐ฐ
๐ Zerodha MCP Server
A Model Context Protocol (MCP) server that provides tools for interacting with the Zerodha trading platform. This server enables AI assistants to place stock orders, view holdings, and manage mutual fund investments through Zerodha's API.
๐ฏ Features
Trading Tools
- Place Stock Orders - Execute buy/sell orders on NSE and BSE
- View Holdings - Get current stock portfolio holdings
- Mutual Fund SIPs - View active Systematic Investment Plans
- Mutual Fund Holdings - Check mutual fund portfolio (experimental)
Authentication
- Zerodha Login - Secure OAuth-based authentication
- Token Management - Automatic token storage and refresh
- Session Handling - Persistent login sessions
Technical Features
- TypeScript - Full type safety across the codebase
- MCP Protocol - Standardized AI assistant integration
- Error Handling - Comprehensive error management
- Logging - Detailed operation logging
๐๏ธ Architecture
zerodha-mcp/
โโโ config/
โ โโโ KiteConfig.ts
โ โโโ tokens.json
โโโ functions/
โ โโโ OrderRelated.ts
โโโ utils/
โ โโโ readWrite.ts
โโโ .env
โโโ bun.lock
โโโ main.ts
โโโ package.json
๐ ๏ธ Tech Stack
- TypeScript - Type-safe JavaScript
- MCP SDK - Model Context Protocol implementation
- KiteConnect - Zerodha's official trading API
- Axios - HTTP client for API requests
- Bun - Required JavaScript runtime
๐ฆ Installation
Prerequisites
- Bun - Required runtime
- Zerodha trading account
- Zerodha API credentials
1. Clone the Repository
git clone git@github.com:ManikLakhanpal/Zerodha-MCP.git
cd zerodha-mcp
2. Install Dependencies
bun install
3. Environment Setup
Create a .env
file in the root directory:
API_KEY=your_zerodha_api_key
API_SECRET=your_zerodha_api_secret
4. Get Zerodha API Credentials
- Log in to your Zerodha account
- Go to Zerodha Developers
- Create a new application
- Copy your API Key and API Secret
๐ Usage
Starting the MCP Server
bun main.ts
Using with Claude
This MCP server is designed to work with Claude AI assistants. Here's how to set it up:
1. Install Claude Desktop
First, download and install Claude Desktop for your operating system.
2. Configure Claude to Use MCP โ๏ธ
- ๐ฑ Open Claude Desktop
- ๐ง Go to Settings โ Developer Settings
- ๐ Click Open Config File to open
claude_desktop_config.json
in your default editor - โ๏ธ Add the following configuration to the
mcpServers
section:
{
"mcpServers": {
"kite": {
"command": "/opt/homebrew/bin/bun", # Use `which bun` to get path
"env": {
"API_KEY": "your_zerodha_api_key",
"API_SECRET": "your_zerodha_api_secret"
},
"args": ["/path/to/your/zerodha-mcp/main.ts"] # Paste the absolute path to main.ts
}
}
}
๐ง Important Notes:
- ๐ ๏ธ Replace
/opt/homebrew/bin/bun
with your Bun installation path (usewhich bun
to find it) - ๐ Replace
/path/to/your/zerodha-mcp/main.ts
with the actual path to your project'smain.ts
file - ๐ Replace
your_zerodha_api_key
andyour_zerodha_api_secret
with your actual Zerodha API credentials - ๐ท๏ธ The server name
"kite"
can be changed to any name you prefer
3. Authentication Flow ๐
- ๐ First Login: Ask Claude to "login to Zerodha"
- ๐ Get Login URL: Claude will provide a login URL
- โ Complete Login: Open the URL in your browser and complete Zerodha login
- ๐ง Set Tokens: Copy the request token from the URL and ask Claude to "set Zerodha tokens" with the token
4. Available Commands in Claude ๐ฌ
Once connected, you can ask Claude to:
- ๐ "Login to Zerodha" - Get authentication URL
- ๐ง "Set Zerodha tokens with [request_token]" - Complete authentication
- ๐ "Place a buy order for 10 shares of RELIANCE on NSE" - Execute trades
- ๐ "Show my current holdings" - View portfolio
- ๐ฐ "Get my mutual fund SIPs" - View SIP investments
- ๐ฆ "Check my mutual fund holdings" - View MF portfolio
5. Example Conversations ๐ญ
You: ๐ "Login to Zerodha"
Claude: ๐ [Provides login URL]
You: ๐ง "Set Zerodha tokens with abc123xyz"
Claude: โ
[Confirms token setup]
You: ๐ "Buy 5 shares of TCS on NSE"
Claude: ๐ฐ [Executes order and shows result]
You: ๐ "What stocks do I currently hold?"
Claude: ๐ [Shows your portfolio holdings]
Available Tools ๐ ๏ธ
1. ๐ Login to Zerodha
// Tool: login-to-zerodha
// Returns a login URL for user authentication
2. ๐ง Set Authentication Tokens
// Tool: set-zerodha-tokens
// Parameters: { request_token: string }
// Sets access tokens after successful login
3. ๐ Place Stock Order
// Tool: place-stock-order
// Parameters: {
// variety: "regular" | "amo" | "co" | "auction" | "iceberg",
// stock: string,
// qty: number,
// exchange: "NSE" | "BSE",
// orderType: "BUY" | "SELL"
// }
4. ๐ Get Holdings
// Tool: get-zerodha-holdings
// Returns current stock portfolio holdings
5. ๐ฐ Get Mutual Fund SIPs
// Tool: get-zerodha-mutual-fund-sips
// Returns active Systematic Investment Plans
6. ๐ฆ Get Mutual Fund Holdings
// Tool: zerodha-mf-holdings
// Returns mutual fund portfolio (experimental)
๐ง Configuration
๐ Token Management
The server automatically manages authentication tokens:
- ๐ Tokens are stored in
config/tokens.json
- ๐ Automatic token refresh on session expiry
- ๐ก๏ธ Secure token handling with error recovery
โก API Limits
- โฑ๏ธ Zerodha has rate limits on API calls
- ๐ ๏ธ The server includes built-in error handling
- ๐ Failed requests are logged with detailed error information
๐ Security
- ๐ Environment Variables - API credentials stored securely on your local machine
- ๐ Error Logging - No sensitive data in error messages
๐ API Reference
๐ข Zerodha API Integration
The server uses Zerodha's official KiteConnect API:
- ๐ Trading - Place orders, view holdings
- ๐ฐ Mutual Funds - SIP management and holdings
- ๐ Authentication - OAuth-based login flow
๐ค MCP Protocol
Implements the Model Context Protocol for AI assistant integration:
- ๐ ๏ธ Tool Definitions - Structured parameter schemas
- ๐ก๏ธ Error Handling - Graceful failure responses
- ๐ Type Safety - Zod schema validation
๐งช Development
๐ Project Structure
src/
โโโ main.ts # Server entry point
โโโ config/
โ โโโ KiteConfig.ts # Zerodha configuration
โโโ functions/
โ โโโ OrderRelated.ts # Trading functions
โโโ utils/
โโโ readWrite.ts # File utilities
๐ ๏ธ Adding New Tools
- ๐ Define the tool in
main.ts
- โ๏ธ Implement the function in
functions/
- ๐ก๏ธ Add proper error handling
- ๐ Update this README
๐จ Important Notes
โ ๏ธ Trading Risks
- ๐ฐ Real Money Trading - This server executes real trades
- โฐ Market Hours - Orders only work during market hours
- ๐ก๏ธ Risk Management - Implement proper stop-loss mechanisms
- ๐งช Testing - Use paper trading for testing
๐ง API Limitations
- โฑ๏ธ Rate Limits - Respect Zerodha's API rate limits
- ๐ Market Hours - Some functions only work during trading hours
- ๐ฆ Account Type - Requires a Zerodha trading account
๐ง Troubleshooting
๐จ Common Issues
๐ Authentication Errors
# Check if tokens are valid
cat config/tokens.json
# Re-authenticate if needed
# Use login-to-zerodha tool
โ ๏ธ API Errors
- ๐ Verify API credentials in
.env
- ๐ฆ Check Zerodha account status
- โฐ Ensure market hours for trading functions
๐ Network Issues
- ๐ก Check internet connection
- ๐ข Verify Zerodha API status
- ๐ Review error logs for details
๐ค Claude MCP Connection Issues
- ๐ Server Not Found: Ensure the working directory path is correct
- ๐ ๏ธ Command Not Found: Make sure
bun
is installed and in PATH - ๐ Authentication Failed: Check environment variables are set correctly
- โฐ Token Expired: Re-authenticate using the login flow
- ๐ซ Permission Denied: Ensure the project folder has proper read/write permissions
๐ค Contributing
- ๐ด Fork the repository
- ๐ฟ Create a feature branch (
git checkout -b feature/new-tool
) - โ๏ธ Implement your changes
- ๐ก๏ธ Add proper error handling
- ๐ Update documentation
- ๐ค Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
โ ๏ธ Disclaimer
This software is for educational and personal use only. Trading involves substantial risk of loss and is not suitable for all investors. The developers are not responsible for any financial losses incurred through the use of this software. ๐ก๏ธ
๐ Support
- ๐ Issues - Report bugs via GitHub Issues
- ๐ Documentation - Check this README and code comments
- ๐ข Zerodha Support - Contact Zerodha for API-related issues
๐ Acknowledgments
- ๐ข Zerodha - Trading platform and API
- ๐ค MCP SDK - Model Context Protocol implementation
- ๐ TypeScript - Type safety and development experience
Made by Manik Lakhanpal ๐ฅ