🚀 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.3 min read

Boost Developer Speed with Google Cloud CLI & Claude AI

Accelerate software development with Google Cloud CLI and Claude AI. Automate tasks, deploy faster, and improve workflows using intelligent tools.

Aneh Thakur
Aneh Thakur.4 min read

India’s Rise in the AI Era: Shaping the Future as a Global Leader

India is becoming a global AI leader through initiatives like IndiaAI, indigenous LLMs like Sarvam AI and BharatGPT, and rapid startup growth. Learn how AI is shaping India’s digital and inclusive future.

Aneh Thakur
Aneh Thakur.5 min read

AI and Beginner Developers: A Double-Edged Sword in Programming

AI tools are transforming how beginner developers learn to code. Discover the benefits, risks of over-reliance, and best practices to use AI effectively in your programming journey.

Aneh Thakur
Aneh Thakur.3 min read

Mastering Google AI Mode: A Guide for SEO Professionals in the Age of Answer Engines

Learn how Google AI Mode is changing search. Discover how to adapt your SEO strategy with Answer Engine Optimization (AEO) for AI-powered results.

SWATI BARWAL
SWATI BARWAL.3 min read

🚀 OpenAI’s $3 Billion Windsurf Acquisition: What It Really Means

OpenAI's $3 billion Windsurf deal shows that developer tools—not chatbots—are the real future of AI. Here’s what this means for coders, jobs, and the evolving dev landscape.

.

Advertisement

Advertisement
Built on Koows