Los agentes de IA que responden preguntas financieras necesitan datos en tiempo real: noticias bursátiles, informes de ganancias, sentimiento del mercado. Un servidor MCP que encapsula la búsqueda proporciona esto sin crear una canalización de datos personalizada. Este tutorial crea una herramienta MCP de noticias financieras que busca en Google News información específica de acciones y en Reddit para conocer el sentimiento del mercado, todo a través de la API de Scavio a $0,005 por búsqueda. Su agente obtiene respuestas financieras fundamentadas en lugar de números alucinados.
Requisitos previos
- Python 3.9+ instalado
- solicita biblioteca instalada
- Una clave API de Scavio de scavio.dev
- Comprensión básica de las definiciones de herramientas MCP
Guia paso a paso
Paso 1: Construir las funciones de búsqueda de noticias financieras
Cree funciones de búsqueda especializadas para noticias bursátiles, datos de ganancias y sentimiento del mercado. Cada función apunta a patrones de consulta específicos que devuelven datos financieros.
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]}')Paso 2: Cree el informe bursátil completo
Combine noticias, ganancias y sentimiento en un informe financiero unificado. Extraiga señales clave como menciones de precios, calificaciones de analistas e indicadores de sentimiento.
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']}")Paso 3: Definir esquemas de herramientas MCP
Cree definiciones de herramientas compatibles con MCP a las que un agente de IA pueda llamar. Cada herramienta devuelve datos financieros formateados que el LLM puede utilizar para responder preguntas.
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])Paso 4: Crear la configuración del servidor MCP
Configure la configuración .mcp.json para que los agentes de IA puedan conectarse a su servidor de noticias financieras.
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')Ejemplo en 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)Ejemplo en 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)}`));
})();Salida esperada
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']Tutoriales relacionados
- Cómo agregar búsqueda en tiempo real a Claude a través de MCP
- Cómo determinar el alcance de los servidores MCP por proyecto para reducir la sobrecarga de tokens
- Cómo obtener resultados de Google News a través de la API de Scavio
- Cómo crear un agente de detección de tendencias utilizando YouTube y Google