# How to integrate Alpha vantage MCP with OpenAI Agents SDK

```json
{
  "title": "How to integrate Alpha vantage MCP with OpenAI Agents SDK",
  "toolkit": "Alpha vantage",
  "toolkit_slug": "alpha_vantage",
  "framework": "OpenAI Agents SDK",
  "framework_slug": "open-ai-agents-sdk",
  "url": "https://composio.dev/toolkits/alpha_vantage/framework/open-ai-agents-sdk",
  "markdown_url": "https://composio.dev/toolkits/alpha_vantage/framework/open-ai-agents-sdk.md",
  "updated_at": "2026-10-04T17:17:52.181Z"
}
```

## Introduction

This guide walks you through connecting Alpha vantage to the OpenAI Agents SDK using the Composio tool router. By the end, you'll have a working Alpha vantage agent that can get latest brent crude oil prices, show upcoming earnings calendar for tech stocks, fetch annual balance sheet for apple through natural language commands.
This guide will help you understand how to give your OpenAI Agents SDK agent real control over a Alpha vantage account through Composio's Alpha vantage MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Alpha vantage with

- [Claude Code](https://composio.dev/toolkits/alpha_vantage/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/alpha_vantage/framework/claude-cowork)
- [Claude Agent SDK](https://composio.dev/toolkits/alpha_vantage/framework/claude-agents-sdk)
- [Codex](https://composio.dev/toolkits/alpha_vantage/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/alpha_vantage/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/alpha_vantage/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/alpha_vantage/framework/atomic-agent)
- [Google ADK](https://composio.dev/toolkits/alpha_vantage/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/alpha_vantage/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/alpha_vantage/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/alpha_vantage/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/alpha_vantage/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/alpha_vantage/framework/crew-ai)
- [Pydantic AI](https://composio.dev/toolkits/alpha_vantage/framework/pydantic-ai)
- [AutoGen](https://composio.dev/toolkits/alpha_vantage/framework/autogen)

## TL;DR

Here's what you'll learn:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for Alpha vantage
- Configure an AI agent that can use Alpha vantage as a tool
- Run a live chat session where you can ask the agent to perform Alpha vantage operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## What is the Alpha vantage MCP server, and what's possible with it?

The Alpha Vantage MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Alpha Vantage account. It provides structured and secure access to stock, options, forex, cryptocurrency, market, and economic data, so your agent can retrieve quotes, examine historical prices, track market activity, compare exchange rates, and research economic trends on your behalf.
- Stock quotes and company research: Have your agent retrieve current prices and volume, search for ticker symbols, review company fundamentals, and examine dividend histories.
- Historical market analysis: Direct your agent to study intraday, daily, weekly, or monthly stock prices and calculate sliding-window analytics for trend analysis.
- Market activity monitoring: Let the agent check whether global exchanges are open and identify top gainers, top losers, and the most actively traded US stocks.
- Currency, crypto, and options research: Instruct your agent to compare live currency exchange rates, examine forex and cryptocurrency price history, or retrieve historical options chains with Greeks and implied volatility.
- Economic trend tracking: Have your agent review inflation, consumer prices, unemployment, nonfarm payrolls, federal funds rates, and US Treasury yields.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `ALPHA_VANTAGE_ALL_COMMODITIES` | Get All Commodities Price Index | Tool to retrieve the global price index of all commodities. Use when you need monthly, quarterly, or annual aggregated price index data for commodities. |
| `ALPHA_VANTAGE_ALUMINUM` | ALUMINUM | Tool to fetch global aluminum prices. Use when you need monthly, quarterly, or annual LME aluminum price data. |
| `ALPHA_VANTAGE_BALANCE_SHEET` | Balance Sheet | Tool to return annual and quarterly balance sheets for a company. Use when you need detailed fiscal statements for analysis. Numeric fields may be returned as strings or empty values; treat empty/missing fields as null, not zero, before performing calculations. |
| `ALPHA_VANTAGE_BRENT` | Brent Crude Oil Prices | Tool to fetch Brent crude oil prices. Use when you need daily, weekly, or monthly Brent price data. |
| `ALPHA_VANTAGE_CASH_FLOW` | Cash Flow | Tool to return annual and quarterly cash flow statements for a company. Use when you need to analyze cash movements. |
| `ALPHA_VANTAGE_COFFEE` | Global Coffee Price | Tool to retrieve the global coffee price series. Use when you need historical monthly, quarterly, or annual coffee prices. |
| `ALPHA_VANTAGE_COMPANY_OVERVIEW` | Company Overview (Stocks Only) | Tool to retrieve company overview and fundamental data for individual company stocks. Note: This endpoint only works for stocks, not ETFs, mutual funds, or indices. Use after specifying a valid stock ticker symbol. Numeric fields (e.g., MarketCapitalization, SharesOutstanding, Beta, DividendYield, PERatio) are returned as strings and may be empty — treat empty/missing values as null, not zero. Fundamentals such as Beta, PERatio, and PayoutRatio may reflect different reporting periods across symbols; avoid naive cross-symbol aggregation without aligning periods. Check the as-of date in the response; SharesOutstanding and similar fields can lag corporate actions. Alpha Vantage enforces per-minute and per-day rate caps; throttle requests when processing bulk symbol lists. |
| `ALPHA_VANTAGE_COPPER` | COPPER | Tool to fetch global price of copper in monthly, quarterly, and annual intervals. Use when you need historical copper price series for analysis. |
| `ALPHA_VANTAGE_CORN` | Corn | Tool to retrieve global price of corn in monthly, quarterly, and annual intervals. Use after verifying API key when you need historical Corn price data. |
| `ALPHA_VANTAGE_COTTON` | COTTON | Tool to retrieve global cotton prices in monthly, quarterly, and annual intervals. Use when you need historical cotton price data. |
| `ALPHA_VANTAGE_CPI` | Consumer Price Index (CPI) | Tool to fetch monthly and semiannual Consumer Price Index (CPI) data of the United States. Use when you need inflation metrics or CPI historical data. |
| `ALPHA_VANTAGE_CRYPTO_INTRADAY` | Crypto Intraday Time Series | Tool to retrieve intraday time series data for cryptocurrencies with realtime updates. Use when you need high-frequency OHLCV data (open, high, low, close, volume) for a specific cryptocurrency/market pair within the trading day. |
| `ALPHA_VANTAGE_CURRENCY_EXCHANGE_RATE` | Currency Exchange Rate | Tool to retrieve real-time exchange rate for a currency pair. Use after confirming base and quote currency codes to get current rates. Rate is nested at response['Realtime Currency Exchange Rate']['5. Exchange Rate'] as a string; cast to float before calculations. Treat missing key or '0.00000000' as unavailable. On free-tier keys, throttling returns HTTP 200 with 'Information' or 'Note' field instead of data — inspect response body before parsing. Free-tier limits: ~5 requests/minute, ~25 requests/day. For historical or intraday data use ALPHA_VANTAGE_FX_DAILY or TWELVE_DATA_TIME_SERIES. |
| `ALPHA_VANTAGE_DIGITAL_CURRENCY_DAILY` | Digital Currency Daily Time Series | Tool to retrieve daily historical time series for a digital currency traded on a specific market. Use when needing daily OHLC and volume data for a crypto/fiat pair, refreshed daily at midnight UTC. |
| `ALPHA_VANTAGE_DIGITAL_CURRENCY_MONTHLY` | Digital Currency Monthly Time Series | Tool to retrieve monthly digital currency prices in a fiat currency. Use when needing long-term monthly OHLC and volume data for a given crypto/fiat pair. Always returns full history; no date range filtering — filter client-side. OHLCV response values are strings; convert to numeric types before calculations. |
| `ALPHA_VANTAGE_DIGITAL_CURRENCY_WEEKLY` | Digital Currency Weekly Time Series | Tool to retrieve weekly digital currency prices in a fiat currency. Use when needing weekly OHLC and volume data for a given crypto/fiat pair. |
| `ALPHA_VANTAGE_DURABLES` | Durable Goods Orders | Tool to fetch monthly manufacturers' new orders of durable goods data for the United States. Use when you need historical data on big-ticket consumer purchases like cars, appliances, and refrigerators. |
| `ALPHA_VANTAGE_EARNINGS` | Earnings | Tool to retrieve annual and quarterly earnings (EPS history) for a specific company symbol. Free tier limit: ~25 requests/day, 1 request/second; an 'Information' key or empty array in the response indicates rate limit exhaustion or missing data — avoid parallel calls. |
| `ALPHA_VANTAGE_EARNINGS_CALENDAR` | Earnings Calendar | Tool to return the earnings calendar for the next three months. Use when you need a schedule of upcoming earnings across symbols. Returned dates reflect local exchange time, not UTC; normalize to UTC before comparing against the horizon window. |
| `ALPHA_VANTAGE_EARNINGS_CALL_TRANSCRIPT` | Earnings Call Transcript | Tool to retrieve the earnings call transcript for a given company and quarter. Use after confirming symbol and quarter. Returns full transcript text and associated LLM-based sentiment signals. Transcripts may be unavailable for some quarters; verify available periods via ALPHA_VANTAGE_EARNINGS if response is empty. Free tier: ~25 requests/day, ~1 request/second — empty arrays or 'Information' messages may indicate rate limits rather than missing data; space out requests and avoid parallel calls. Transcripts can be very long; chunk or extract key sections before passing to an LLM. |
| `ALPHA_VANTAGE_FEDERAL_FUNDS_RATE` | Federal Funds Rate | Tool to fetch daily, weekly, and monthly federal funds rate data of the United States. Use when you need historical interest rate data from the US Federal Reserve for economic analysis. |
| `ALPHA_VANTAGE_FX_DAILY` | FX Daily Time Series | Tool to fetch daily time series (open, high, low, close) for a currency pair. Use after confirming base and quote currency codes to retrieve historical daily FX rates. Response keys are timestamp strings and are not guaranteed to be sorted; always sort explicitly to find the most recent entry. Weekends and market holidays are excluded from the series. |
| `ALPHA_VANTAGE_FX_INTRADAY` | FX Intraday Time Series | Tool to retrieve intraday OHLC time series for a forex pair at 1-60 minute intervals (premium endpoint). Use when you need minute-bar FX data for backtesting or monitoring. Note: This is a premium Alpha Vantage function; check entitlement if errors occur. |
| `ALPHA_VANTAGE_FX_MONTHLY` | FX Monthly Time Series | Tool to get monthly time series (open, high, low, close) for a currency pair. Use when you need historical monthly forex data for a given currency pair. Data is returned in reverse-chronological order; OHLC values are strings and must be cast to numeric types before computations. The most recent entry may represent an incomplete period — treat its OHLC values as preliminary until the month closes. |
| `ALPHA_VANTAGE_FX_WEEKLY` | FX Weekly Time Series | Tool to get weekly time series (open, high, low, close) for a currency pair. Use when you need weekly FX rates. Results are reverse-chronological; sort ascending and cast OHLC string values to numeric before computing indicators. The most recent entry may represent an incomplete week — treat its high, low, and close as provisional until the week closes. |
| `ALPHA_VANTAGE_GET_DIVIDENDS` | Get Dividend History | Tool to retrieve historical dividend payment records for a stock symbol. Use when you need dividend dates and amounts for analyzing company distributions. |
| `ALPHA_VANTAGE_GET_HISTORICAL_OPTIONS` | Get Historical Options | Tool to retrieve full historical options chain for a symbol on a specific date with 15+ years of history, including Greeks and IV. Use when you need historical options data with pricing, volume, and Greeks for analysis. Note: This is a premium Alpha Vantage endpoint. |
| `ALPHA_VANTAGE_GET_SLIDING_WINDOW_ANALYTICS` | Analytics Sliding Window | Tool to retrieve advanced analytics metrics with sliding window calculations for trend analysis. Use when you need to perform statistical analysis on stock price movements over time, such as calculating moving averages, standard deviations, variances, or correlations between multiple stocks. Ideal for technical analysis and identifying trends. |
| `ALPHA_VANTAGE_GLOBAL_QUOTE` | Global Quote | Tool to retrieve latest price and volume information for a specified security ticker in realtime. Use when you need current stock quote data with price, volume, and daily trading metrics. |
| `ALPHA_VANTAGE_INCOME_STATEMENT` | Income Statement | Tool to fetch annual and quarterly income statements. Use after confirming the company symbol. Numeric fields may be returned as strings or empty values — convert safely and treat empty/missing as null, not zero, before computing derived metrics. Some symbols may be missing fields entirely; treat absent fields as missing data rather than defaults. One API call per symbol; when processing multiple symbols, retain only key derived fields rather than full raw responses. |
| `ALPHA_VANTAGE_INFLATION` | Inflation | Tool to fetch annual U.S. inflation rates (consumer prices). Use when you need historical inflation data for economic analysis. |
| `ALPHA_VANTAGE_IPO_CALENDAR` | IPO Calendar | Tool to retrieve the IPO calendar for the next three months. Use when you need a list of upcoming IPO events across markets. |
| `ALPHA_VANTAGE_LISTING_STATUS` | Listing Status | Tool to fetch listing status of US stocks and ETFs. Use when you need active or delisted securities as of a date. |
| `ALPHA_VANTAGE_MARKET_STATUS` | Market Status | Tool to retrieve current market status (open/closed) for global stock exchanges. Use when you need to check if major trading venues worldwide are currently open or closed. |
| `ALPHA_VANTAGE_NEWS_SENTIMENT` | News Sentiment | Tool to fetch live and historical market news & sentiment. Use when you need curated news articles with sentiment scores for specified tickers and topics. |
| `ALPHA_VANTAGE_NONFARM_PAYROLL` | Nonfarm Payroll | Tool to fetch monthly U.S. nonfarm payroll employment data from the Bureau of Labor Statistics. Use when you need historical employment statistics for economic analysis. |
| `ALPHA_VANTAGE_REAL_GDP` | Real GDP | Tool to fetch U.S. real GDP time series. Use when you need quarterly or annual GDP data. |
| `ALPHA_VANTAGE_REAL_GDP_PER_CAPITA` | Real GDP Per Capita | Tool to fetch quarterly Real GDP per capita data of the United States. Use when you need real GDP per capita information adjusted for inflation. |
| `ALPHA_VANTAGE_REALTIME_BULK_QUOTES` | Realtime Bulk Quotes | Tool to retrieve realtime quotes for US-traded symbols in bulk (up to 100 symbols per request). Use when you need current price and volume data for multiple symbols simultaneously, covering both regular and extended trading hours. This is a premium API function requiring subscription. If subscription access is denied, use ALPHA_VANTAGE_GLOBAL_QUOTE for single-symbol quotes. |
| `ALPHA_VANTAGE_RETAIL_SALES` | Retail Sales | Tool to fetch monthly retail trade sales data of the United States. Use when you need historical U.S. retail sales statistics sourced from Census Bureau. |
| `ALPHA_VANTAGE_SECTOR` | Sector Performance | Tool to retrieve real-time and historical sector performance data. Use when you need sector performance metrics across timeframes. |
| `ALPHA_VANTAGE_SPLITS` | Stock Splits | Tool to retrieve historical stock split events for a symbol. Use when you need past split dates and ratio details before analyzing corporate actions. |
| `ALPHA_VANTAGE_SUGAR` | Global Sugar Price | Tool to retrieve the global sugar price series. Use when you need historical monthly, quarterly, or annual sugar prices. |
| `ALPHA_VANTAGE_SYMBOL_SEARCH` | Symbol Search | Tool to search for best-matching symbols based on keywords. Use when you need to find ticker symbols by a name or keyword. Returns multiple close matches — inspect the exchange, region, and currency fields in each result to select the correct symbol before passing it to downstream calls. Coverage excludes some exotic instruments and non-US assets; handle empty results explicitly. |
| `ALPHA_VANTAGE_TECHNICAL_INDICATOR` | Technical Indicator | Tool to fetch technical indicators for the specified equity or currency pair. Use after obtaining time series to compute moving averages or oscillators. Response body may contain 'Information' or 'Note' keys indicating errors or rate-limit signals — inspect payload before treating data as valid. Results are nested under a function-specific key (e.g., 'Technical Analysis: RSI') with values as strings; convert to numeric before calculations. No date range filtering supported; returns all available data points — filter client-side to the required window. |
| `ALPHA_VANTAGE_TIME_SERIES_DAILY` | Time Series Daily | Tool to retrieve daily time series data (date, daily open, high, low, close, volume) for a global equity symbol, covering 20+ years of historical data. Use when you need daily OHLCV data for a specific stock. |
| `ALPHA_VANTAGE_TIME_SERIES_INTRADAY` | Time Series Intraday | Tool to retrieve intraday OHLCV for a given equity. Use when you need high-frequency pricing data within the trading day. Always inspect the JSON response body for 'Information' or 'Error Message' fields — the API may return these instead of data even on HTTP 200. |
| `ALPHA_VANTAGE_TIME_SERIES_INTRADAY_EXTENDED` | Time Series Intraday Extended | Tool to retrieve historical intraday OHLCV data for the trailing 2 years, covering over 2 million data points per ticker. Use when you need extensive historical intraday pricing data for data visualization, trading simulation, backtesting, or machine learning applications with longer horizons. |
| `ALPHA_VANTAGE_TIME_SERIES_MONTHLY` | Time Series Monthly | Tool to retrieve monthly open, high, low, close, and volume for a global equity. Use when you need month-end OHLCV data for a specific stock symbol. |
| `ALPHA_VANTAGE_TIME_SERIES_MONTHLY_ADJUSTED` | Monthly Adjusted Time Series | Tool to retrieve monthly adjusted OHLC and volume for a global equity. Use after confirming the ticker symbol when you need end-of-month adjusted price and dividend data. Dividends are returned as a single aggregated value per month; annual or multi-year payout totals require manual summation across monthly data points. |
| `ALPHA_VANTAGE_TIME_SERIES_WEEKLY` | Weekly Time Series | Tool to fetch weekly open, high, low, close, and volume for a global equity symbol. Use after confirming the target symbol to obtain its historical weekly OHLCV series. Alpha Vantage enforces per-minute and per-day rate limits; throttle sequential calls combining this tool with other time series or fundamentals endpoints. |
| `ALPHA_VANTAGE_TIME_SERIES_WEEKLY_ADJUSTED` | Weekly Adjusted Time Series | Tool to fetch weekly adjusted time series data with split/dividend adjustments, covering 20+ years of historical data. Use after confirming the target symbol to obtain its historical weekly adjusted OHLCV series with dividend information. |
| `ALPHA_VANTAGE_TOP_GAINERS_LOSERS` | Top Gainers, Losers & Most Active | Tool to fetch the top 20 gainers, losers, and most actively traded US tickers. Use when you need current market movers data without maintaining a ticker universe. Data is updated end-of-day by default, with realtime/15-min delayed access available via premium. |
| `ALPHA_VANTAGE_TREASURY_YIELD` | US Treasury Yield | Tool to fetch US Treasury yield data for specified maturity and interval. Use when you need daily, weekly, or monthly treasury yield rates for various constant maturities (3-month, 2-year, 5-year, 7-year, 10-year, 30-year). |
| `ALPHA_VANTAGE_UNEMPLOYMENT` | Unemployment Rate | Tool to fetch monthly unemployment rate data of the United States. Use when you need historical U.S. unemployment statistics sourced from Bureau of Labor Statistics. |
| `ALPHA_VANTAGE_WHEAT` | WHEAT | Tool to fetch global price of wheat. Use when you need historical wheat prices in monthly, quarterly, or annual intervals. |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The Alpha vantage MCP server is an implementation of the Model Context Protocol that connects your AI agent to Alpha vantage. It provides structured and secure access so your agent can perform Alpha vantage operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live Alpha vantage project
- Some knowledge of Python or Typescript

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like Alpha vantage.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only alpha_vantage.
- The router checks the user's Alpha vantage connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access Alpha vantage.
- This approach keeps things lightweight and lets the agent request Alpha vantage tools only when needed during the conversation.
```python
# Create a Alpha vantage Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["alpha_vantage"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for Alpha vantage
const session = await composio.create(userId as string, {
  toolkits: ['alpha_vantage'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Alpha vantage. "
        "Help users perform Alpha vantage operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access Alpha vantage. Help users perform Alpha vantage operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["alpha_vantage"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access Alpha vantage. "
        "Help users perform Alpha vantage operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['alpha_vantage'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access Alpha vantage. Help users perform Alpha vantage operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating Alpha vantage MCP with OpenAI Agents SDK to build a functional AI agent that can interact with Alpha vantage.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build Alpha vantage MCP Agent with another framework

- [Claude Code](https://composio.dev/toolkits/alpha_vantage/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/alpha_vantage/framework/claude-cowork)
- [Claude Agent SDK](https://composio.dev/toolkits/alpha_vantage/framework/claude-agents-sdk)
- [Codex](https://composio.dev/toolkits/alpha_vantage/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/alpha_vantage/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/alpha_vantage/framework/hermes-agent)
- [Atomic Agent](https://composio.dev/toolkits/alpha_vantage/framework/atomic-agent)
- [Google ADK](https://composio.dev/toolkits/alpha_vantage/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/alpha_vantage/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/alpha_vantage/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/alpha_vantage/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/alpha_vantage/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/alpha_vantage/framework/crew-ai)
- [Pydantic AI](https://composio.dev/toolkits/alpha_vantage/framework/pydantic-ai)
- [AutoGen](https://composio.dev/toolkits/alpha_vantage/framework/autogen)

## Related Toolkits

- [Stripe](https://composio.dev/toolkits/stripe) - Stripe is a global online payments platform offering APIs for managing payments, customers, and subscriptions. Trusted by businesses for secure, efficient, and scalable payment processing worldwide.
- [44API](https://composio.dev/toolkits/44api) - 44API is an API service for validating VAT and tax identifiers and returning company details. Use it to verify business tax data and manage account IP whitelists quickly.
- [Airwallex](https://composio.dev/toolkits/airwallex) - Airwallex is a global financial platform providing business accounts, payments, payouts, FX, and cards. Built to simplify cross-border payments and streamline financial operations for businesses.
- [Aiwyn Tax MCP](https://composio.dev/toolkits/aiwyn_tax_mcp) - Aiwyn Tax MCP is a tax estimation service powered by Aiwyn's federal and state tax engine. It helps teams estimate tax outcomes without building tax calculation logic from scratch.
- [Alpaca](https://composio.dev/toolkits/alpaca) - Alpaca is a stock and crypto trading platform for commission-free trading, real-time market data, and algorithmic strategies. Use it to build brokerage apps, trading bots, and portfolio workflows with market connectivity.
- [Altoviz](https://composio.dev/toolkits/altoviz) - Altoviz is a cloud-based billing and invoicing platform for businesses. It streamlines online payments, expense tracking, and customizable invoice management.
- [Benzinga](https://composio.dev/toolkits/benzinga) - Benzinga provides real-time financial news and data APIs for market coverage. It helps you track breaking news and actionable market insights instantly.
- [Bigdata.com MCP](https://composio.dev/toolkits/bigdata_com_mcp) - Bigdata.com MCP provides grounded access to financial news, transcripts, filings, and entity intelligence. Ideal for building research workflows and generating timely market insights.
- [Billsby](https://composio.dev/toolkits/billsby) - Billsby is a subscription billing platform for managing customers, subscriptions, invoices, products, plans, usage counters, add-ons, and allowances. It helps SaaS and subscription teams automate billing operations without building complex billing logic from scratch.
- [Brex](https://composio.dev/toolkits/brex) - Brex provides corporate credit cards and spend management tailored for startups and tech businesses. It helps optimize company cash flow, streamline accounting, and accelerate business growth.
- [Cashfree Payments MCP](https://composio.dev/toolkits/cashfree_payments_mcp) - Cashfree Payments MCP is a merchant payments platform that handles collection, payouts, subscriptions, settlements, refunds, and identity verification. Simplifies merchant money lifecycle management with unified, API-driven workflows.
- [Chaser](https://composio.dev/toolkits/chaser) - Chaser is accounts receivable automation software that sends invoice reminders and helps businesses get paid faster. It streamlines the collections process to save time and improve cash flow.
- [Clarity AI MCP](https://composio.dev/toolkits/clarity_ai_mcp) - Clarity AI MCP is an MCP toolkit for simulating SFDR 2.0 fund classifications from a fund name, ISIN, or CUSIP. Use it to tap Clarity AI disclosure data and modeling without building custom sustainability-data workflows.
- [Clientary](https://composio.dev/toolkits/clientary) - Clientary is a platform for managing clients, invoices, projects, proposals, and more. It streamlines client work and saves you serious admin time.
- [Coinbase](https://composio.dev/toolkits/coinbase) - Coinbase is a platform for buying, selling, and storing cryptocurrency. It makes exchanging and managing crypto simple and secure for everyone.
- [Coinbase Agents MCP](https://composio.dev/toolkits/coinbase_agents_mcp) - Coinbase Agents MCP is Coinbase's managed toolkit exposing accounts, portfolios, orders, fills, and market data. Use it to let authorized agents inspect holdings, execute trades, perform transfers, and handle payments.
- [Coinbase Wallet MCP](https://composio.dev/toolkits/coinbase_wallet_mcp) - Coinbase Wallet MCP is Coinbase's wallet service for interacting with onchain accounts. Use it to give agents secure, structured access to inspect wallets and request onchain actions.
- [Coinranking](https://composio.dev/toolkits/coinranking) - Coinranking is a comprehensive cryptocurrency market data platform offering access to real-time coin prices, market caps, and historical data. Get accurate, up-to-date stats for thousands of digital assets in one place.
- [Coupa](https://composio.dev/toolkits/coupa) - Coupa is a business spend management platform for procurement, invoicing, and expenses. It helps organizations streamline purchasing, control costs, and gain complete visibility over financial operations.
- [CurrencyScoop](https://composio.dev/toolkits/currencyscoop) - CurrencyScoop is a developer-friendly API for real-time and historical currency exchange rates. Easily access fiat and crypto data for smart, up-to-date financial applications.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Alpha vantage MCP?

With a standalone Alpha vantage MCP server, the agents and LLMs can only access a fixed set of Alpha vantage tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Alpha vantage and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Alpha vantage tools.

### Can I manage the permissions and scopes for Alpha vantage while using Tool Router?

Yes, absolutely. You can configure which Alpha vantage scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Alpha vantage data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
