Build a Stock Market AI Assistant with the Massive API
April 22, 2026 · Tutorial · 12 min read
Imagine giving your users the ability to ask plain-English questions about the stock market and get real answers:
- "What's Apple trading at right now?"
- "Show me the options chain for Tesla expiring this Friday"
- "What were the top gainers today?"
- "Is the market open right now?"
With the Massive MCP server on Universal API, you can add this kind of AI-powered stock market intelligence to any website or application — without building a financial data pipeline from scratch.
The Massive MCP server wraps Polygon.io's comprehensive stock and options API into 13 AI-ready tools that any AI agent can call. In this tutorial, we'll walk through four different ways to integrate it, from a one-line HTML embed to building your own custom MCP server.
Choose Your Integration Path
| Approach | Difficulty | Best For | BYO API Key |
|---|---|---|---|
| Option A: Embed Widget | ⭐ Easy | Websites, no backend | Creator's key |
| Option B: Agent via API | ⭐⭐ Medium | Apps, chatbots, backends | ✅ Per-user keys |
| Option C: Call MCP Tools Directly | ⭐⭐⭐ Advanced | Custom pipelines, AI IDEs | ✅ Per-user keys |
| Option D: Build Your Own MCP Server | ⭐⭐⭐ Advanced | Custom APIs, monetization | ✅ Full control |
Prerequisites
Before we start, you'll need:
- A Universal API account — Sign up free (comes with 100 credits)
- A bearer token — Create one on the API Keys page
- A Polygon.io API key — Get one free (free tier: 5 API calls/minute)
Store Your Polygon API Key
The Massive MCP server reads your Polygon.io key automatically at runtime. Store it once and it works everywhere:
Via the Dashboard: Navigate to API Keys → Third-Party Keys and add:
- Service Name:
POLYGON_API_KEY - API Key: Your Polygon.io API key
Via the API:
curl -X POST https://api.universalapi.co/keys \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"serviceName": "POLYGON_API_KEY", "apiKey": "YOUR_POLYGON_KEY"}'How BYO Keys Work
When you call any MCP server or agent on Universal API, your stored third-party keys are automatically injected into the runtime environment. The MCP server code reads process.env.POLYGON_API_KEY — no manual plumbing needed. Each user gets their own isolated key injection, so multi-tenant apps work out of the box.
Option A: Embed a Stock Assistant on Your Website
Difficulty: ⭐ Easy · Time: 5 minutes · Code: 1 line of HTML
This is the fastest path. Drop a voice-enabled AI stock assistant widget onto any webpage using our CDN-hosted embed script.
Step 1: Create a Stock Market Agent
First, create an agent that connects to the Massive MCP server. You can do this via the Agents Dashboard or the API:
Agent Source Code:
import os
from strands import Agent
from strands.models import BedrockModel
from strands.tools.mcp import MCPClient
from mcp.client.streamable_http import streamablehttp_client
def create_agent():
model = BedrockModel(
model_id="us.anthropic.claude-sonnet-4-6",
region_name="us-east-1"
)
# Connect to the Massive (Polygon.io) MCP server
bearer_token = os.environ.get('UNIVERSALAPI_BEARER_TOKEN', '')
massive_client = MCPClient(
lambda: streamablehttp_client(
"https://mcp.api.universalapi.co/mcp/s/snowtimber/massive-stocks",
headers={"Authorization": f"Bearer {bearer_token}"}
)
)
system_prompt = """You are a helpful stock market assistant. You have access to
real-time stock data from the Massive (Polygon.io) API.
When users ask about stocks:
- Use get_snapshot to get current price, volume, and daily change
- Use get_previous_close for yesterday's closing data
- Use get_aggregates for historical price bars
- Use get_options_chain for options data
- Use get_market_status to check if markets are open
Always format prices as currency ($XXX.XX) and percentages with 2 decimal places.
If the market is closed, mention that and show the most recent data available."""
agent = Agent(
model=model,
tools=[massive_client],
system_prompt=system_prompt
)
return agent, [massive_client]Create it via the API:
curl -X POST https://api.universalapi.co/agent \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agentName": "stock-assistant",
"description": "AI stock market assistant powered by Massive/Polygon.io",
"sourceCode": "...the source code above...",
"visibility": "private"
}'Note the agentId from the response — you'll need it for the embed token.
Step 2: Create an Embed Token
Embed tokens are publishable keys that let you safely embed your agent on public websites:
Via the Dashboard: Go to API Keys → Embed Tokens and create a new token for your agent.
Via the API:
curl -X POST https://api.universalapi.co/embed-tokens \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"agentId": "YOUR_AGENT_ID",
"allowedDomains": ["yourdomain.com", "localhost"],
"greeting": "Hi! Ask me about any stock — prices, options, market status.",
"brandColor": "#10B981",
"position": "bottom-right"
}'Step 3: Add One Line of HTML
Drop this script tag on any page:
<script
src="https://cdn.universalapi.co/widget/v2.js"
data-agent="YOUR_AGENT_ID"
data-token="emb_pk_live_XXXXX"
data-mode="text"
async>
</script>That's it! Your users can now click the floating chat button and ask questions about any stock. The v2 widget supports text chat (ideal for stock queries), voice, or both modes — with streaming responses, conversation history, and a clean UI, all from the CDN.
Text vs Voice
For a stock market assistant, data-mode="text" is recommended since users typically want to read formatted price data, tables, and charts. Use data-mode="voice" for hands-free use, or data-mode="both" to let users toggle between text and voice.
Customization Options
| Attribute | Description | Default |
|---|---|---|
data-agent | Agent UUID (required) | — |
data-token | Embed token (required) | — |
data-mode | text, voice, or both | text |
data-position | bottom-right or bottom-left | bottom-right |
data-color | Brand color hex | #6366f1 |
data-greeting | Initial greeting message | — |
Option B: Create a Text Agent and Chat via API
Difficulty: ⭐⭐ Medium · Time: 10 minutes · Code: Python or curl
This approach gives you full control over the conversation. Create a stock agent and chat with it programmatically — perfect for building chatbots, Slack bots, or custom UIs.
Step 1: Create the Agent
Use the same source code from Option A. Create it via the dashboard or API.
Step 2: Chat with Your Agent
Once created, chat with it using the streaming API:
curl -X POST https://stream.api.universalapi.co/agent/YOUR_AGENT_ID/chat \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"prompt": "What is AAPL trading at right now?"}'Example response:
Apple (AAPL) is currently trading at **$198.42**, up **+1.23% ($2.41)**
on the day. Volume is 45.2M shares.
📊 Today's range: $196.80 — $199.15
📈 52-week range: $164.08 — $199.62Multi-Turn Conversations
Extract the conversationId from the __META__ line in the response to maintain context:
# First message
curl -X POST https://stream.api.universalapi.co/agent/YOUR_AGENT_ID/chat \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"prompt": "What is TSLA trading at?"}'
# Follow-up (using conversationId from previous response)
curl -X POST https://stream.api.universalapi.co/agent/YOUR_AGENT_ID/chat \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Show me its options chain expiring this Friday",
"conversationId": "conv-xxxxx"
}'Python Example
import requests
UAPI_TOKEN = "uapi_ut_XXXX_..."
AGENT_ID = "your-agent-id"
def ask_stock_question(prompt, conversation_id=None):
body = {"prompt": prompt}
if conversation_id:
body["conversationId"] = conversation_id
response = requests.post(
f"https://stream.api.universalapi.co/agent/{AGENT_ID}/chat",
headers={"Authorization": f"Bearer {UAPI_TOKEN}"},
json=body
)
return response.text
# Ask about a stock
print(ask_stock_question("What are the top gainers today?"))Option C: Call MCP Tools Directly
Difficulty: ⭐⭐⭐ Advanced · Time: 15 minutes · Best for: Custom pipelines, AI IDEs
Skip the agent layer entirely and call the Massive MCP server's tools directly. This gives you raw, structured JSON data — ideal for building dashboards, data pipelines, or integrating with your own AI models.
Connect from Claude Desktop / Cursor / Cline
Add this to your MCP client configuration (e.g., claude_desktop_config.json):
{
"mcpServers": {
"massive-stocks": {
"url": "https://mcp.api.universalapi.co/mcp/s/snowtimber/massive-stocks",
"headers": {
"Authorization": "Bearer YOUR_UAPI_TOKEN"
}
}
}
}Now you can ask Claude, Cursor, or Cline to look up stock data and it will call the Massive tools automatically.
Call Tools via HTTP (MCP Protocol)
You can also call tools directly using the MCP protocol over HTTP:
# Initialize the session
curl -X POST https://mcp.api.universalapi.co/mcp/s/snowtimber/massive-stocks \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "get_snapshot",
"arguments": {"ticker": "AAPL"}
},
"id": 1
}'Available Tools Reference
The Massive MCP server provides 13 tools covering stocks and options:
| Tool | Description | Example Use |
|---|---|---|
get_snapshot | Real-time quote with price, volume, change | Current price of AAPL |
get_previous_close | Previous day's OHLCV data | Yesterday's close for TSLA |
get_aggregates | Historical price bars (min/hour/day/week) | NVDA daily chart last 30 days |
get_trades | Recent trade executions | Last 10 trades for MSFT |
get_quotes | NBBO quote snapshots | Current bid/ask for SPY |
get_ticker_details | Company info, description, market cap | Details about AMZN |
get_related_companies | Similar companies by industry | Companies related to META |
search_tickers | Search for stocks by name or symbol | Search "artificial intelligence" |
get_market_status | Current market open/close status | Is the market open? |
get_market_holidays | Upcoming market holidays | Next market closure |
get_options_chain | Full options chain with Greeks | TSLA calls expiring May 2 |
get_options_contract | Single option contract details | Specific AAPL call contract |
get_gainers_losers | Top market movers | Today's biggest gainers |
Option D: Build Your Own MCP Server
Difficulty: ⭐⭐⭐ Advanced · Time: 30 minutes · Best for: Custom APIs, monetization
Want to wrap different Polygon.io endpoints, add custom logic, or build a server that combines multiple data sources? Create your own MCP server on Universal API.
Example: Custom Stock Screener MCP Server
const { McpServer } = require("@modelcontextprotocol/sdk/server/mcp.js");
const { z } = require("zod");
const https = require("https");
function createMcpServer() {
const server = new McpServer({
name: "my-stock-screener",
version: "1.0.0"
});
// Helper to call Polygon API
function callPolygon(path) {
const apiKey = process.env.POLYGON_API_KEY;
return new Promise((resolve, reject) => {
https.get(
`https://api.polygon.io${path}?apiKey=${apiKey}`,
(res) => {
let data = "";
res.on("data", (chunk) => (data += chunk));
res.on("end", () => resolve(JSON.parse(data)));
res.on("error", reject);
}
);
});
}
server.registerTool("stock_summary", {
title: "Stock Summary",
description: "Get a concise summary of a stock including price, change, and company info",
inputSchema: {
ticker: z.string().describe("Stock ticker symbol (e.g., AAPL)")
}
}, async ({ ticker }) => {
const symbol = ticker.toUpperCase();
// Fetch snapshot and details in parallel
const [snapshot, details] = await Promise.all([
callPolygon(`/v2/snapshot/locale/us/markets/stocks/tickers/${symbol}`),
callPolygon(`/v3/reference/tickers/${symbol}`)
]);
const tick = snapshot.ticker;
const info = details.results;
const summary = {
symbol: symbol,
name: info?.name,
price: tick?.day?.c,
change: tick?.todaysChange,
changePercent: tick?.todaysChangePerc,
volume: tick?.day?.v,
marketCap: info?.market_cap,
description: info?.description?.substring(0, 200)
};
return {
content: [{
type: "text",
text: JSON.stringify(summary, null, 2)
}]
};
});
return server;
}
module.exports = { createMcpServer };Deploy Your MCP Server
curl -X POST https://api.universalapi.co/mcp-admin \
-H "Authorization: Bearer YOUR_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"serverName": "my-stock-screener",
"description": "Custom stock screener combining price data with company info",
"sourceCode": "...the source code above...",
"visibility": "public"
}'Once created, your server gets its own MCP endpoint that anyone can connect to:
https://mcp.api.universalapi.co/mcp/s/YOUR_ALIAS/my-stock-screenerMonetize Your MCP Server
Want to earn money from your MCP server? Set author pricing and connect Stripe on the Author Dashboard. You earn a share of every invocation.
Bring Your Own API Key (Multi-Tenant)
If you're building a SaaS product where each customer should use their own Polygon.io API key, Universal API handles this automatically.
How It Works
- Each of your users creates their own Universal API account
- They store their Polygon.io key as
POLYGON_API_KEYin their Third-Party Keys - When they call the Massive MCP server (or an agent connected to it), their key is auto-injected
- No code changes needed — the same MCP server code works for every user
Storing Keys via the API
Your app can store keys on behalf of your users (with their UAPI token):
# Store the user's Polygon key
curl -X POST https://api.universalapi.co/keys \
-H "Authorization: Bearer USERS_UAPI_TOKEN" \
-H "Content-Type: application/json" \
-d '{"serviceName": "POLYGON_API_KEY", "apiKey": "USERS_POLYGON_KEY"}'Key Priority
If both the MCP server author and the calling user have a key stored:
- Author keys take priority — useful for servers that include API access in their pricing
- User keys are used as fallback — perfect for BYO-key models
This means you can build MCP servers that work in both modes: include your own key for a "batteries included" experience, or let power users bring their own key for higher rate limits.
What's Next?
Now that you have a stock market AI assistant, here are some ideas to take it further:
- 📅 Daily Market Summary: Set up a cron job to have your agent email you a market recap every evening
- 💬 Slack/Discord Bot: Connect your agent to Slack or Discord so your team can ask stock questions in chat
- 📱 Mobile App: Use the agent chat API to build a stock assistant into your iOS or Android app
- 🔄 Combine Data Sources: Connect multiple MCP servers (e.g., Massive + news search) for a comprehensive market intelligence agent
Ready to build your stock market AI? Sign up for Universal API and get 100 free credits to start. Check out the Massive MCP server to explore all 13 tools, or browse our MCP server catalog for more integrations.