Zerodha Kite MCP Server

Zerodha Kite MCP Server

Implements a Model Context Protocol server that connects with Zerodha Kite API, allowing users to buy/sell stocks and retrieve holdings and positions information.

Category
访问服务器

README

Zerodha Kite MCP Server

This project implements an MCP (Model Context Protocol) server that interacts with the Zerodha Kite API, allowing you to perform trading actions like buying and selling stocks, and fetching your holdings and positions.

Prerequisites

  1. Node.js and npm/yarn: Ensure you have Node.js installed. This project uses typescript and esbuild for building.
  2. Zerodha Kite Developer Account: You need an account with Zerodha and access to their developer API.

Setup Instructions

1. Create a Kite App

  • Go to https://developers.kite.trade/create and create a new app.
  • During app creation, you can use any redirection URL (e.g., https://localhost:3000/api/callback/userauth). This URL is primarily used for the initial authentication flow.
  • Note down the API key and API secret provided after app creation.

2. Configure API Keys in the Project

  • Open the index.ts file.
  • Replace "your_api_key" with your actual Kite App API key.
    const apiKey = "YOUR_ACTUAL_API_KEY"; // Replace with your API key
    
  • Important: The apiSecret is needed for the initial access token generation. It's commented out in the index.ts file by default. You will need to uncomment it and add your API secret when generating the access token for the first time.
    // const apiSecret = "YOUR_ACTUAL_API_SECRET"; // Uncomment and replace for first-time token generation
    

3. Obtain an Access Token

The access token is required for the server to make authenticated calls to the Kite API. It needs to be generated once and can then be reused.

  • Step 3a: Get the Login URL
    • In index.ts, temporarily uncomment the getLoginUrl function:
      // async function getLoginUrl() {
      //     return kc.getLoginURL();
      // }
      
    • You'll also need to call this function. You can add a line like console.log(await getLoginUrl()); at the end of the file or run it in a separate script.
    • Run the modified index.ts (e.g., using ts-node index.ts or by building and running the JS output). This will print a login URL to your console.
  • Step 3b: Authorize and Get Request Token
    • Open the printed login URL in your browser.
    • Log in with your Zerodha credentials and authorize the app.
    • After successful authorization, you will be redirected to your specified redirect_url. The URL will contain a request_token parameter (e.g., https://localhost:3000/api/callback/userauth?request_token=YOUR_REQUEST_TOKEN).
    • Copy this request_token.
  • Step 3c: Generate Access Token
    • In index.ts, uncomment the getAccessToken function and ensure your apiSecret is correctly set:
      // async function getAccessToken(requestToken: string) {
      //     const response = await kc.generateSession(requestToken, apiSecret);
      //     console.log(response.access_token);
      // }
      
    • Call this function with the request_token you obtained. For example, add await getAccessToken("YOUR_REQUEST_TOKEN"); to the script or run it interactively.
    • Run the script. This will print your access_token to the console.
  • Step 3d: Set the Access Token in index.ts
    • Copy the generated access_token.
    • Paste it into the access_token variable in index.ts:
      const access_token = "YOUR_GENERATED_ACCESS_TOKEN"; // Replace with your access token
      
    • Security Note: After generating the access token, you can (and should) comment out or remove the getLoginUrl and getAccessToken functions, and especially the apiSecret from index.ts to avoid accidental exposure. The access_token is long-lived.

4. Install Dependencies

Navigate to the project root directory in your terminal and run:

npm install
# or
yarn install

This will install kiteconnect, @modelcontextprotocol/sdk, zod, and other necessary dependencies.

5. Build the Project

The project uses TypeScript. You need to compile it to JavaScript. A common way is to use esbuild as suggested by the MCP server setup. If you have a build script in your package.json (e.g., esbuild trader.ts --bundle --outfile=dist/trader.js --platform=node --format=esm), run:

npm run build
# or
yarn build

This will typically create a dist directory with the compiled trader.js file. Make sure the output path matches the one you will use in the MCP server configuration (see below).

Running the MCP Server

Once the setup is complete and the project is built, the MCP server can be started. The trader.ts (compiled to dist/trader.js) is the entry point for the MCP server.

The server listens for commands via standard input/output (stdio) when configured with an MCP client like Cursor.

Configuring with Cursor

To use this trader bot as an MCP server in Cursor:

  1. Go to Cursor settings (Cmd/Ctrl + ,).

  2. Navigate to Extensions -> MCP.

  3. Click on Edit in settings.json for Model Context Protocol: Servers.

  4. Add the following configuration:

    {
      "mcpServers": {
        "trader": {
          "command": "node",
          "args": ["/path/to/your/Zerodha-MCP/dist/trader.js"] // Ensure this path is correct
        }
      }
    }
    

    Important: Replace /path/to/your/Zerodha-MCP/dist/trader.js with the absolute path to the compiled trader.js file on your system. For example, if your username is user and the project is in Development/Zerodha-MCP, the path would be /Users/user/Development/Zerodha-MCP/dist/trader.js.

Available MCP Tools

The server exposes the following tools that can be called by an MCP client:

  • trader.add

    • Description: A simple tool to add two numbers.
    • Parameters:
      • a (number): The first number.
      • b (number): The second number.
    • Returns: The sum of a and b.
  • trader.sellStock

    • Description: Places a market sell order for a given stock.
    • Parameters:
      • tradingsymbol (string): The trading symbol of the stock (e.g., "INFY", "RELIANCE").
      • quantity (number): The number of shares to sell.
    • Returns: A confirmation message "Stock sold successfully" or an error if the transaction fails.
    • Note: This uses PRODUCT_CNC (Cash and Carry, for delivery-based trades) and EXCHANGE_NSE. The order tag is automatically generated and incremented.
  • trader.buyStock

    • Description: Places a market buy order for a given stock.
    • Parameters:
      • tradingsymbol (string): The trading symbol of the stock.
      • quantity (number): The number of shares to buy.
    • Returns: A confirmation message "Stock bought successfully" or an error if the transaction fails.
    • Note: This uses PRODUCT_CNC and EXCHANGE_NSE. The order tag is automatically generated and incremented.
  • trader.getPositions

    • Description: Fetches your current open positions.
    • Parameters: None.
    • Returns: A JSON string representing your current positions.
  • trader.getHoldings

    • Description: Fetches your current holdings (stocks in your demat account).
    • Parameters: None.
    • Returns: A JSON string representing your holdings.

Project Structure Highlights

  • index.ts: Contains the core Kite Connect API interaction logic, including setting API keys, access tokens, and functions for buying/selling stocks, and fetching profile, holdings, and positions. It also handles persisting an orderTagCounter in counter.json to ensure unique order tags.
  • trader.ts: Sets up the MCP server using @modelcontextprotocol/sdk. It defines the tools exposed by the server and maps them to the functions in index.ts.
  • counter.json: Automatically created in the same directory as index.js (or its compiled output) to store and persist the last used order tag number. This ensures that order tags are unique across server restarts.

Development Notes

  • Order Tagging: The system uses an incremental counter (orderTagCounter in index.ts, persisted in counter.json) to tag orders. This helps in identifying orders.
  • Error Handling: Basic error handling is implemented (logging to console). You might want to expand this for more robust error reporting through the MCP.
  • Initial Setup: The init() function in index.ts is called automatically when index.ts is imported. It loads the orderTagCounter and sets the Kite Connect access token.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选