ScavioScavio
Pricing
Tools
Sign InsGet Startedg
  1. Home
  2. Tutorials
  3. How to Build a Financial News MCP Server with Search
Tutorial

How to Build a Financial News MCP Server with Search

Build an MCP server that provides real-time financial news and stock data to AI agents. Search-powered financial intelligence for Claude and other LLMs.

Get Free API KeyAPI Docs

AI agents answering financial questions need real-time data: stock news, earnings reports, market sentiment. An MCP server that wraps search provides this without building a custom data pipeline. This tutorial builds a financial news MCP tool that searches Google News for stock-specific information and Reddit for market sentiment, all through the Scavio API at $0.005 per search. Your agent gets grounded financial answers instead of hallucinated numbers.

Prerequisites

  • Python 3.9+ installed
  • requests library installed
  • A Scavio API key from scavio.dev
  • Basic understanding of MCP tool definitions

Walkthrough

Step 1: Build the financial news search functions

Create specialized search functions for stock news, earnings data, and market sentiment. Each function targets specific query patterns that return financial data.

Python
import os, requests, re, time
from datetime import datetime

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
URL = 'https://api.scavio.dev/api/v2/google'
H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}

def search_stock_news(ticker: str, num: int = 5) -> list:
    """Get latest news for a stock ticker."""
    resp = requests.post(URL, headers=H,
        json={'query': f'{ticker} stock news 2026', 'gl': 'us'})
    return [{'title': r['title'], 'snippet': r.get('snippet', ''),
             'url': r['link'], 'source': 'google_news'}
            for r in resp.json().get('organic_results', [])[:num]]

def search_earnings(ticker: str) -> list:
    """Search for recent earnings reports."""
    resp = requests.post(URL, headers=H,
        json={'query': f'{ticker} earnings report Q2 2026',
 'gl': 'us'})
    return [{'title': r['title'], 'snippet': r.get('snippet', ''),
             'url': r['link'], 'source': 'earnings'}
            for r in resp.json().get('organic_results', [])]

def search_market_sentiment(ticker: str) -> list:
    """Check Reddit for market sentiment."""
    resp = requests.post(URL, headers=H,
        json={'query': f'site:reddit.com {ticker} stock',
 'gl': 'us'})
    return [{'title': r['title'], 'snippet': r.get('snippet', ''),
             'url': r['link'], 'source': 'reddit'}
            for r in resp.json().get('organic_results', [])]

news = search_stock_news('AAPL')
print(f'AAPL news: {len(news)} articles')
for n in news[:3]:
    print(f'  {n["title"][:60]}')

Step 2: Build the comprehensive stock report

Combine news, earnings, and sentiment into a unified financial report. Extract key signals like price mentions, analyst ratings, and sentiment indicators.

Python
def stock_report(ticker: str) -> dict:
    """Generate a comprehensive stock report."""
    news = search_stock_news(ticker)
    time.sleep(0.3)
    earnings = search_earnings(ticker)
    time.sleep(0.3)
    sentiment = search_market_sentiment(ticker)
    # Analyze sentiment from Reddit
    all_reddit_text = ' '.join(r['snippet'] for r in sentiment).lower()
    bullish_words = ['bull', 'buy', 'moon', 'undervalued', 'growth', 'strong']
    bearish_words = ['bear', 'sell', 'overvalued', 'crash', 'decline', 'weak']
    bull_count = sum(1 for w in bullish_words if w in all_reddit_text)
    bear_count = sum(1 for w in bearish_words if w in all_reddit_text)
    sentiment_label = 'bullish' if bull_count > bear_count else 'bearish' if bear_count > bull_count else 'neutral'
    # Extract price mentions
    all_text = ' '.join(r['snippet'] for r in news + earnings)
    prices = re.findall(r'\$([\d,]+\.?\d*)', all_text)
    return {
        'ticker': ticker,
        'timestamp': datetime.now().isoformat(),
        'news_count': len(news),
        'top_headlines': [n['title'] for n in news[:3]],
        'earnings_count': len(earnings),
        'reddit_sentiment': sentiment_label,
        'sentiment_detail': {'bullish': bull_count, 'bearish': bear_count},
        'price_mentions': prices[:5],
        'sources': news + earnings + sentiment,
        'credits_used': 3,
        'cost': 0.015,
    }

report = stock_report('NVDA')
print(f"Stock Report: {report['ticker']}")
print(f"Headlines: {len(report['top_headlines'])}")
for h in report['top_headlines']:
    print(f'  - {h[:60]}')
print(f"Reddit sentiment: {report['reddit_sentiment']}")
print(f"Cost: ${report['cost']}")

