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

people

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:

  1. Create a Developer AccountVisit: https://developers.kite.trade

    • Register your app (e.g., "Trade Assistant")

    • Note your API Key and API Secret

  2. Authenticate via OAuth

    • Generate a Request Token by logging in with your Zerodha credentials

    • Exchange it for an Access Token

  3. Install Zerodha Node.js SDK

bash
npm install kiteconnect
  1. Sample Kite Connect Setup

js
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

bash
npm install express kiteconnect @model-context-protocol/sdk zod

📄 server.ts (Complete Working Code)

ts
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

  1. Install Claude (MCP-enabled desktop version)

  2. Enable Developer Mode from settings

  3. Edit Claude’s MCP Config to include your server:

json
{
  "servers": [
    {
      "name": "zerodha_mcp",
      "command": "npx tsx server.ts"
    }
  ]
}
  1. 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


🔗 Resources & Links

More Stories from

Aneh Thakur
Aneh Thakur.4 min read

React Native 0.78 Unveiled: New Features, Changes, and Benefits You’ll Love 🚀

Discover React Native 0.78! From React 19 support to Android vector drawables and better iOS integration, explore the latest features, changes, and benefits with examples to make app development faster and smoother. 🌟

.
Aneh Thakur
Aneh Thakur.4 min read

🚀 Encore.ts: Blazing Fast Backend Powerhouse – 9x Faster Than Express.js & 3x Faster Than Bun + Zod

Discover why Encore.ts outshines Express.js and Bun + Zod with 9x and 3x faster performance, respectively. Explore sample code, speed benchmarks, and see how this TypeScript framework redefines backend efficiency! ⚡

.
Aneh Thakur
Aneh Thakur.4 min read

Trump Unveils U.S. Crypto Strategic Reserve: Bitcoin and Altcoins Surge

Donald Trump announces a U.S. Crypto Strategic Reserve featuring Bitcoin, Ethereum, XRP, Solana, and Cardano, sparking a $300B market rally. Explore the implications and trends as of March 3, 2025.

.
Aneh Thakur
Aneh Thakur.4 min read

Prototype Your Idea in Under an Hour Using AI

Learn to create working prototypes in under an hour using AI tools like Claude and Bolt. Ideal for designers and entrepreneurs with minimal coding skills.

Aneh Thakur
Aneh Thakur.3 min read

How X’s New Grok AI Tools Make Ad Creation and Analysis a Breeze

Discover X’s latest AI-powered features—Prefill with Grok and Analyze Campaign with Grok. Learn how these tools simplify ad creation, boost campaign performance, and help advertisers save time in 2025.

Built on Koows