Market-Intelligence-MCP-Server

TannaPrasanthkumar/Market-Intelligence-MCP-Server

3.2

If you are the rightful owner of Market-Intelligence-MCP-Server 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.

The Market Intelligence MCP Server is an AI-powered backend service designed for market intelligence and financial news analysis, utilizing Model Context Protocol (MCP) integration.

Tools
2
Resources
0
Prompts
0

Market Intelligence MCP Server 🚀

AI-powered backend service for market intelligence and financial news analysis using MCP (Model Context Protocol) integration.

📋 Overview

This project implements a backend-only service that runs on an MCP server architecture, integrating AI capabilities with real-time market data tools. It provides context-aware responses to market and financial questions through a RESTful API.

Key Features

MCP Server Architecture - Built on Model Context Protocol for tool integration
AI-Powered Responses - Using Google Gemini 2.0 Flash for intelligent answers
Real-Time Market Data - Stock prices, company info via Yahoo Finance
Financial News - Latest news from multiple sources (NewsAPI + RSS feeds)
Context Management - Session-based conversation memory
Streaming Support - Real-time streaming responses (bonus feature)
Async Architecture - High-performance async/await implementation


🏗️ Architecture

┌─────────────┐
│   Client    │
│  (curl/API) │
└──────┬──────┘
       │ HTTP Request
       ▼
┌─────────────────────────────────┐
│      FastAPI Server             │
│  ┌──────────────────────────┐  │
│  │   MCP Integration Layer  │  │
│  └────────┬─────────────────┘  │
│           │                     │
│  ┌────────▼─────────┐          │
│  │  AI Model        │          │
│  │  (Gemini 2.0)    │          │
│  └──────────────────┘          │
└───────────┬─────────────────────┘
            │
    ┌───────┴───────┐
    ▼               ▼
┌─────────┐   ┌──────────┐
│ MCP     │   │ MCP News │
│ Stock   │   │ Fetcher  │
│ Tool    │   │ Tool     │
└────┬────┘   └────┬─────┘
     │             │
     ▼             ▼
┌─────────┐   ┌──────────┐
│ Yahoo   │   │ NewsAPI/ │
│ Finance │   │ RSS Feeds│
└─────────┘   └──────────┘

🚀 Quick Start

Prerequisites

  • Python 3.9+
  • pip
  • Google Gemini API key (free)

Installation

  1. Clone and setup:
git clone <your-repo>
cd market-intel-mcp
  1. Install dependencies:
pip install -r requirements.txt
  1. Configure environment:
cp .env.example .env
# Edit .env and add your API keys
  1. Verify setup:
python setup_checker.py
  1. Start the server:
python main.py

Server will start on http://localhost:8000


🔑 API Keys Setup

Required Keys:

  1. Google Gemini API (FREE)

  2. Service API Key (Your own password)

    • Generate: python -c "import secrets; print(secrets.token_hex(32))"
    • Add to .env: SERVICE_API_KEY=your-secure-key

Optional Keys:

  1. NewsAPI (FREE - 100 req/day)

See API_KEYS_GUIDE.md for detailed instructions.


📡 API Endpoints

Base URL

http://localhost:8000

1. Health Check

curl http://localhost:8000/health

2. Query Endpoint (Main)

curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-service-api-key" \
  -d '{
    "message": "What is the current price of Apple stock?"
  }'

Response:

{
  "session_id": "abc123...",
  "answer": "Based on real-time data, Apple (AAPL) is currently trading at $185.50...",
  "tool_data_used": ["stock_data"],
  "timestamp": 1728738000.0
}

3. Streaming Endpoint (Bonus)

curl -X POST http://localhost:8000/query/stream \
  -H "Content-Type: application/json" \
  -H "X-API-Key: your-service-api-key" \
  -d '{
    "message": "Give me latest stock market news"
  }' \
  --no-buffer

4. Conversation History

curl http://localhost:8000/sessions/{session_id}/history \
  -H "X-API-Key: your-service-api-key"

5. Clear Session

curl -X POST http://localhost:8000/sessions/{session_id}/clear \
  -H "X-API-Key: your-service-api-key"

6. List MCP Tools

curl http://localhost:8000/mcp/tools \
  -H "X-API-Key: your-service-api-key"

🧠 How Context is Preserved

Session-Based Memory

  • Each conversation gets a unique session_id
  • Messages stored in-memory with timestamps
  • Last 6 exchanges kept in context (configurable via MAX_HISTORY)
  • Automatic cleanup after 30 minutes of inactivity

Context Flow:

User Query 1 → AI Response 1 → Stored in session
User Query 2[Previous context + Query 2] → AI Response 2

Implementation:

  • In-memory store: CONTEXTS dictionary indexed by session_id
  • Thread-safe: Async locks per session
  • Persistent: Context maintained across multiple queries in same session

🛠️ MCP Server Configuration

What is MCP?

MCP (Model Context Protocol) is Anthropic's standard for connecting AI models to external tools and data sources.

Our MCP Implementation:

