PutrMCP

Agam77055/PutrMCP

3.1

If you are the rightful owner of PutrMCP and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

PutrMCP is a production-ready Model Context Protocol (MCP) Server designed for seamless integration with the Kite Connect trading API, providing access to Indian stock market data and trading capabilities.

Tools
3
Resources
0
Prompts
0

🚀 PutrMCP - Kite Connect MCP Server

A production-ready Model Context Protocol (MCP) Server for Kite Connect trading API integration. PutrMCP provides seamless access to Indian stock market data, options chains, portfolio management, and trading capabilities directly from Claude Desktop.

📋 Table of Contents

✨ Features

🔐 Authentication & Security

  • Persistent OAuth2 authentication with Kite Connect
  • Secure session management with Redis
  • Token refresh and validation

📊 Market Data

  • Real-time NIFTY spot prices and indices
  • Live options chains for NIFTY, BANKNIFTY, and individual stocks
  • Historical data with multiple timeframes
  • WebSocket-based real-time price updates

💼 Portfolio Management

  • Complete portfolio overview (holdings, positions, margins)
  • Real-time P&L tracking
  • Order history and status

🎯 Trading Capabilities ⚠️ Work In Progress

  • View orders and order history
  • Portfolio and position monitoring
  • Account margins and balance tracking
  • Note: Direct order placement through LLM is currently disabled for safety. Manual trading interface planned for future release.

Performance & Caching

  • Redis-based instrument caching for blazing-fast responses
  • Smart cache management with automatic expiry
  • Reduced API calls through intelligent data storage

🔧 Database Management

  • Populate Redis with 23,000+ options instruments
  • Organized storage by expiry dates
  • Cache statistics and health monitoring

🚀 Quick Start

Prerequisites

  • Node.js 18+: Download from nodejs.org
  • Redis: Local Redis server for caching
  • Kite Connect Account: Get API credentials from Kite Trade

1. Install Redis

# macOS (using Homebrew)
brew install redis
brew services start redis

# Ubuntu/Debian
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server

# Windows
# Download from https://redis.io/download
# Or use WSL with above Ubuntu commands
# Or Docker: docker run -d -p 6379:6379 redis:alpine

2. Clone & Setup Project

git clone https://github.com/Agam77055/PutrMCP
cd PutrMCP

# Install dependencies
npm install

# Copy environment template
cp .env.example .env

3. Configure Environment

Edit .env file with your credentials:

# .env file
KITE_API_KEY=your_kite_api_key_here
KITE_API_SECRET=your_kite_api_secret_here
PORT=3005
REDIS_URL=redis://localhost:6379
NODE_ENV=production

4. Build & Test

# Build TypeScript
npm run build

# Test the server (optional)
npm start

# Verify it's working
curl http://localhost:3005/health

🖥️ Claude Desktop Setup

1. Locate Claude Desktop Configuration File

Find your config file location:

  • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json
  • Linux: ~/.config/Claude/claude_desktop_config.json

2. Add MCP Server Configuration

If the file doesn't exist, create it first:

# macOS/Linux
mkdir -p ~/Library/Application\ Support/Claude/
touch ~/Library/Application\ Support/Claude/claude_desktop_config.json

# Or find your actual path
echo $HOME/Library/Application\ Support/Claude/claude_desktop_config.json

Add this configuration to claude_desktop_config.json:

{
  "mcpServers": {
    "PutrMCP": {
      "command": "node",
      "args": ["/FULL/PATH/TO/YOUR/PutrMCP/dist/index.js"],
      "env": {
        "KITE_API_KEY": "your_actual_kite_api_key",
        "KITE_API_SECRET": "your_actual_kite_api_secret",
        "REDIS_URL": "redis://localhost:6379",
        "PORT": "3005"
      }
    }
  }
}

⚠️ Important Path Notes:

  • Replace /FULL/PATH/TO/YOUR/PutrMCP/ with your actual project path
  • Use absolute paths, not relative paths like ./dist/index.js
  • Example: /Users/yourusername/Projects/PutrMCP/dist/index.js

4. Verify Configuration

