# How to integrate Alpha vantage MCP with LlamaIndex

```json
{
  "title": "How to integrate Alpha vantage MCP with LlamaIndex",
  "toolkit": "Alpha vantage",
  "toolkit_slug": "alpha_vantage",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/alpha_vantage/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/alpha_vantage/framework/llama-index.md",
  "updated_at": "2026-10-04T17:17:52.181Z"
}
```

## Introduction

This guide walks you through connecting Alpha vantage to LlamaIndex 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 LlamaIndex 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)
- [OpenAI Agents SDK](https://composio.dev/toolkits/alpha_vantage/framework/open-ai-agents-sdk)
- [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)
- [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:
- Set your OpenAI and Composio API keys
- Install LlamaIndex and Composio packages
- Create a Composio Tool Router session for Alpha vantage
- Connect LlamaIndex to the Alpha vantage MCP server
- Build a Alpha vantage-powered agent using LlamaIndex
- Interact with Alpha vantage through natural language

## What is LlamaIndex?

LlamaIndex is a data framework for building LLM applications. It provides tools for connecting LLMs to external data sources and services through agents and tools.
Key features include:
- ReAct Agent: Reasoning and acting pattern for tool-using agents
- MCP Tools: Native support for Model Context Protocol
- Context Management: Maintain conversation context across interactions
- Async Support: Built for async/await patterns

## 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 you begin, make sure you have:
- Python 3.8/Node 16 or higher installed
- A Composio account with the API key
- An OpenAI API key
- A Alpha vantage account and project
- Basic familiarity with async Python/Typescript

### 1. Getting API Keys for OpenAI, Composio, and Alpha vantage

No description provided.

### 2. Installing dependencies

No description provided.
```python
pip install composio-llamaindex llama-index llama-index-llms-openai llama-index-tools-mcp python-dotenv
```

```typescript
npm install @composio/llamaindex @llamaindex/openai @llamaindex/tools @llamaindex/workflow dotenv
```

### 3. Set environment variables

Create a .env file in your project root:
These credentials will be used to:
- Authenticate with OpenAI's GPT-5 model
- Connect to Composio's Tool Router
- Identify your Composio user session for Alpha vantage access
```bash
OPENAI_API_KEY=your-openai-api-key
COMPOSIO_API_KEY=your-composio-api-key
COMPOSIO_USER_ID=your-user-id
```

### 4. Import modules

No description provided.
```python
import asyncio
import os
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();
```

### 5. Load environment variables and initialize Composio

No description provided.
```python
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set in the environment")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set in the environment")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set in the environment")
```

```typescript
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) throw new Error("OPENAI_API_KEY is not set");
if (!COMPOSIO_API_KEY) throw new Error("COMPOSIO_API_KEY is not set");
if (!COMPOSIO_USER_ID) throw new Error("COMPOSIO_USER_ID is not set");
```

### 6. Create a Tool Router session and build the agent function

What's happening here:
- We create a Composio client using your API key and configure it with the LlamaIndex provider
- We then create a tool router MCP session for your user, specifying the toolkits we want to use (in this case, alpha vantage)
- The session returns an MCP HTTP endpoint URL that acts as a gateway to all your configured tools
- LlamaIndex will connect to this endpoint to dynamically discover and use the available Alpha vantage tools.
- The MCP tools are mapped to LlamaIndex-compatible tools and plug them into the Agent.
```python
async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["alpha_vantage"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")

    description = "An agent that uses Composio Tool Router MCP tools to perform Alpha vantage actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Alpha vantage actions.
    """
    return ReActAgent(tools=tools, llm=llm, description=description, system_prompt=system_prompt, verbose=True)
```

```typescript
async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["alpha_vantage"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
        description : "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Alpha vantage actions." ,
    llm,
    tools,
  });

  return agent;
}
```

### 7. Create an interactive chat loop

No description provided.
```python
async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")
```

```typescript
async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}
```

### 8. Define the main entry point

What's happening here:
- We're orchestrating the entire application flow
- The agent gets built with proper error handling
- Then we kick off the interactive chat loop so you can start talking to Alpha vantage
```python
async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err) {
    console.error("Failed to start agent:", err);
    process.exit(1);
  }
}

main();
```

### 9. Run the agent

When prompted, authenticate and authorise your agent with Alpha vantage, then start asking questions.
```bash
python llamaindex_agent.py
```

```typescript
npx ts-node llamaindex-agent.ts
```

## Complete Code

```python
import asyncio
import os
import signal
import dotenv

from composio import Composio
from composio_llamaindex import LlamaIndexProvider
from llama_index.core.agent.workflow import ReActAgent
from llama_index.core.workflow import Context
from llama_index.llms.openai import OpenAI
from llama_index.tools.mcp import BasicMCPClient, McpToolSpec

dotenv.load_dotenv()

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
COMPOSIO_API_KEY = os.getenv("COMPOSIO_API_KEY")
COMPOSIO_USER_ID = os.getenv("COMPOSIO_USER_ID")

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is not set")
if not COMPOSIO_API_KEY:
    raise ValueError("COMPOSIO_API_KEY is not set")
if not COMPOSIO_USER_ID:
    raise ValueError("COMPOSIO_USER_ID is not set")

async def build_agent() -> ReActAgent:
    composio_client = Composio(
        api_key=COMPOSIO_API_KEY,
        provider=LlamaIndexProvider(),
    )

    session = composio_client.create(
        user_id=COMPOSIO_USER_ID,
        toolkits=["alpha_vantage"],
    )

    mcp_url = session.mcp.url
    print(f"Composio MCP URL: {mcp_url}")

    mcp_client = BasicMCPClient(mcp_url, headers={"x-api-key": COMPOSIO_API_KEY})
    mcp_tool_spec = McpToolSpec(client=mcp_client)
    tools = await mcp_tool_spec.to_tool_list_async()

    llm = OpenAI(model="gpt-5")
    description = "An agent that uses Composio Tool Router MCP tools to perform Alpha vantage actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Alpha vantage actions.
    """
    return ReActAgent(
        tools=tools,
        llm=llm,
        description=description,
        system_prompt=system_prompt,
        verbose=True,
    );

async def chat_loop(agent: ReActAgent) -> None:
    ctx = Context(agent)
    print("Type 'quit', 'exit', or Ctrl+C to stop.")

    while True:
        try:
            user_input = input("\nYou: ").strip()
        except (KeyboardInterrupt, EOFError):
            print("\nBye!")
            break

        if not user_input or user_input.lower() in {"quit", "exit"}:
            print("Bye!")
            break

        try:
            print("Agent: ", end="", flush=True)
            handler = agent.run(user_input, ctx=ctx)

            async for event in handler.stream_events():
                # Stream token-by-token from LLM responses
                if hasattr(event, "delta") and event.delta:
                    print(event.delta, end="", flush=True)
                # Show tool calls as they happen
                elif hasattr(event, "tool_name"):
                    print(f"\n[Using tool: {event.tool_name}]", flush=True)

            # Get final response
            response = await handler
            print()  # Newline after streaming
        except KeyboardInterrupt:
            print("\n[Interrupted]")
            continue
        except Exception as e:
            print(f"\nError: {e}")

async def main() -> None:
    agent = await build_agent()
    await chat_loop(agent)

if __name__ == "__main__":
    # Handle Ctrl+C gracefully
    signal.signal(signal.SIGINT, lambda s, f: (print("\nBye!"), exit(0)))
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nBye!")
```

```typescript
import "dotenv/config";
import readline from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

import { Composio } from "@composio/core";
import { LlamaindexProvider } from "@composio/llamaindex";

import { mcp } from "@llamaindex/tools";
import { agent as createAgent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";

dotenv.config();

const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const COMPOSIO_API_KEY = process.env.COMPOSIO_API_KEY;
const COMPOSIO_USER_ID = process.env.COMPOSIO_USER_ID;

if (!OPENAI_API_KEY) {
    throw new Error("OPENAI_API_KEY is not set in the environment");
  }
if (!COMPOSIO_API_KEY) {
    throw new Error("COMPOSIO_API_KEY is not set in the environment");
  }
if (!COMPOSIO_USER_ID) {
    throw new Error("COMPOSIO_USER_ID is not set in the environment");
  }

async function buildAgent() {

  console.log(`Initializing Composio client...${COMPOSIO_USER_ID!}...`);
  console.log(`COMPOSIO_USER_ID: ${COMPOSIO_USER_ID!}...`);

  const composio = new Composio({
    apiKey: COMPOSIO_API_KEY,
    provider: new LlamaindexProvider(),
  });

  const session = await composio.create(
    COMPOSIO_USER_ID!,
    {
      toolkits: ["alpha_vantage"],
    },
  );

  const mcpUrl = session.mcp.url;
  console.log(`Composio Tool Router MCP URL: ${mcpUrl}`);

  const server = mcp({
    url: mcpUrl,
    clientName: "composio_tool_router_with_llamaindex",
    requestInit: {
      headers: {
        "x-api-key": COMPOSIO_API_KEY!,
      },
    },
    // verbose: true,
  });

  const tools = await server.tools();

  const llm = openai({ apiKey: OPENAI_API_KEY, model: "gpt-5" });

  const agent = createAgent({
    name: "composio_tool_router_with_llamaindex",
    description:
      "An agent that uses Composio Tool Router MCP tools to perform actions.",
    systemPrompt:
      "You are a helpful assistant connected to Composio Tool Router."+
"Use the available tools to answer user queries and perform Alpha vantage actions." ,
    llm,
    tools,
  });

  return agent;
}

async function chatLoop(agent: ReturnType<typeof createAgent>) {
  const rl = readline.createInterface({ input, output });

  console.log("Type 'quit' or 'exit' to stop.");

  while (true) {
    let userInput: string;

    try {
      userInput = (await rl.question("\nYou: ")).trim();
    } catch {
      console.log("\nAgent: Bye!");
      break;
    }

    if (!userInput) {
      continue;
    }

    const lower = userInput.toLowerCase();
    if (lower === "quit" || lower === "exit") {
      console.log("Agent: Bye!");
      break;
    }

    try {
      process.stdout.write("Agent: ");

      const stream = agent.runStream(userInput);
      let finalResult: any = null;

      for await (const event of stream) {
        // The event.data contains the streamed content
        const data: any = event.data;

        // Check for streaming delta content
        if (data?.delta) {
          process.stdout.write(data.delta);
        }

        // Store final result for fallback
        if (data?.result || data?.message) {
          finalResult = data;
        }
      }

      // If no streaming happened, show the final result
      if (finalResult) {
        const answer =
          finalResult.result ??
          finalResult.message?.content ??
          finalResult.message ??
          "";
        if (answer && typeof answer === "string" && !answer.includes("[object")) {
          process.stdout.write(answer);
        }
      }

      console.log(); // New line after streaming completes
    } catch (err: any) {
      console.error("\nAgent error:", err?.message ?? err);
    }
  }

  rl.close();
}

async function main() {
  try {
    const agent = await buildAgent();
    await chatLoop(agent);
  } catch (err: any) {
    console.error("Failed to start agent:", err?.message ?? err);
    process.exit(1);
  }
}

main();
```

## Conclusion

You've successfully connected Alpha vantage to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Alpha vantage tools through an MCP endpoint
- LlamaIndex's ReActAgent handles reasoning and orchestration; Composio handles integrations
- The agent becomes more capable without increasing prompt size
- Async Python provides clean, efficient execution of agent workflows
You can easily extend this to other toolkits like Gmail, Notion, Stripe, GitHub, and more by adding them to the toolkits parameter.

## 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)
- [OpenAI Agents SDK](https://composio.dev/toolkits/alpha_vantage/framework/open-ai-agents-sdk)
- [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)
- [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 LlamaIndex?

Yes, you can. LlamaIndex 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)