Step 3: Define MCP tool schemas

Create MCP-compatible tool definitions that an AI agent can call. Each tool returns formatted financial data the LLM can use to answer questions.

Python
MCP_TOOLS = {
    'stock_news': {
        'name': 'stock_news',
        'description': 'Get the latest news articles for a stock ticker symbol. Returns headlines, snippets, and source URLs.',
        'inputSchema': {
            'type': 'object',
            'properties': {
                'ticker': {'type': 'string', 'description': 'Stock ticker symbol (e.g., AAPL, NVDA, TSLA)'},
                'num_results': {'type': 'integer', 'description': 'Number of articles (1-10)', 'default': 5}
            },
            'required': ['ticker']
        }
    },
    'stock_report': {
        'name': 'stock_report',
        'description': 'Generate a comprehensive stock report with news, earnings, and Reddit sentiment analysis.',
        'inputSchema': {
            'type': 'object',
            'properties': {
                'ticker': {'type': 'string', 'description': 'Stock ticker symbol'}
            },
            'required': ['ticker']
        }
    },
    'market_sentiment': {
        'name': 'market_sentiment',
        'description': 'Check Reddit sentiment for a stock or market topic.',
        'inputSchema': {
            'type': 'object',
            'properties': {
                'ticker': {'type': 'string', 'description': 'Stock ticker or topic'}
            },
            'required': ['ticker']
        }
    }
}

def handle_mcp_call(tool_name: str, args: dict) -> str:
    if tool_name == 'stock_news':
        news = search_stock_news(args['ticker'], args.get('num_results', 5))
        return '\n\n'.join([f'{n["title"]}\n{n["snippet"]}\nSource: {n["url"]}' for n in news])
    elif tool_name == 'stock_report':
        report = stock_report(args['ticker'])
        lines = [f'Stock Report: {report["ticker"]}',
                 f'Sentiment: {report["reddit_sentiment"]}',
                 f'Headlines:']
        lines.extend(f'  - {h}' for h in report['top_headlines'])
        return '\n'.join(lines)
    elif tool_name == 'market_sentiment':
        results = search_market_sentiment(args['ticker'])
        return '\n\n'.join(f'{r["title"]}\n{r["snippet"]}' for r in results)
    return 'Unknown tool'

print('MCP tools defined:', list(MCP_TOOLS.keys()))
result = handle_mcp_call('stock_news', {'ticker': 'AAPL', 'num_results': 3})
print(result[:300])

Step 4: Create the MCP server configuration

Set up the .mcp.json configuration so AI agents can connect to your financial news server.

Python
import json

def create_finance_mcp_config(output_path: str = '.mcp.json'):
    """Create MCP config with Scavio for financial data."""
    config = {
        'mcpServers': {
            'scavio': {
                'url': 'https://mcp.scavio.dev/mcp',
                'headers': {
                    'Authorization': 'Bearer ${SCAVIO_API_KEY}'
                }
            }
        }
    }
    with open(output_path, 'w') as f:
        json.dump(config, f, indent=2)
    print(f'MCP config written to {output_path}')
    print(f'Financial tools available via Scavio MCP:')
    print(f'  - Web search (stock news, earnings, filings)')
    print(f'  - Reddit search (market sentiment)')
    print(f'  - YouTube search (analyst videos)')
    print(f'  Cost: $0.005 per search')
    print(f'  Endpoint: mcp.scavio.dev/mcp')

# Test the full pipeline
create_finance_mcp_config()
print('\nExample usage with Claude:')
print('  User: "What is the latest news on NVDA stock?"')
print('  Agent calls: stock_news({ticker: "NVDA"})')
print('  Agent gets: real-time news headlines + Reddit sentiment')
print('  Cost: $0.005-$0.015 per question')

Python Example

Python
import os, requests, time

SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
H = {'Authorization': f'Bearer {SCAVIO_KEY}', 'Content-Type': 'application/json'}

def stock_news(ticker, num=5):
    resp = requests.post('https://api.scavio.dev/api/v2/google', headers=H,
        json={'query': f'{ticker} stock news 2026', 'gl': 'us'})
    return resp.json().get('organic_results', [])[:num]

def stock_sentiment(ticker):
    resp = requests.post('https://api.scavio.dev/api/v2/google', headers=H,
        json={'query': f'site:reddit.com {ticker} stock', 'gl': 'us'})
    text = ' '.join(r.get('snippet','') for r in resp.json().get('organic_results', [])).lower()
    bull = sum(1 for w in ['bull','buy','growth'] if w in text)
    bear = sum(1 for w in ['bear','sell','crash'] if w in text)
    return 'bullish' if bull > bear else 'bearish' if bear > bull else 'neutral'

