Les agents IA répondant à des questions financières ont besoin de données en temps réel : actualités boursières, rapports de résultats, sentiment du marché. Un serveur MCP qui encapsule la recherche fournit cela sans avoir à construire un pipeline de données personnalisé. Ce tutoriel construit un outil MCP d'actualités financières qui recherche sur Google News des informations spécifiques aux actions et sur Reddit le sentiment du marché, le tout via l'API Scavio à $0.005 par recherche. Votre agent obtient des réponses financières fondées au lieu de chiffres hallucinés.
Prérequis
- Python 3.9+ installé
- bibliothèque requests installée
- Une clé API Scavio depuis scavio.dev
- Compréhension de base des définitions d'outils MCP
Parcours
Étape 1: Construire les fonctions de recherche d'actualités financières
Créez des fonctions de recherche spécialisées pour les actualités boursières, les données de résultats et le sentiment du marché. Chaque fonction cible des modèles de requête spécifiques qui renvoient des données financières.
import os, requests, re, time
from datetime import datetime
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
URL = 'https://api.scavio.dev/api/v1/search'
H = {'x-api-key': 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', 'country_code': 'us', 'num_results': num})
return [{'title': r['title'], 'snippet': r.get('snippet', ''),
'url': r['link'], 'source': 'google_news'}
for r in resp.json().get('organic_results', [])]
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',
'country_code': 'us', 'num_results': 5})
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',
'country_code': 'us', 'num_results': 5})
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]}')Étape 2: Construire le rapport boursier complet
Combinez actualités, résultats et sentiment en un rapport financier unifié. Extrayez les signaux clés comme les mentions de prix, les notations d'analystes et les indicateurs de sentiment.
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']}")Étape 3: Définir les schémas d'outils MCP
Créez des définitions d'outils compatibles MCP qu'un agent IA peut appeler. Chaque outil renvoie des données financières formatées que le LLM peut utiliser pour répondre aux questions.
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])Étape 4: Créer la configuration du serveur MCP
Configurez le fichier .mcp.json pour que les agents IA puissent se connecter à votre serveur d'actualités financières.
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')Exemple Python
import os, requests, time
SCAVIO_KEY = os.environ['SCAVIO_API_KEY']
H = {'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json'}
def stock_news(ticker, num=5):
resp = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'query': f'{ticker} stock news 2026', 'country_code': 'us', 'num_results': num})
return resp.json().get('organic_results', [])
def stock_sentiment(ticker):
resp = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'query': f'site:reddit.com {ticker} stock', 'country_code': 'us', 'num_results': 5})
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)Exemple JavaScript
const SCAVIO_KEY = process.env.SCAVIO_API_KEY;
async function stockNews(ticker, num = 5) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: `${ticker} stock news 2026`, country_code: 'us', num_results: num })
});
return (await resp.json()).organic_results || [];
}
async function stockSentiment(ticker) {
const resp = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST',
headers: { 'x-api-key': SCAVIO_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ query: `site:reddit.com ${ticker} stock`, country_code: 'us', num_results: 5 })
});
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)}`));
})();Sortie attendue
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']