# Make sure Redis is running
redis-cli ping
# Should return: PONG

# Make sure the built files exist
ls /path/to/your/PutrMCP/dist/index.js

# Test the MCP server manually (optional)
cd /path/to/your/PutrMCP
npm start

5. Restart Claude Desktop

  1. Completely quit Claude Desktop (not just close window)
  2. Reopen Claude Desktop
  3. Look for MCP server connection messages in the logs

6. First Time Setup in Claude

Once Claude Desktop restarts, start a new conversation and use:

Use the kite_login tool to authenticate with Kite Connect

This will give you a URL to complete OAuth authentication.

7. Verify It's Working

After authentication, test with:

Use the server_status tool to check if everything is working

You should see the server status with authentication details and cached data information.

🛠️ Available Tools

🔐 Authentication Tools

kite_login

Purpose: Start OAuth authentication with Kite Connect Parameters: None

{}
kite_complete_auth

Purpose: Complete OAuth flow with request token Parameters:

  • request_token (string): Token from Kite callback URL
kite_auth_status

Purpose: Check current authentication status Parameters: None


📊 Market Data Tools

get_nifty_spot

Purpose: Get current NIFTY 50 spot price and data Parameters: None

{}
get_weekly_options_chain

Purpose: Get NIFTY weekly options chain Parameters:

  • expiry (string, optional): Specific expiry date (YYYY-MM-DD) or "auto"
  • strike_range (number, optional): Strike range around ATM (default: 500)
{
  "expiry": "2024-01-25",
  "strike_range": 1000
}
get_live_options_data

Purpose: Get live options chain with real-time prices Parameters:

  • underlying (string): Underlying symbol (default: "NIFTY")
  • expiry (string): Expiry date (YYYY-MM-DD)
{
  "underlying": "NIFTY",
  "expiry": "2024-01-25"
}
get_stock_data

Purpose: Get comprehensive stock quote data Parameters:

  • symbol (string): Stock symbol (e.g., RELIANCE, TCS, INFY)
  • exchange (string, optional): Exchange (NSE/BSE, default: NSE)
{
  "symbol": "RELIANCE",
  "exchange": "NSE"
}
get_stock_options ⚠️ Work In Progress

Purpose: Get options chain for any stock Parameters:

  • symbol (string): Stock symbol (e.g., RELIANCE, BANKNIFTY)
  • expiry (string): Options expiry date (YYYY-MM-DD)
  • strike_range (number, optional): Strike range around current price (default: 500)
{
  "symbol": "RELIANCE",
  "expiry": "2024-01-25",
  "strike_range": 500
}
get_historical_data

Purpose: Get historical price data Parameters:

  • instrument_token (string, optional): Instrument token (default: NIFTY)
  • from_date (string): Start date (YYYY-MM-DD)
  • to_date (string): End date (YYYY-MM-DD)
  • interval (string, optional): Timeframe (day, 5minute, 15minute, etc.)
{
  "instrument_token": "256265",
  "from_date": "2024-01-01",
  "to_date": "2024-01-31",
  "interval": "day"
}

💼 Portfolio & Trading Tools

get_portfolio

Purpose: Get complete portfolio with holdings, positions, and margins Parameters: None

{}
get_positions

Purpose: Get current trading positions Parameters: None

get_margins

Purpose: Get account margins and available funds Parameters: None

get_orders

Purpose: Get all orders (pending, completed, cancelled) Parameters: None

place_order

Purpose: Place a trading order Parameters:

  • tradingsymbol (string): Trading symbol
  • exchange (string, optional): Exchange (NSE/NFO/BSE, default: NSE)
  • transaction_type (string): BUY or SELL
  • quantity (number): Quantity to trade
  • order_type (string, optional): MARKET, LIMIT, SL, SL-M (default: MARKET)
  • product (string, optional): CNC, MIS, NRML (default: MIS)
  • price (number, optional): Price for LIMIT orders
  • trigger_price (number, optional): Trigger price for SL orders
{
  "tradingsymbol": "RELIANCE",
  "transaction_type": "BUY",
  "quantity": 1,
  "order_type": "MARKET",
  "product": "CNC"
}