Tools Exposed:

  1. Stock Data Tool

    • get_stock_price() - Current price & metrics
    • get_historical_data() - Historical prices
    • get_company_info() - Company details
  2. News Fetcher Tool

    • get_latest_news() - Search financial news
    • get_market_news() - General market updates
    • get_company_news() - Company-specific news
    • get_economic_news() - Economic indicators

MCP Server Config:

# Located in mcp_server.py
Server Name: market-intelligence-mcp
Version: 1.0.0
Protocol: stdio-based MCP
Tools: 2 (Stock Data, News Fetcher)

Tool Integration:

The FastAPI layer automatically calls MCP tools based on query analysis:

  • Keywords like "price", "stock" → Triggers stock_tool
  • Keywords like "news", "latest" → Triggers news_tool
  • Results passed to AI for intelligent synthesis

📚 Tech Stack & Libraries

Core Framework:

  • FastAPI - Modern async web framework
  • Uvicorn - ASGI server
  • Pydantic - Data validation

AI & LLM:

  • LangChain - LLM orchestration
  • Google Generative AI - Gemini 2.0 Flash model

MCP Protocol:

  • mcp - Model Context Protocol implementation
  • anthropic-mcp - Anthropic's MCP utilities

Market Data:

  • yfinance - Yahoo Finance API (stock data)
  • newsapi-python - NewsAPI client
  • feedparser - RSS feed parsing

Utilities:

  • python-dotenv - Environment management
  • httpx / aiohttp - Async HTTP clients
  • asyncio - Async/await support

📁 Project Structure

market-intel-mcp/
├── main.py                    # FastAPI application + MCP integration
├── mcp_server.py             # Standalone MCP server implementation
├── tools/
│   ├── __init__.py           # Tools package
│   ├── stock_data.py         # Stock market data tools
│   └── news_fetcher.py       # Financial news tools
├── requirements.txt          # Python dependencies
├── .env                      # Environment variables (you create this)
├── .env.example             # Environment template
├── setup_checker.py         # Setup verification script
├── README.md                # This file
├── API_KEYS_GUIDE.md       # Detailed API key instructions
└── market_intel.log        # Application logs

🧪 Testing

Run Setup Checker:

python setup_checker.py

Test Endpoints:

Basic Query:

# Replace YOUR_API_KEY with your SERVICE_API_KEY from .env
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{"message": "What is the price of Microsoft stock?"}'

Stock + News Query:

curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{"message": "Tell me about Tesla stock and recent news"}'

Streaming Test:

curl -X POST http://localhost:8000/query/stream \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{"message": "Latest market news"}' \
  --no-buffer

With Session Context:

# First query
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{"message": "What is Apple stock price?"}' \
  | jq -r '.session_id' > session.txt

# Follow-up (uses context)
SESSION_ID=$(cat session.txt)
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d "{\"message\": \"How has it changed this week?\", \"session_id\": \"$SESSION_ID\"}"

🚢 Deployment

Option 1: Railway (Recommended)

# Install Railway CLI
npm install -g @railway/cli

# Login
railway login

# Deploy
railway up

Option 2: Render

  1. Connect GitHub repo
  2. Select "Web Service"
  3. Build command: pip install -r requirements.txt
  4. Start command: uvicorn main:app --host 0.0.0.0 --port $PORT
  5. Add environment variables from .env

Option 3: DigitalOcean App Platform

  1. Create new app from GitHub
  2. Configure build: pip install -r requirements.txt
  3. Configure run: python main.py
  4. Add environment variables

Environment Variables for Deployment:

Ensure these are set in your hosting platform:

  • GOOGLE_API_KEY
  • SERVICE_API_KEY
  • NEWS_API_KEY (optional)
  • PORT (usually auto-set by platform)

📊 Performance & Scaling

  • Async Architecture: All I/O operations are non-blocking
  • Session Management: Automatic cleanup prevents memory leaks
  • Rate Limiting: Respects API provider limits
  • Caching: Consider adding Redis for production use
  • Horizontal Scaling: Stateless design allows multiple instances

🐛 Troubleshooting

"Invalid API Key" error:

  • Check .env file has correct keys
  • Ensure no extra spaces in .env
  • Run python setup_checker.py

"Model not initialized" error:

  • Verify GOOGLE_API_KEY is valid
  • Check internet connection
  • Try regenerating API key

No stock data returned:

  • Yahoo Finance may be temporarily down
  • Check ticker symbol is correct (uppercase)
  • Try a different stock symbol

News not loading:

  • If NewsAPI key not provided, RSS feeds are used (may be slower)
  • Check NEWS_API_KEY if set
  • RSS feeds may have rate limits

📄 License

MIT License - See LICENSE file for details


🤝 Contributing

This is an internship project, but suggestions are welcome!

  1. Fork the repository
  2. Create feature branch
  3. Make changes
  4. Submit pull request

📞 Support

For issues or questions:

  • Check API_KEYS_GUIDE.md for setup help
  • Run python setup_checker.py to diagnose issues
  • Review logs in market_intel.log

🎯 Project Requirements Met

✅ Python backend service
✅ MCP server implementation
✅ AI chatbot integration (Google Gemini)
✅ Context preservation (session-based memory)
✅ Market Data