Alpha Vantage MCP Server
Provides access to Alpha Vantage stock price data (OHLCV) and financial news with sentiment analysis through MongoDB storage, automatically fetching missing data from the API when needed.
README
Alpha Vantage MCP Server
A Model Context Protocol (MCP) server that provides access to Alpha Vantage stock price and financial news data through MongoDB storage. This project demonstrates a systematic approach to building production-ready MCP servers.
📺 Video Tutorial
Watch the complete tutorial on YouTube:
▶️ Building MCP Servers with Bun
🎯 What This Project Does
This MCP server provides two powerful tools for querying financial data:
get_stock_prices- Query stock price data (OHLCV) with automatic API fetching when data is missingget_news- Query financial news articles with sentiment analysis and keyword filtering
The server automatically pulls missing data from the Alpha Vantage API, stores it in MongoDB for fast future queries, and provides graceful error handling with helpful messages.
🏗️ Building an MCP Server: The Common Pattern
This project follows a systematic 6-step approach to building MCP servers. You can use this pattern for any MCP server project:
Step 1: Research & Preparation
- Identify the data source or API you want to integrate
- Study the API documentation and data structures
- Plan your data storage strategy (MongoDB, SQLite, files, etc.)
- Define what tools your MCP server will expose
In this project:
- API: Alpha Vantage API for stocks and news
- Storage: MongoDB with separate collections per stock symbol
- Tools:
get_stock_pricesandget_news
Step 2: Install Dependencies
- Set up your runtime environment (Bun, Node.js, etc.)
- Install required packages for MCP, database, and API access
- Configure environment variables
Commands:
bun init
bun add @modelcontextprotocol/sdk mongodb express zod yargs
Step 3: Create Utility Functions
- Build database connection and CRUD operations
- Create reusable helper functions
- Implement proper error handling and type safety
Files created:
src/mongo.ts- MongoDB utilities (connect, findDocuments, upsertDocument, etc.)
Step 4: Implement Core Business Logic
- Create functions to interact with your data source/API
- Implement data fetching, parsing, and storage
- Handle rate limiting and API key rotation
Files created:
src/business.ts- Alpha Vantage API integration (pullStock, pullNews, getKey)
Step 5: Create CLI Tool
- Build a command-line interface for testing and manual operations
- Implement all major operations as CLI commands
- This helps validate your business logic before building the MCP server
Files created:
src/run-stocks.ts- CLI tool using yargs
Step 6: Build the MCP Server
- Use the bun-mcp-template as a starting point
- Implement tool handlers that leverage your business logic
- Add both stdio and SSE transport support
- Include comprehensive error handling
Files created:
src/mcp.ts- MCP server implementation
🚀 Quick Start
Prerequisites
- Bun runtime installed
- MongoDB running (default:
mongodb://localhost:27017) - Alpha Vantage API key(s) (get free keys at https://www.alphavantage.co/support/#api-key)
Installation
# Clone the repository
git clone <repository-url>
cd alphavantage
# Install dependencies
bun install
# Set up environment variables
echo "MONGODB_CONNECTION_STRING=mongodb://localhost:27017" > .env
# Set up API keys for auto-pull feature
echo "YOUR_ALPHA_VANTAGE_API_KEY" > .keylist
See SETUP-KEYLIST.md for detailed .keylist setup instructions.
🧪 Testing
Run All Tests
# Test MongoDB utilities
bun test src/mongo.test.ts
# Test business logic
bun test src/business.test.ts
# Verify MCP implementation
bun run verify
# or
bun verify-mcp.ts
Test Specific Features
# Test auto-pull feature
bun test-auto-pull.ts
# Test .keylist path resolution
bun test-keylist-path.ts
# Test SSE transport mode
bun test-sse.ts
🖥️ Using the CLI Tool
The CLI provides direct access to all functionality for testing and manual operations.
Pull Data from API
# Pull stock data for a symbol
bun src/run-stocks.ts --pull-stock AAPL
# Pull news for a date range (YYYYMMDD-YYYYMMDD)
bun src/run-stocks.ts --pull-news 20251220-20251222
Query Data from MongoDB
# Get latest 100 stock prices for a symbol
bun src/run-stocks.ts --symbol AAPL
# Get stock price for a specific date
bun src/run-stocks.ts --symbol AAPL --date 20251223
# Query news articles within a date range
bun src/run-stocks.ts --news --from 20251220 --to 20251222
CLI Help
# Show all available commands and options
bun src/run-stocks.ts --help
CLI Examples
# Example 1: Pull and query Apple stock data
bun src/run-stocks.ts --pull-stock AAPL
bun src/run-stocks.ts --symbol AAPL
# Example 2: Query specific date
bun src/run-stocks.ts --symbol MSFT --date 20251223
# Example 3: Pull and search news
bun src/run-stocks.ts --pull-news 20251220-20251222
bun src/run-stocks.ts --news --from 20251220 --to 20251222
🔌 Installing the MCP Server
The MCP server can be installed in various MCP clients like Cursor, Claude Desktop, and Claude Code CLI.
Option 1: Install in Cursor
Add this configuration to your ~/.cursor/mcp.json file:
{
"mcpServers": {
"alphavantage": {
"command": "bun",
"args": [
"/Users/rossz/workspace/tutorials/labs/alphavantage/src/mcp.ts"
],
"env": {
"MONGODB_CONNECTION_STRING": "mongodb://localhost:27017"
}
}
}
}
Note: Update the path to match your actual project location.
Option 2: Install in Claude Desktop
Add this configuration to your Claude Desktop MCP settings file:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%/Claude/claude_desktop_config.json
{
"mcpServers": {
"alphavantage": {
"command": "bun",
"args": [
"/Users/rossz/workspace/tutorials/labs/alphavantage/src/mcp.ts",
"--stdio"
],
"env": {
"MONGODB_CONNECTION_STRING": "mongodb://localhost:27017"
}
}
}
}
Option 3: Install in Claude Code CLI
Using the claude mcp add command:
claude mcp add alphavantage bun /Users/rossz/workspace/tutorials/labs/alphavantage/src/mcp.ts
This will automatically configure the MCP server in Claude Code. You can verify it's installed:
# List all MCP servers
claude mcp list
# Check server status
claude mcp status alphavantage
Configuring Environment Variables
After installation, you may need to set environment variables:
For Cursor/Claude Desktop: Add to the env object in the JSON config:
"env": {
"MONGODB_CONNECTION_STRING": "mongodb://localhost:27017"
}
For Claude Code CLI: Environment variables are automatically loaded from your project's .env file.
🛠️ Running the MCP Server Directly
You can also run the MCP server directly for testing:
Stdio Mode (for MCP clients)
bun src/mcp.ts --stdio
SSE Mode (for HTTP clients)
# Default port 3001
bun src/mcp.ts --sse
# Custom port
bun src/mcp.ts --sse --port 8080
Test MCP Server Manually
# List available tools
echo '{"jsonrpc": "2.0", "method": "tools/list", "id": 1}' | bun src/mcp.ts --stdio 2>/dev/null
# Get stock prices for AAPL
echo '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "get_stock_prices", "arguments": {"symbol": "AAPL"}}, "id": 2}' | bun src/mcp.ts --stdio 2>/dev/null
# Get news articles
echo '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "get_news", "arguments": {"from": "20251220", "to": "20251222"}}, "id": 3}' | bun src/mcp.ts --stdio 2>/dev/null
📚 MCP Tools Reference
Tool 1: get_stock_prices
Query stock price data with automatic API fetching.
Parameters:
symbol(string, required) - Stock ticker symbol (e.g., "AAPL", "MSFT", "GOOGL")date(string, optional) - Specific date in YYYYMMDD format (e.g., "20251223")
Behavior:
- Queries MongoDB first
- If not found, automatically pulls from Alpha Vantage API
- Returns specific date data or latest 100 prices
- Indicates if data was "freshly pulled from API"
Example:
{
"name": "get_stock_prices",
"arguments": {
"symbol": "AAPL",
"date": "20251223"
}
}
Tool 2: get_news
Query financial news articles with sentiment analysis.
Parameters:
from(string, required) - Start date in YYYYMMDD formatto(string, required) - End date in YYYYMMDD formatkeyword(string, optional) - Filter by keyword in title/summary
Behavior:
- Queries news collection in MongoDB
- Filters by date range and optional keyword
- Returns articles with sentiment scores and ticker sentiment
Example:
{
"name": "get_news",
"arguments": {
"from": "20251220",
"to": "20251222",
"keyword": "market"
}
}
🎯 Key Features
Auto-Pull Feature
The MCP server automatically fetches missing stock data from the Alpha Vantage API when queried. This provides a seamless experience - users can query any stock symbol without manually pulling data first.
How it works:
- User queries a stock symbol
- Server checks MongoDB
- If not found, automatically calls Alpha Vantage API
- Stores data in MongoDB
- Returns the data with "(freshly pulled from API)" indicator
Intelligent Error Handling
- Missing
.keylistfile: Provides setup instructions and manual pull alternative - Invalid API keys: Clear error messages with documentation links
- Rate limit errors: Helpful guidance on API limits
- All errors include actionable next steps
Path Resolution
The .keylist file is located using absolute path resolution based on the source file location. This ensures the server works regardless of the working directory.
Rate Limiting
- Automatic 5-second delay after API calls
- Round-robin key rotation from
.keylistfile - Respects Alpha Vantage free tier limits (5 calls/minute, 500 calls/day)
📁 Project Structure
alphavantage/
├── .claude/
│ └── commands/ # Slash commands for development workflow
│ ├── 00-get-keys.md
│ ├── 01-mongo-crud.md
│ ├── 02-core-business.md
│ ├── 03-run-cli.md
│ └── 04-build-mcp.md
├── src/
│ ├── mongo.ts # MongoDB CRUD utilities
│ ├── business.ts # Alpha Vantage API integration
│ ├── run-stocks.ts # CLI tool
│ └── mcp.ts # MCP server implementation
├── .env # Environment variables
├── .keylist # Alpha Vantage API keys (one per line)
├── package.json
├── README.md
├── MCP-SERVER-README.md # Detailed MCP server documentation
└── SETUP-KEYLIST.md # .keylist setup guide
🔧 Configuration
Environment Variables
Create a .env file:
MONGODB_CONNECTION_STRING=mongodb://localhost:27017
API Keys
Create a .keylist file with your Alpha Vantage API keys (one per line):
YOUR_API_KEY_1
YOUR_API_KEY_2
YOUR_API_KEY_3
See SETUP-KEYLIST.md for detailed setup instructions.
📖 Additional Documentation
- MCP-SERVER-README.md - Detailed MCP server documentation
- SETUP-KEYLIST.md - Complete .keylist setup guide
- AUTO-PULL-FEATURE.md - Auto-pull feature documentation
- ERROR-HANDLING-UPDATE.md - Error handling details
- PATH-RESOLUTION-FIX.md - Path resolution implementation
🤝 Contributing
This project follows a systematic development pattern that can be adapted for other MCP servers. Feel free to use it as a template!
📝 License
This project was created using bun init in bun v1.2.20. Bun is a fast all-in-one JavaScript runtime.
🔗 Resources
- MCP Template Repository
- Alpha Vantage API Documentation
- Model Context Protocol Specification
- Bun Documentation
- Video Tutorial
💡 Tips
- Start with the CLI - Build and test your business logic with a CLI tool before creating the MCP server
- Use the template - The bun-mcp-template provides a solid foundation
- Test thoroughly - Create test scripts for each component (MongoDB, API, MCP tools)
- Document errors - Provide helpful error messages with actionable guidance
- Handle edge cases - Consider rate limits, missing data, network errors, etc.
🐛 Troubleshooting
MCP Server Not Connecting
- Verify MongoDB is running:
mongo --versionor check Docker container - Check
.envfile has correctMONGODB_CONNECTION_STRING - Ensure the path in MCP config matches your actual project location
- Check MCP client logs for specific errors
Auto-Pull Not Working
- Verify
.keylistfile exists in project root - Check API keys are valid (test with CLI:
bun src/run-stocks.ts --pull-stock AAPL) - Ensure you haven't hit rate limits (5 calls/minute, 500 calls/day)
- Check server logs for specific error messages
Path Resolution Issues
The .keylist file must be in the project root. If you get "file not found" errors, verify:
ls -la .keylist
The server uses absolute path resolution, so it should work from any directory.
Built with ❤️ using Bun and the Model Context Protocol
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。
