yahoo-finance-mcp
v1.6.2
Published
Multi-usage Yahoo Finance library supporting MCP server integration
Downloads
116
Maintainers
Readme
Yahoo Finance MCP - Multi-Usage Library
A versatile Yahoo Finance library that supports Model Context Protocol (MCP) servers. Provides comprehensive financial data access through multiple usage patterns.
Features
- 🔌 MCP Server: Run as a standalone Model Context Protocol server
- 📚 Direct Usage: Import and use core functions directly
- 🌐 Comprehensive API: 14 financial data tools covering quotes, historical data, news, and more
- 📈 Real-time stock quotes and historical data
- 📰 Financial news and market updates
- 📊 Company information and financial metrics
- 🔍 Symbol search and lookup functionality
- 📋 Market summaries and major indices
- 🎯 Trending symbols by region
- 📈 Analyst recommendations and ratings
- 🌐 Multi-region support (US, GB, CA, etc.)
Table of Contents
- Installation
- Usage Options
- Transport Modes
- Available Tools
- Tool Categories
- Examples
- API Reference
- Development
- Architecture
- Contributing
- License
Installation
Method 1: Install from npm (Recommended)
npm install -g yahoo-finance-mcpMethod 2: Install for library usage
npm install yahoo-finance-mcpMethod 3: Build from source
- Clone the repository:
git clone https://github.com/phields/yahoo-finance-mcp.git
cd yahoo-finance-mcp- Install dependencies:
npm install- Build the project:
npm run buildUsage Options
This library supports two different usage patterns:
1. As an MCP Server
With Claude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"yahoo-finance": {
"command": "npx",
"args": ["yahoo-finance-mcp"]
}
}
}Standalone Server
npm start
# or for global installation
yahoo-finance-mcp2. Direct Function Usage
import { getQuote, getHistoricalData, searchSymbols } from 'yahoo-finance-mcp/tools';
// Get current quote
const quote = await getQuote({ symbol: 'AAPL' });
// Get historical data
const history = await getHistoricalData({
symbol: 'AAPL',
period1: '2023-01-01',
period2: '2023-12-31',
interval: '1d'
});
// Search for symbols
const results = await searchSymbols({ query: 'Apple' });Transport Modes
The MCP server supports multiple transport modes for different use cases:
1. STDIO Transport (Default)
The most basic transport mode, suitable for command-line tools and direct process communication.
import { yahooFinanceMcp } from "yahoo-finance-mcp/server";
// Start stdio transport (default)
await yahooFinanceMcp.start();
// Or explicitly specify
await yahooFinanceMcp.start('stdio');2. SSE (Server-Sent Events) Transport
Suitable for web applications that support real-time data streaming.
import { yahooFinanceMcp } from "yahoo-finance-mcp/server";
// Requires HTTP response object
await yahooFinanceMcp.start('sse', {
endpoint: "/message",
response: httpResponse // HTTP response object
});Complete Example with Hono Framework
import { Hono } from "hono";
import { yahooFinanceMcp } from "yahoo-finance-mcp/server";
const app = new Hono();
app.post("/mcp", async (c) => {
await yahooFinanceMcp.start('sse', {
endpoint: "/mcp",
response: c.res
});
return c.text("Yahoo Finance MCP SSE server started");
});
export default app;3. StreamableHTTP Transport
Suitable for HTTP scenarios that require session management.
import { yahooFinanceMcp } from "yahoo-finance-mcp/server";
await yahooFinanceMcp.start('streamableHttp', {
sessionIdGenerator: () => {
return `yahoo-finance-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
}
});Advanced Usage
Get Server Instance
For custom integration and advanced configuration.
const server = yahooFinanceMcp.getServer();
// Now you can use server for custom configurationCreate Custom Transports
Manually create transport instances for reuse.
// Create SSE transport
const sseTransport = yahooFinanceMcp.createSSETransport("/custom-endpoint", response);
// Create StreamableHTTP transport
const httpTransport = yahooFinanceMcp.createStreamableHTTPTransport({
sessionIdGenerator: () => `custom-session-${Date.now()}`
});Environment Variable Configuration
Support for selecting transport type via environment variables.
# Set transport type
export TRANSPORT_TYPE=stdio # Default
export TRANSPORT_TYPE=sse # SSE transport
export TRANSPORT_TYPE=streamableHttp # HTTP transport
# Run server
npm startStop Server
await yahooFinanceMcp.stop();Available Tools
This library provides 14 comprehensive financial data tools:
| Tool | Description | Parameters |
|------|-------------|------------|
| getQuote | Get current stock quote | symbol |
| getHistoricalData | Get historical price data | symbol, period1, period2, interval |
| searchSymbols | Search for stock symbols | query |
| getCompanyInfo | Get company profile information | symbol |
| getRecommendations | Get analyst recommendations | symbol |
| getTrendingSymbols | Get trending stocks by region | - |
| getMarketSummary | Get major market indices | - |
| getNews | Get financial news | query, newsCount |
| getOptions | Get options data | symbol, formatted, date? |
| getInsights | Get research insights | symbol, reportsCount |
| getDailyGainers | Get top gaining stocks | - |
| getDailyLosers | Get top losing stocks | - |
| getChart | Get chart data | symbol, range, interval |
| getQuoteSummary | Get comprehensive quote data | symbol, modules |
Tool Categories
Quoting Tools
Core stock price and quote functionality:
getQuote- Current stock quotesgetHistoricalData- Historical price datagetChart- Chart data for visualizationgetQuoteSummary- Comprehensive quote information
Analysis Tools
Market analysis and research:
getRecommendations- Analyst recommendationsgetInsights- Research reports and analysisgetOptions- Options chain datagetCompanyInfo- Company profile and financial metrics
Discovery Tools
Finding and exploring stocks:
searchSymbols- Symbol and company searchgetTrendingSymbols- Popular/trending stocksgetDailyGainers- Best performing stocksgetDailyLosers- Worst performing stocks
Market Data Tools
Overall market information:
getMarketSummary- Major indices and market overviewgetNews- Financial news and updates
Examples
┌─────────────────────────────────────┐
│ Usage Layers │
├─────────────────────────────────────┤
│ MCP Server │ Direct Usage │
│ (mcp.ts) │ │
├─────────────────────────────────────┤
│ Core Business Logic │
│ (tools.ts) │
├─────────────────────────────────────┤
│ Yahoo Finance API │
│ (yahoo-finance2 library) │
└─────────────────────────────────────┘Key Benefits
- Type Safety: Full TypeScript support with Zod schema validation
- Modularity: Use only what you need
- Flexibility: Multiple integration patterns
- Consistency: Same core functions across all usage patterns
- Extensibility: Easy to add new tools or modify existing ones
Development
Prerequisites
- Node.js 18+
- npm or yarn
Setup
git clone https://github.com/phields/yahoo-finance-mcp.git
cd yahoo-finance-mcp
npm installDevelopment Commands
# Build the project
npm run build
# Start MCP server in development
npm run dev
# Start MCP server
npm start
# Run tests (if available)
npm test
# Clean build artifacts
npm run cleanAdding New Tools
- Add your function to
src/tools.tswith Zod schema - Export the function and schema
- Add MCP handler to
src/mcp-server.ts - Update exports in
src/index.ts
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-tool - Make your changes
- Test your changes:
npm run build && npm test - Commit your changes:
git commit -am 'Add new tool' - Push to the branch:
git push origin feature/new-tool - Submit a pull request
License
This project is licensed under the MIT License - see the LICENSE.md file for details.
Acknowledgments
- Built on top of the excellent yahoo-finance2 library
- Inspired by the Model Context Protocol specification
Support
Note: This library provides access to Yahoo Finance data for educational and research purposes. Please respect Yahoo Finance's terms of service and rate limits when using this library in production applications.
Key Benefits
- Type Safety: Full TypeScript support with Zod schema validation
- Modularity: Use only what you need
- Flexibility: Multiple integration patterns
- Consistency: Same core functions across all usage patterns
- Extensibility: Easy to add new tools or modify existing ones
Error Handling
The server includes comprehensive error handling for:
- Invalid stock symbols
- API rate limiting
- Network timeouts
- Market closure periods
- Invalid date ranges
Rate Limiting
This server respects Yahoo Finance's rate limits and implements:
- Request throttling
- Automatic retry with exponential backoff
- Graceful degradation during high load periods
Development
Prerequisites
- Node.js 18.x or higher
- npm or yarn package manager
Setup
- Clone the repository:
git clone https://github.com/phields/yahoo-finance-mcp.git
cd yahoo-finance-mcp- Install dependencies:
npm install- Start development server:
npm run devScripts
npm run build- Build the TypeScript projectnpm run dev- Start development server with hot reloadnpm start- Start production servernpm run lint- Run ESLintnpm run lint:fix- Fix linting issues automatically
Project Structure
yahoo-finance-mcp/
├── src/
│ └── index.ts # Main server implementation
├── build/ # Compiled JavaScript output
├── tests/ # Test files
├── package.json # Dependencies and scripts
├── tsconfig.json # TypeScript configuration
└── README.md # This fileTesting
# Run tests
npm test
# Run tests with coverage
npm run test:coverageLinting
npm run lint
npm run lint:fixContributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
npm test) - Run linting (
npm run lint) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Contribution Guidelines
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
- Ensure all CI checks pass
Changelog
See CHANGELOG.md for a detailed history of changes.
Support
- 🐛 Bug reports: GitHub Issues
- 💡 Feature requests: GitHub Issues
- 💬 Questions: GitHub Discussions
License
This project is licensed under the MIT License - see the LICENSE.md file for details.
Disclaimer
⚠️ Important: This project is for educational and informational purposes only. It is not intended for financial advice or trading recommendations. Always conduct your own research and consult with qualified financial professionals before making investment decisions.
The data provided by this server is sourced from Yahoo Finance and may be subject to delays, inaccuracies, or interruptions. Use at your own risk.
Acknowledgments
- Yahoo Finance for providing the financial data
- Model Context Protocol for the MCP specification
- yahoo-finance2 for the Yahoo Finance API wrapper
