finnhub-mcp

SalZaki/finnhub-mcp

3.2

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

The MCP FinnHub Server is a lightweight server that integrates with Finnhub’s financial data APIs using Model Context Protocol (MCP) and Server-Sent Events (SSE).

Build Status codecov License: MIT .NET Architecture MCP Commitizen friendly GitHub issues with bug label GitHub Repo stars

⚠️ This repository is under active development. The service will be live soon. Stay tuned! ⚠️

πŸ‘‹ Welcome to Finnhub MCP Server

🎯 Project Overview

A robust Model Context Protocol (MCP) Server that integrates with Finnhub's institutional-grade financial data APIs. Provides both Server-Sent Events (SSE) and Standard Input/Output (STDIO) transport protocols for streaming live financial data with modern .NET practices and Finnhub API best practices.

πŸš€ Key Features

  • βœ… Symbol Search Tool with validated and sanitized user input
  • βœ… Finnhub API Rate Limiting
    • Respects free tier limits (60 requests/minute)
    • Implements exponential backoff for 429 responses
    • Configurable rate limiting for different subscription tiers
  • βœ… Robust Input Validation
    • Query & exchange inputs sanitized using regex patterns
    • Length and pattern constraints enforced at runtime and via JSON Schema
    • Symbol validation against Finnhub's supported formats
  • βœ… Secure by Default
    • Actively defends against common injection vectors (<script>, SQL-style, etc.)
    • Allowed character sets enforced through schema and code
    • API key stored securely via environment variables
  • βœ… Resilient HTTP Communication
    • Typed HttpClient with retry & circuit breaker policies (via Polly)
    • Connection pooling with SocketsHttpHandler
    • Automatic retry with jitter for failed requests
  • βœ… WebSocket Support (Coming Soon)
    • Real-time streaming via Finnhub WebSocket API
    • Automatic reconnection handling
    • Subscription management for multiple symbols

πŸ“Š Finnhub API Integration & Best Practices

This server implements Finnhub's recommended best practices:

Rate Limiting

  • Free Tier: 60 requests/minute with automatic throttling
  • Premium Tiers: Configurable limits based on your subscription
  • Implements exponential backoff for rate limit responses (HTTP 429)
  • Request queuing to prevent API limit violations

Error Handling

  • Comprehensive error handling for all Finnhub API responses
  • Graceful degradation when API is unavailable
  • Retry logic with exponential backoff for transient failures
  • Proper handling of 401 (Unauthorized) and 429 (Rate Limit) responses

Data Validation

  • Input sanitization for all symbol and parameter inputs
  • Validates symbols against Finnhub's supported formats
  • Exchange code validation for international markets
  • Query parameter encoding to prevent injection attacks

Performance Optimization

  • HTTP connection pooling and reuse
  • Efficient JSON deserialization with System.Text.Json
  • Async/await patterns throughout for non-blocking operations
  • Memory-efficient streaming for large datasets

🚧 Available & Upcoming MCP Tools

βœ… Currently Available

  • Symbol Search Tool β€” search for stock symbols with fuzzy matching

πŸ”„ In Development

  • Real-Time Quote Tool β€” live prices for stock, forex & crypto
  • Company Profile Tool β€” detailed company information and metrics
  • Basic Financial Tool β€” key financial metrics and ratios

πŸ“‹ Planned Features

  • Advanced Fundamentals Tool β€” comprehensive financial statements
  • Earnings Calendar Tool β€” track earnings release dates and estimates
  • News & Sentiment Tool β€” company news with sentiment analysis
  • Insider Trading Tool β€” insider transaction data
  • Market Status Tool β€” trading hours and market holidays
  • Technical Indicators β€” RSI, MACD, moving averages
  • Economic Data Tool β€” GDP, inflation, employment data
  • Crypto Data Tool β€” cryptocurrency prices and market data

πŸš€ Getting Started

πŸ“‹ Prerequisites

πŸ”‘ Getting Your Finnhub API Key

  1. Visit Finnhub.io and create a free account
  2. Navigate to your Dashboard
  3. Copy your API key from the dashboard
  4. Note: Free tier provides 60 requests/minute and access to basic market data

πŸ“¦ Installation

git clone https://github.com/SalZaki/finnhub-mcp.git
cd finnhub-mcp
dotnet restore

πŸ” API Key Configuration

Security Note: Never commit your API key to version control. Always use environment variables or secure configuration management.

Option 1: Environment Variable (Recommended)

macOS/Linux:

export FINNHUB_API_KEY="your_api_key_here"

Windows PowerShell:

$env:FINNHUB_API_KEY="your_api_key_here"

Windows Command Prompt:

set FINNHUB_API_KEY=your_api_key_here
Option 2: .env File (Development Only)

Create a .env file in the root directory:

echo "FINNHUB_API_KEY=your_api_key_here" > .env

Important: The .env file is automatically loaded during development but should never be committed to version control.

πŸš€ Running the Server

HTTP Transport (Default)
dotnet run --project src/FinnHub.MCP.Server --urls http://localhost:5101
STDIO Transport
dotnet run --project src/FinnHub.MCP.Server -- --stdio
Docker Support
docker build -t finnhub-mcp .
docker run -e FINNHUB_API_KEY="your_api_key_here" -p 5101:5101 finnhub-mcp

πŸ“– API Usage Examples

Symbol Search

# Search for Apple stock
curl -X POST "http://localhost:5101/mcp/tools/symbol_search" \
  -H "Content-Type: application/json" \
  -d '{"query": "AAPL"}'

Real-Time Quote (Coming Soon)

# Get real-time quote for Apple
curl -X POST "http://localhost:5101/mcp/tools/quote" \
  -H "Content-Type: application/json" \
  -d '{"symbol": "AAPL"}'

βš™οΈ Configuration

Rate Limiting Configuration

{
  "Finnhub": {
    "RateLimit": {
      "RequestsPerMinute": 60,
      "BurstLimit": 10,
      "RetryAfterSeconds": 60
    }
  }
}

Logging Configuration

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "FinnHub.MCP.Server": "Debug",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

πŸ§ͺ Testing

Unit Tests

dotnet test src/FinnHub.MCP.Server.Tests

Integration Tests

# Set test API key
export FINNHUB_TEST_API_KEY="your_test_api_key"
dotnet test src/FinnHub.MCP.Server.IntegrationTests

Load Testing

# Test rate limiting behavior
dotnet run --project tests/FinnHub.MCP.LoadTests

πŸ”§ Development

Building from Source

dotnet build

Running with Hot Reload

dotnet watch run --project src/FinnHub.MCP.Server

Code Quality

# Run code analysis
dotnet format
dotnet run --project tools/CodeAnalysis

πŸ“Š Monitoring & Observability

  • Health Checks: /health endpoint for monitoring
  • Metrics: Prometheus metrics via /metrics
  • Tracing: OpenTelemetry integration
  • Logging: Structured logging with Serilog

πŸ› οΈ Tech Stack

  • Framework: .NET 8 with ASP.NET Core
  • Resilience: Polly for retry policies and circuit breakers
  • Validation: JsonSchema.Net for input validation
  • Testing: xUnit with Moq for mocking
  • Configuration: DotNetEnv for environment management
  • Logging: Serilog for structured logging
  • Monitoring: OpenTelemetry for observability
  • CI/CD: GitHub Actions with automated testing and deployment

Development Setup

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (dotnet test)
  6. Submit a pull request

πŸ“„ License

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

πŸ™ Acknowledgments

πŸ“ž Support