alonlevyshavit/stock-analyzr-mcp
If you are the rightful owner of stock-analyzr-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.
Stock Analyzr MCP Server is a powerful Model Context Protocol server designed for comprehensive stock analysis and valuation, providing computational tools for financial analysis.
Stock Analyzr MCP Server
A powerful Model Context Protocol (MCP) server for comprehensive stock analysis and valuation. This server provides computational tools for financial analysis that can be used by Large Language Models (LLMs) to perform professional-grade investment research.
Features
🎯 Core Capabilities
- Real-time Financial Data: Fetch comprehensive company financials, income statements, balance sheets, cash flows, and key metrics
- DCF Valuation: Advanced Discounted Cash Flow calculator with sensitivity analysis
- Flexible Data Periods: Support for both quarterly and annual financial data
- Smart Caching: Intelligent caching system with data-type specific TTLs
- Rate Limiting: Built-in rate limiting to respect API quotas
- Multiple Data Sources: Adapter pattern supporting Financial Modeling Prep (FMP) API with extensibility for other providers
📊 Available Tools
1. fetch_company_data
Fetches comprehensive financial data for any publicly traded company.
Parameters:
ticker(required): Stock ticker symbol (e.g., "AAPL", "GOOGL")dataTypes: Array of data types to fetchprofile: Company overview and business descriptionquote: Real-time stock price and market dataincome_statement: Revenue, expenses, and profitability metricsbalance_sheet: Assets, liabilities, and equitycash_flow: Operating, investing, and financing cash flowsratios: Financial ratios (P/E, ROE, debt ratios, etc.)key_metrics: Key performance indicators
period: "quarter" (default) or "annual"limit: Number of periods to fetch (1-20, default: 5)
2. calculate_dcf
Performs Discounted Cash Flow valuation with sensitivity analysis.
Parameters:
projectedFreeCashFlows: Array of projected FCF for each yearterminalGrowthRate: Long-term growth rate (e.g., 0.025 for 2.5%)discountRate: WACC/discount rate (e.g., 0.10 for 10%)netDebt: Total debt minus cashsharesOutstanding: Diluted shares outstanding- Optional context fields for additional analysis
Returns:
- Fair value per share
- Enterprise value and equity value
- Present value calculations
- 5x5 sensitivity analysis matrix
- Detailed breakdown of all calculations
3. test_api_connection
Tests the FMP API connection and validates your API key.
Installation
Prerequisites
- Node.js 18+
- npm or yarn
- Financial Modeling Prep API key (get one at financialmodelingprep.com)
Setup
- Clone the repository:
git clone https://github.com/yourusername/stock-analyzr-mcp.git
cd stock-analyzr-mcp
- Install dependencies:
npm install
- Set up environment variables:
# Create .env file
echo "FMP_API_KEY=your_api_key_here" > .env
- Build the project:
npm run build
- Run tests to verify setup:
npm test
Usage
With Claude Desktop
- Add to your Claude Desktop configuration (
~/Library/Application Support/Claude/claude_desktop_config.json):
{
"mcpServers": {
"stock-analyzr": {
"command": "node",
"args": ["/path/to/stock-analyzr-mcp/dist/server.js"],
"env": {
"FMP_API_KEY": "your_api_key_here"
}
}
}
}
-
Restart Claude Desktop
-
The tools will be available in your conversations. Example prompts:
- "Analyze Apple's financial health using the latest quarterly data"
- "Calculate the DCF valuation for Microsoft with conservative growth assumptions"
- "Compare the financial ratios of Tesla vs traditional automakers"
Standalone MCP Server
# Start the server
npm start
# The server runs on stdio and can be connected to any MCP client
Development
Project Structure
stock-analyzr-mcp/
├── src/
│ ├── server.ts # Main MCP server
│ ├── tools/
│ │ ├── company-data-fetcher.ts # Financial data retrieval
│ │ └── dcf-calculator.ts # DCF valuation engine
│ ├── adapters/
│ │ └── fmp-adapter.ts # Financial Modeling Prep API
│ ├── models/ # TypeScript interfaces
│ ├── utils/
│ │ ├── cache.ts # Caching system
│ │ └── rate-limiter.ts # API rate limiting
│ └── prompts/
│ └── system-instructions.ts # LLM guidance frameworks
├── tests/ # Comprehensive test suite
├── docs/ # Additional documentation
└── config/ # Configuration files
Available Scripts
npm run dev # Start development server with hot reload
npm run build # Compile TypeScript to JavaScript
npm run test # Run all tests
npm run test:unit # Run unit tests only
npm run test:integration # Run integration tests
npm run lint # Run ESLint
npm run lint:fix # Auto-fix linting issues
npm run format # Format code with Prettier
Testing
The project includes comprehensive test coverage:
- Unit tests for all calculators and utilities
- Integration tests for API adapters
- End-to-end tests for MCP server functionality
Run tests with coverage:
npm run test:coverage
Architecture
Design Principles
- Separation of Concerns: Computational tools handle math, LLMs handle interpretation
- Pure Functions: All calculators are deterministic and side-effect free
- Type Safety: Full TypeScript with strict typing
- Error Resilience: Comprehensive error handling and validation
- Performance: Smart caching and rate limiting for optimal API usage
Data Flow
LLM Request → MCP Server → Tool Selection → Data Fetcher/Calculator
↓ ↓
Rate Limiter FMP Adapter
↓ ↓
Cache Layer External API
↓ ↓
Response ← ← ← ← ← ← ← ← ← Processed Data
Caching Strategy
- Quote Data: 1 minute TTL (real-time pricing)
- Financial Statements: 1 hour TTL (updated quarterly)
- Company Profiles: 24 hour TTL (rarely changes)
- Cache Keys: Include ticker, data type, and period for granular control
API Documentation
Financial Data Types
Company Profile
{
symbol: string;
companyName: string;
industry: string;
sector: string;
description: string;
marketCap: number;
// ... additional fields
}
Income Statement
{
date: string;
period: string;
revenue: number;
netIncome: number;
eps: number;
// ... additional fields
}
DCF Results
{
sharePrice: number;
enterpriseValue: number;
equityValue: number;
presentValueOfCashFlows: number[];
terminalValue: number;
sensitivityAnalysis: {
discountRateRange: number[];
terminalGrowthRange: number[];
valuationMatrix: number[][];
}
}
Configuration
Environment Variables
FMP_API_KEY(required): Your Financial Modeling Prep API keyCACHE_TTL(optional): Default cache TTL in secondsRATE_LIMIT(optional): API calls per minute limitLOG_LEVEL(optional): Logging verbosity (debug/info/warn/error)
Advanced Configuration
Create a config/custom.json for advanced settings:
{
"cache": {
"maxKeys": 1000,
"checkPeriod": 60
},
"rateLimiter": {
"maxTokens": 100,
"refillRate": 10
}
}
Troubleshooting
Common Issues
-
API Key Invalid
- Verify your FMP_API_KEY is correct
- Check API key permissions on FMP dashboard
- Use
test_api_connectiontool to validate
-
Rate Limiting
- Default limit is 250 calls/minute for free tier
- Upgrade FMP subscription for higher limits
- Adjust rate limiter settings if needed
-
Cache Issues
- Clear cache with
npm run clear-cache - Check cache size limits in configuration
- Verify file system permissions for cache directory
- Clear cache with
Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Write tests for all new features
- Maintain TypeScript strict mode compliance
- Follow existing code style (enforced by ESLint)
- Update documentation for API changes
- Add JSDoc comments for public methods
Roadmap
Phase 3: Extended Features (In Progress)
- Multi-source data integration (Yahoo Finance, Alpha Vantage)
- Advanced caching with Redis support
- WebSocket support for real-time data
- Portfolio analysis tools
Phase 4: Production Features (Planned)
- Docker containerization
- Kubernetes deployment manifests
- Monitoring and alerting (Prometheus/Grafana)
- Advanced error recovery and circuit breakers
Future Enhancements
- Technical analysis indicators
- Options pricing models
- Earnings forecast analysis
- Sector comparison tools
- Custom financial metrics builder
License
MIT License - see file for details
Acknowledgments
- Built with Anthropic's MCP SDK
- Financial data provided by Financial Modeling Prep
- DCF methodology based on academic finance principles
Support
For issues, questions, or suggestions:
- Open an issue on GitHub
- Check the for detailed guides
- Review closed issues for common problems
Security
- Never commit API keys to version control
- Use environment variables for sensitive configuration
- Regularly rotate API keys
- Monitor API usage for anomalies
Note: This is an active development project. Features and APIs may change. Always refer to the latest documentation and changelog for updates.