🚀 How to Build an MCP Server for Zerodha – AI-Powered Trading with Claude

Aneh Thakur
·4 min read
Introduction
The future of trading is here—and it speaks your language.
With Claude, an advanced AI by Anthropic, and Zerodha, India’s leading brokerage, you can now place trades, check your stock portfolio, and run custom strategies—all by simply typing a message.
Thanks to MCP (Model Context Protocol), an emerging standard for connecting LLMs to real-world APIs, we can bridge the gap between natural language and actual trading.
In this guide, you’ll learn how to:✅ Build a working MCP server using Node.js✅ Connect it to Zerodha’s Kite API✅ Enable Claude to run real trade commands
🧠 What is MCP (Model Context Protocol)?
MCP is a protocol that lets large language models (LLMs) like Claude securely and predictably interact with external systems via API-based tools.
Why Use MCP with Zerodha?
🎯 Natural Language Trading: Place orders like “Buy 5 shares of Infosys”.
⚡ Faster Execution: Automate actions like selling top performers.
🧑💻 Zero Coding Needed: End-users don’t need to know how to write scripts.
MCP is already being used with tools like GitHub, Slack, and Kubernetes—and now, we’ll adapt it for stock trading.
🔌 Part 1: Set Up Zerodha API (Kite Connect)
Zerodha offers a developer API called Kite Connect. This API allows programmatic access to your trading account.
✅ Steps to Get Started:
Create a Developer AccountVisit: https://developers.kite.trade
Register your app (e.g., "Trade Assistant")
Note your API Key and API Secret
Authenticate via OAuth
Generate a Request Token by logging in with your Zerodha credentials
Exchange it for an Access Token
Install Zerodha Node.js SDK
npm install kiteconnectSample Kite Connect Setup
const { KiteConnect } = require("kiteconnect");
const kc = new KiteConnect({ api_key: "YOUR_API_KEY" });
kc.setAccessToken("YOUR_ACCESS_TOKEN");⚙️ Part 2: Build the MCP Server (Node.js)
We’ll now expose trading actions—like buy, sell, and show portfolio—to Claude using MCP tools.
🛠️ Install Required Packages
npm install express kiteconnect @model-context-protocol/sdk zod📄 server.ts (Complete Working Code)
import express from 'express';
import { MCPServer } from '@model-context-protocol/sdk';
import { z } from 'zod';
import { KiteConnect } from 'kiteconnect';
// Zerodha Kite API setup
const api_key = "YOUR_API_KEY";
const access_token = "YOUR_ACCESS_TOKEN";
const kc = new KiteConnect({ api_key });
kc.setAccessToken(access_token);
// Helper to place buy/sell order
async function placeOrder(stock: string, quantity: number, type: "BUY" | "SELL") {
return kc.placeOrder("regular", {
exchange: "NSE",
tradingsymbol: stock,
transaction_type: type,
quantity,
order_type: "MARKET",
product: "CNC",
});
}
// Create express app and MCP server
const app = express();
const server = new MCPServer({ expressApp: app });
// MCP Tool 1: Buy Stock
server.tool({
name: "buy_stock",
title: "Buy a stock on Zerodha",
description: "Places a BUY order via Zerodha.",
input: z.object({
stock: z.string(),
quantity: z.number(),
}),
handler: async ({ stock, quantity }) => {
await placeOrder(stock, quantity, "BUY");
return { contents: `✅ Bought ${quantity} shares of ${stock}` };
},
});
// MCP Tool 2: Sell Stock
server.tool({
name: "sell_stock",
title: "Sell a stock on Zerodha",
description: "Places a SELL order via Zerodha.",
input: z.object({
stock: z.string(),
quantity: z.number(),
}),
handler: async ({ stock, quantity }) => {
await placeOrder(stock, quantity, "SELL");
return { contents: `✅ Sold ${quantity} shares of ${stock}` };
},
});
// MCP Tool 3: Show Portfolio
server.tool({
name: "show_portfolio",
title: "Show my holdings",
description: "Displays current Zerodha holdings.",
handler: async () => {
const holdings = await kc.getHoldings();
return { contents: JSON.stringify(holdings, null, 2) };
},
});
// Start server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`🚀 MCP server running on http://localhost:${PORT}`);
});
🤖 Part 3: Connect Claude to Your MCP Server
Install Claude (MCP-enabled desktop version)
Enable Developer Mode from settings
Edit Claude’s MCP Config to include your server:
{
"servers": [
{
"name": "zerodha_mcp",
"command": "npx tsx server.ts"
}
]
}
Restart Claude
It will auto-discover tools like buy_stock, sell_stock, and show_portfolio.
✅ Testing: Example Commands for Claude
You can now talk to Claude like this:
💸 "Buy 10 shares of INFY"
📉 "Sell 5 shares of TCS"
📊 "Show my current holdings"
Claude will:
Match the natural language to the MCP tool
Convert it into a valid API call
Execute and return the result 🎉
⚠️ Caveats & Improvements
Limitation | Suggestion |
|---|---|
🧾 Stock Symbol Confusion | Use a lookup API or alias map |
🔒 Access Token Expiry | Automate token refresh or store securely |
💹 Real-Time Data | Subscribe to Zerodha’s historical data APIs |
🧠 Custom Strategy | Add logic for auto-buy/sell based on trends |
💡 Future Ideas:
“Buy top gainer of the day” tool
Auto-sell on stop-loss
Mutual Fund support
🎯 Conclusion
You’ve just built a fully functional AI-powered trading assistant using Claude and Zerodha!
Thanks to Model Context Protocol, Claude can:
Place trades using just text
Analyze portfolios
Execute smart strategies in real-time
This architecture can easily be adapted for:
GitHub automation
DevOps (e.g., Kubernetes control)
Data analysis pipelines
CRM integrations




