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
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
E2B
Using MCP to run code via e2b.
