Skip to main content
Glama
souzanahamza

FinMCP-Core

by souzanahamza

FinMCP-Backend

Financial AI backend combining FastAPI, Google Gemini, and FastMCP. Exposes Yahoo Finance market data through an MCP stdio server and a Gemini-powered REST chat API for frontend clients.

Features

  • MCP server (FinMCP-Core) — 15 tools for stock quotes, financials, risk metrics, news sentiment, SEC filings, and session summaries

  • REST API — POST /api/chat endpoint powered by Gemini with automatic function calling

  • Shared service layer — Yahoo Finance logic centralized in app/services/market_data.py

  • Dual run modes — Web API or stdio MCP server from a single entry point

  • Configurable Gemini model — set via GEMINI_MODEL in .env

Related MCP server: yfinance

Architecture

main.py
├── web  → FastAPI (app/api.py) → Gemini + fetch_stock_price
└── stdio → FastMCP (app/mcp_server.py) → 15 tools
                    ↓
         app/services/market_data.py (yfinance)

Layer

Role

app/services/market_data.py

Core yfinance business logic, returns structured dict payloads

app/mcp_server.py

Thin @mcp.tool() wrappers for MCP clients (Cursor, Claude Desktop)

app/api.py

FastAPI app with CORS; Gemini chat with fetch_stock_price

Prerequisites

Installation

git clone <your-repo-url>
cd finMCP

py -m pip install -r requirements.txt

Create a .env file in the project root:

GEMINI_API_KEY=your_key_here
GEMINI_MODEL=gemini-2.0-flash

Variable

Required

Description

GEMINI_API_KEY

Yes (web API)

API key from Google AI Studio

GEMINI_MODEL

No

Gemini model name (default: gemini-3.1-flash-lite)

The MCP stdio server does not require a Gemini API key.

Running

Web API (FastAPI)

py main.py web

Server starts at http://localhost:8000.

MCP Server (stdio)

py main.py

Runs the FinMCP-Core MCP server over stdio transport for desktop AI clients.

API Usage

POST /api/chat

Send a natural-language message. Gemini automatically calls fetch_stock_price when a stock quote is needed.

Request:

{
  "message": "What is the current price of AAPL?"
}

Response:

{
  "reply": "Apple Inc. (AAPL): 189.50 USD"
}

Example with curl:

curl -X POST http://localhost:8000/api/chat \
  -H "Content-Type: application/json" \
  -d "{\"message\": \"What is the current price of AAPL?\"}"

Gemini tools (web API)

Tool

Description

fetch_stock_price

Current price, currency, and company name for a ticker

API error responses

Status

Cause

400

Invalid request or unsupported model configuration

401

Invalid or unauthorized API key

429

Gemini rate limit or free-tier quota exceeded

500

GEMINI_API_KEY not configured

502

Transient or internal Gemini API error

The chat endpoint retries transient failures automatically via the Google SDK.

MCP Tools

Tool

Description

get_current_stock_price

Real-time price and company name

get_historical_stock_splits

Stock split history

get_stock_info

Sector, industry, market cap, description

get_financials

Income, balance sheet, or cash flow statements

get_dividend_analysis

Dividend yield, payout ratio, history

get_institutional_holders

Institutional ownership data

get_options_chain

Calls, puts, and implied volatility

get_news_sentiment

Filtered news with basic sentiment counts

get_valuation_metrics

P/E, PEG, EV/EBITDA, price-to-book

get_sector_comparison

Sector benchmarks and peers

get_risk_metrics

Beta, volatility, Sharpe ratio, max drawdown

get_earnings_analysis

EPS estimates vs actuals

get_sec_filings

SEC filing metadata

add_summary

Append a message to the session summary file

read_summary

Read accumulated session summaries

Session summaries are stored at app/data/summary.txt (created automatically on first use).

Cursor MCP Configuration

Add to your Cursor MCP settings:

{
  "mcpServers": {
    "finmcp": {
      "command": "py",
      "args": ["main.py"],
      "cwd": "d:\\Desktop\\projects\\finMCP"
    }
  }
}

Adjust cwd to match your local project path.

Project Structure

finMCP/
├── app/
│   ├── __init__.py
│   ├── api.py              # FastAPI + Gemini chat endpoint
│   ├── mcp_server.py       # FastMCP tool registrations
│   ├── data/
│   │   └── summary.txt     # Created at runtime
│   └── services/
│       ├── __init__.py
│       └── market_data.py  # Yahoo Finance service functions
├── main.py                 # Entry point (web | stdio)
├── requirements.txt
└── .env                    # GEMINI_API_KEY, GEMINI_MODEL (not committed)

Troubleshooting

GEMINI_API_KEY is not configured

Set a valid key in .env. The MCP server does not need it.

429 / quota exceeded

Your API key has hit the free-tier or per-minute limit for the configured model. Options:

  • Wait and retry (limits reset per minute/day)

  • Switch model in .env, e.g. GEMINI_MODEL=gemini-1.5-flash

  • Check usage at ai.dev/rate-limit