for ticker in ['AAPL', 'NVDA']:
    news = stock_news(ticker, 3)
    print(f'{ticker}: {len(news)} articles, sentiment={stock_sentiment(ticker)}')
    for n in news[:2]:
        print(f'  {n["title"][:60]}')
    time.sleep(0.3)

JavaScript Example

JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;

async function stockNews(ticker, num = 5) {
  const resp = await fetch('https://api.scavio.dev/api/v2/google', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${SCAVIO_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: `${ticker} stock news 2026`, gl: 'us' })
  });
  return (await resp.json()).organic_results?.slice(0, num) || [];
}

async function stockSentiment(ticker) {
  const resp = await fetch('https://api.scavio.dev/api/v2/google', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${SCAVIO_KEY}`, 'Content-Type': 'application/json' },
    body: JSON.stringify({ query: `site:reddit.com ${ticker} stock`, gl: 'us' })
  });
  const text = ((await resp.json()).organic_results || []).map(r => r.snippet || '').join(' ').toLowerCase();
  const bull = ['bull','buy','growth'].filter(w => text.includes(w)).length;
  const bear = ['bear','sell','crash'].filter(w => text.includes(w)).length;
  return bull > bear ? 'bullish' : bear > bull ? 'bearish' : 'neutral';
}

(async () => {
  const news = await stockNews('AAPL', 3);
  const sent = await stockSentiment('AAPL');
  console.log(`AAPL: ${news.length} articles, sentiment=${sent}`);
  news.slice(0, 2).forEach(n => console.log(`  ${n.title.slice(0, 60)}`));
})();

Expected Output

JSON
AAPL news: 5 articles
  Apple Reports Record Q2 2026 Revenue Driven by AI
  AAPL Stock Surges on Strong iPhone 17 Pre-orders
  Apple Vision Pro 2 Launch Boosts Stock Price

Stock Report: NVDA
Headlines: 3
  - NVIDIA H200 Demand Outstrips Supply in Q2 2026
  - NVDA Earnings Beat Expectations by 15%
  - NVIDIA Partners with AWS on Next-Gen AI Chips
Reddit sentiment: bullish
Cost: $0.015

MCP tools defined: ['stock_news', 'stock_report', 'market_sentiment']

Related Tutorials

    Frequently Asked Questions

    Most developers complete this tutorial in 15 to 30 minutes. You will need a Scavio API key (free tier works) and a working Python or JavaScript environment.

    Python 3.9+ installed. requests library installed. A Scavio API key from scavio.dev. Basic understanding of MCP tool definitions. A Scavio API key gives you 50 free credits on signup.

    Yes. The free tier includes 50 credits on signup, which is more than enough to complete this tutorial and prototype a working solution.

    Scavio has a native LangChain package (langchain-scavio), an MCP server, and a plain REST API that works with any HTTP client. This tutorial uses the raw REST API, but you can adapt to your framework of choice.

    Related Resources

    Best Of

    Best Financial Data MCP Servers in May 2026

    Read more
    Comparison

    MCP Search Integration vs Direct API Integration

    Read more
    Best Of

    Best MCP Search Server in 2026

    Read more
    Glossary

    Agent-First Search

    Read more
    Comparison

    Brave Search API vs Scavio

    Read more
    Solution

    Real-Time Data for Hermes Agent and OpenClaw

    Read more

    Start Building

    Build an MCP server that provides real-time financial news and stock data to AI agents. Search-powered financial intelligence for Claude and other LLMs.

    Get Free API KeyRead the Docs
    ScavioScavio

    One scraper API for every social, search, e-commerce and real estate platform. Built for AI agents.

    Product

    • Features
    • Pricing
    • Dashboard
    • Affiliates

    Developers

    • Documentation
    • API Reference
    • Quickstart
    • MCP Integration
    • Python SDK

    Alternatives

    • Tavily Alternative
    • SerpAPI Alternative
    • Firecrawl Alternative
    • Exa Alternative
    • Serper Alternative
    • Tavily vs Scavio
    • SerpAPI vs Scavio
    • All alternatives
    • Compare Scavio vs alternatives

    Search APIs

    • Google Search API
    • Amazon Product API
    • YouTube API
    • Reddit API
    • Walmart Product API
    • TikTok API
    • Instagram API

    Tools

    • All Tools

    © 2026 Scavio. All rights reserved.

    Featured on TAAFT
    Terms of ServicePrivacy Policy