🔧 Database & Management Tools

get_instruments

Purpose: Fetch and cache instruments for database population Parameters:

  • exchange (string, optional): Exchange (NSE, NFO, BSE, MCX, default: NFO)
  • refresh_cache (boolean, optional): Force refresh cache (default: false)
  • save_to_db (boolean, optional): Save to Redis database (default: true)
{
  "exchange": "NFO",
  "refresh_cache": false,
  "save_to_db": true
}
server_status

Purpose: Get comprehensive server health and status information Parameters: None

{}

Health Checks

Both services include comprehensive health checks:

  • Application: HTTP endpoint monitoring
  • Redis: Redis ping monitoring

🔧 Manual Installation

Prerequisites

  • Node.js 18+
  • Redis server
  • TypeScript

Installation Steps

# Install dependencies
npm install

# Build TypeScript
npm run build

# Start Redis (separate terminal)
redis-server

# Configure environment
cp .env.example .env
# Edit .env with your credentials

# Start the server
npm start

💡 API Usage Examples

Getting Started Workflow

# 1. Check server status
server_status

# 2. Authenticate with Kite
kite_login
# Follow OAuth flow

# 3. Populate instrument database
get_instruments -> {"exchange": "NFO", "save_to_db": true}

# 4. Get NIFTY data
get_nifty_spot

# 5. Get options chain
get_stock_options -> {
  "symbol": "NIFTY",
  "expiry": "2024-01-25",
  "strike_range": 1000
}

Portfolio Management

# Check portfolio
get_portfolio

# View positions
get_positions

# Check available margins
get_margins

# View order history
get_orders

Market Data Analysis

# Stock analysis
get_stock_data -> {"symbol": "RELIANCE"}

# Options analysis
get_stock_options -> {
  "symbol": "RELIANCE", 
  "expiry": "2024-01-25"
}

# Historical data
get_historical_data -> {
  "from_date": "2024-01-01",
  "to_date": "2024-01-31",
  "interval": "day"
}

🏗️ Architecture

Core Components

├── index.ts              # Entry point & server initialization
├── mcpServer.ts          # Main MCP server with tool handlers
├── authManager.ts        # OAuth2 authentication management
├── storageManager.ts     # Redis operations & session storage
├── kiteApiService.ts     # Kite Connect API integration
├── dataTransformer.ts    # Data formatting & transformation
├── instrumentCache.ts    # Options caching & retrieval
└── marketDataEngine.ts   # Real-time WebSocket data

Data Flow

  1. Authentication: OAuth2 flow → Redis session storage
  2. Market Data: Kite API → Redis cache → Live quotes
  3. Real-time Updates: WebSocket → In-memory → Client
  4. Trading: Validation → Kite API → Confirmation

Caching Strategy

  • Instruments: 23,000+ options cached by expiry (7 days TTL)
  • Sessions: User authentication (24 hours TTL)
  • Market Data: Live quotes with WebSocket updates
  • API Responses: Smart caching with retry logic

🔍 Troubleshooting

Common Issues

Authentication Problems
# Check authentication status
server_status

# Re-authenticate if expired
kite_login
No Options Data
# Populate instrument database
get_instruments -> {"exchange": "NFO", "refresh_cache": true}

# Check available expiries
server_status
API Rate Limits

The server includes automatic retry logic with exponential backoff for API rate limits.

Health Monitoring

# Application health
curl http://localhost:3005/health

# Detailed server status
server_status

📈 Performance

Capacity

  • Concurrent Users: 100+ simultaneous connections
  • Cached Instruments: 23,000+ options instruments
  • Uptime: 99.9% with health checks and auto-restart

🤝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

📄 License

This project is licensed under the MIT License - see the file for details.

⚠️ Disclaimer

This software is for educational and informational purposes only. Trading in financial markets involves substantial risk and may not be suitable for all investors. The authors and contributors are not responsible for any financial losses incurred through the use of this software.

🙋‍♂️ Support

  • Documentation: Check this README and inline code comments
  • Issues: Report bugs and feature requests via GitHub Issues
  • Discussions: Community support via GitHub Discussions