500 Internal error from Gemini

Often caused by an invalid model name. Use a supported Gemini model (not Gemma or other non-Gemini IDs). Set GEMINI_MODEL to a known working value such as gemini-2.0-flash or gemini-1.5-flash.

AttributeError: module 'collections' has no attribute 'Mapping'

Upgrade frozendict for Python 3.12+ compatibility:

py -m pip install --upgrade frozendict

py or pip not found

Use python and python -m pip instead, or install Python from python.org.

Dependencies

Package

Purpose

fastapi / uvicorn

Web API server

mcp

FastMCP stdio server

google-generativeai

Gemini chat with function calling

yfinance

Yahoo Finance market data

numpy

Risk metrics calculations

python-dotenv

Environment variable loading

pydantic

Request/response validation

httpx

HTTP client (transitive dependency)

Related MCP Connectors

  • Financial data MCP server for Claude, ChatGPT, Cursor and Codex. Real-time stock quotes, financial statements, options flow, SEC filings, insider trades, 13F holdings, macro data and market news from gloom.sh, the open-source Bloomberg Terminal alternative.

  • The Octagon MCP server provides specialized AI-powered financial research and analysis by integrating with the Octagon Market Intelligence API. It enables users to analyze public market data (SEC filings, earnings transcripts, financial metrics, and stock data for 8000+ companies), private market data (3M+ companies, 500k+ funding rounds, 2M+ M&A/IPO transactions), and conduct deep research including web scraping capabilities. The server also features autonomous research agents that search hundreds of sources and return fully cited reports in approximately one minute.

  • Your agent needs company financials it can compute on — statements, ratios, earnings, estimates, filings and insider activity as structured data, not a PDF. **What you can ask for** • "Give me 8 quarters of income statement, balance sheet and cash flow for this ticker." • "What do analysts estimate for next quarter, and how did the last four surprise?" • "Find this exact line item across every filing." • "Who bought or sold as an insider in the last 90 days?" • "Screen for profitable companies under this valuation with growing revenue." **How to use it** Point any MCP client at https://mcp.aisa.one/marketpulse/mcp and sign in with OAuth — there is no key to create or paste. 21 tools: prices and snapshots, income statements, balance sheets, cash-flow statements, financial metrics and snapshots, earnings, analyst estimates, company facts, filings and filing items, line-item search, a screener, insider trades, macro interest rates, news, plus EDINET documents and filing digests for Japanese issuers. **Why this rather than the source** Statements as fields you can compute on, and a screener in the same place. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Read the fundamentals here, then ask the same agent what social is saying about the ticker — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/finance/mcp for equities, crypto and prediction markets in one place.

  • Your agent needs markets — prices and fundamentals for listed companies, the filings behind them, crypto, and what the prediction markets put the odds at. **What you can ask for** • "Pull this company's income statement, cash flow and balance sheet for the last 8 quarters." • "What did insiders buy or sell, and when?" • "Snapshot prices for these 50 tickers, then the OHLC history for the three that moved." • "What are the current odds on this event across Kalshi and Polymarket?" • "Screen for companies matching these financial criteria." **How to use it** Point any MCP client at https://mcp.aisa.one/finance/mcp and sign in with OAuth — there is no key to create or paste. 49 tools: prices and snapshots, income statements, balance sheets and cash flows, metrics and ratios, earnings and analyst estimates, filings and line-item search, insider trades, macro interest rates, news, a screener; CoinGecko spot prices, market tables, OHLC, per-venue tickers and trending; Kalshi and Polymarket markets and trades; plus EDINET filings for Japan. **Why this rather than the source** Equities, crypto and event markets behind one account, so a cross-asset question is one conversation. **It is also a door to the rest** The same login reaches 26 sources and 580+ operations. Read the number here, then ask the same agent what X is saying about the ticker today — without adding a second server. **What it costs** Finding and inspecting an operation is free. Running one is billed per call at API prices, with no seat and no monthly minimum, and every call takes max_price_usd so an agent cannot overspend by accident. **Where else it reaches** https://mcp.aisa.one/marketpulse/mcp · /crypto-market-data/mcp · /prediction-market-data/mcp · /stock-pulse/mcp for one slice each.

Related MCP Servers

  • A
    license
    C
    quality
    D
    maintenance
    A Model Context Protocol server providing comprehensive financial data from Yahoo Finance, allowing users to retrieve detailed stock information, financial statements, options data, and market news.
    34
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    A Model Context Protocol (MCP) server that provides comprehensive access to Yahoo Finance data through 18 specialized tools for pricing, financials, options, holders, and news.
    18
    35 PyPI
    1
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    MCP server that exposes Yahoo Finance data through tools for searching instruments, fetching quotes, history, company info, financials, dividends, news, recommendations, and options. Enables AI assistants to answer market-data questions using natural language.
    22
    66 PyPI
    MIT
  • F
    license
    Not graded
    quality
    C
    maintenance
    MCP server wrapping yfinance to provide stock market data, financials, and analytics via 24 tools.
    -