# How to integrate Youtube MCP with LlamaIndex

```json
{
  "title": "How to integrate Youtube MCP with LlamaIndex",
  "toolkit": "Youtube",
  "toolkit_slug": "youtube",
  "framework": "LlamaIndex",
  "framework_slug": "llama-index",
  "url": "https://composio.dev/toolkits/youtube/framework/llama-index",
  "markdown_url": "https://composio.dev/toolkits/youtube/framework/llama-index.md",
  "updated_at": "2026-05-12T10:31:01.431Z"
}
```

## Introduction

This guide walks you through connecting Youtube to LlamaIndex using the Composio tool router. By the end, you'll have a working Youtube agent that can list your most recent uploaded videos, get subscriber count for your channel, search youtube for trending tutorials through natural language commands.
This guide will help you understand how to give your LlamaIndex agent real control over a Youtube account through Composio's Youtube MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate Youtube with

- [ChatGPT](https://composio.dev/toolkits/youtube/framework/chatgpt)
- [OpenAI Agents SDK](https://composio.dev/toolkits/youtube/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/youtube/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/youtube/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/youtube/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/youtube/framework/codex)
- [Cursor](https://composio.dev/toolkits/youtube/framework/cursor)
- [VS Code](https://composio.dev/toolkits/youtube/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/youtube/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/youtube/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/youtube/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/youtube/framework/cli)
- [Google ADK](https://composio.dev/toolkits/youtube/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/youtube/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/youtube/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/youtube/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/youtube/framework/crew-ai)

## 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 Youtube
- Connect LlamaIndex to the Youtube MCP server
- Build a Youtube-powered agent using LlamaIndex
- Interact with Youtube 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 Youtube MCP server, and what's possible with it?

The Youtube MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Youtube account. It provides structured and secure access to your channel data, so your agent can perform actions like searching videos, managing playlists, retrieving channel insights, and handling subscriptions on your behalf.
- Channel activity monitoring: Let your agent fetch and summarize recent channel activities, including uploads, likes, playlist additions, and more, to keep you up to date at a glance.
- Automated video and playlist management: Easily list videos from any channel, retrieve your own playlists, and organize your content—all through AI-driven commands.
- Channel analytics and statistics: Ask your agent to pull detailed channel metrics such as subscriber counts, total views, or video counts for quick reporting and insights.
- Subscription management: Have your agent list your current subscriptions or even subscribe you to new channels based on your interests or instructions.
- Search and caption handling: Empower your agent to search YouTube for videos, channels, or playlists, as well as retrieve and download caption tracks for accessible viewing and content repurposing.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `YOUTUBE_ADD_VIDEO_TO_PLAYLIST` | Add Video to Playlist | Tool to add a video to a playlist by inserting a playlist item. Use when organizing videos into playlists or building curated collections. |
| `YOUTUBE_CREATE_CHANNEL_SECTION` | Insert Channel Section | Tool to create a new channel section for the authenticated user's YouTube channel. Use when organizing channel content into sections like featured playlists, recent uploads, or featured channels. |
| `YOUTUBE_CREATE_COMMENT_REPLY` | Insert Comment Reply | Tool to create a reply to an existing YouTube comment. Use when responding to user comments or engaging in conversations on videos. |
| `YOUTUBE_CREATE_PLAYLIST` | Create Playlist | Tool to create a new YouTube playlist on the authenticated user's channel. Use when organizing videos into collections or building curated playlists. |
| `YOUTUBE_DELETE_CHANNEL_SECTION` | Delete Channel Section | Tool to delete a YouTube channel section. Use when you need to remove a channel section from a channel. The channel section must exist and the authenticated user must have permission to delete it. |
| `YOUTUBE_DELETE_COMMENT` | Delete Comment | Tool to delete a YouTube comment owned by the authenticated user or channel. Use when you need to remove a comment from a video. The comment must exist and be owned by the authenticated channel. |
| `YOUTUBE_DELETE_PLAYLIST` | Delete Playlist | Tool to delete a YouTube playlist owned by the authenticated user/channel. Use when you need to permanently remove a playlist from YouTube. Requires explicit confirmation via `confirmDelete: true` to prevent accidental deletions. |
| `YOUTUBE_DELETE_PLAYLIST_ITEM` | Delete Playlist Item | Tool to delete a playlist item (remove a video from a playlist). Use when removing specific videos from playlists. |
| `YOUTUBE_DELETE_VIDEO` | Delete Video | Tool to delete a YouTube video owned by the authenticated user/channel. Use when you need to permanently remove a video from YouTube. Requires explicit confirmation via `confirmDelete: true` to prevent accidental deletions. The video must exist and be owned by the authenticated channel. |
| `YOUTUBE_GET_CHANNEL_ACTIVITIES` | Get Channel Activities | Gets recent activities from a YouTube channel including video uploads, playlist additions, likes, and other channel events. |
| `YOUTUBE_GET_CHANNEL_ID_BY_HANDLE` | Get channel ID by handle | Retrieves the YouTube Channel ID for a specific YouTube channel handle. |
| `YOUTUBE_GET_CHANNEL_STATISTICS` | Get Channel Statistics | Gets detailed statistics for YouTube channels including subscriber counts, view counts, and video counts. Channels can be identified using their ID, handle (e.g., @Google), or username. |
| `YOUTUBE_GET_VIDEO_DETAILS_BATCH` | Video Details Batch | Retrieves multiple YouTube video resource parts in a single batch call. Use when you need cohort-level metrics for many videos to reduce quota usage and latency. |
| `YOUTUBE_GET_VIDEO_RATING` | Get Video Rating | Retrieves the ratings that the authorized user gave to a list of specified videos. Use when you need to check if a user has liked or disliked specific videos. |
| `YOUTUBE_LIST_CAPTION_TRACK` | List captions | Retrieves a list of caption tracks for a YouTube video. Returns an empty items list if no captions are available. Raises ExecutionFailed if the video ID is invalid or not found. |
| `YOUTUBE_LIST_CHANNEL_SECTIONS` | List Channel Sections | Tool to retrieve channel sections from YouTube. Use when you need to get the layout sections of a channel's homepage. Channel sections organize content into categories like playlists, uploads, or featured channels. |
| `YOUTUBE_LIST_CHANNEL_VIDEOS` | List channel videos | Lists videos from a specified YouTube channel. This action primarily uses the playlistItems.list endpoint with the channel's uploads playlist, which is the recommended approach by YouTube. The uploads playlist ID is obtained by fetching the channel resource via the Channels API and extracting the playlist ID from contentDetails.relatedPlaylists.uploads field. If the uploads playlist returns a 404 error (which can happen due to a known YouTube API bug where the returned playlist ID doesn't actually exist), the action automatically falls back to the search.list endpoint to retrieve channel videos. Note that the search fallback has higher quota cost (100 units vs 1 unit) and is limited to 500 results. If a channel exists but has no uploads playlist (e.g., brand accounts, channels with all videos deleted, or channels that haven't uploaded any public content), an empty result set is returned instead of an error. |
| `YOUTUBE_LIST_COMMENTS` | List Comments | List individual comments from YouTube videos. Returns comment details including author, text, timestamps, and engagement metrics. Use 'id' parameter to retrieve specific comments or 'parentId' to retrieve all replies to a top-level comment. |
| `YOUTUBE_LIST_COMMENT_THREADS2` | List Comment Threads | Tool to retrieve comment threads from YouTube videos or channels matching API request parameters. Use when you need to fetch comments with filtering by video, channel, or specific thread IDs. |
| `YOUTUBE_LIST_I18N_LANGUAGES` | List I18n Languages | Returns a list of application languages that the YouTube website supports. Use this when you need to retrieve all available language options for YouTube's interface or to localize content. |
| `YOUTUBE_LIST_I18N_REGIONS` | List I18n Regions | Tool to retrieve a list of content regions that the YouTube website supports. Returns region codes (ISO 3166-1 alpha-2) and localized region names. Use when you need to identify available geographic regions for content filtering or display. |
| `YOUTUBE_LIST_LIVE_CHAT_MESSAGES` | List Live Chat Messages | Tool to list live chat messages for a specific chat. Use for monitoring live chat during broadcasts or retrieving chat history. Returns messages with author details, timestamps, and message types (text, Super Chat, moderation events). |
| `YOUTUBE_LIST_PLAYLIST_IMAGES` | List Playlist Images | Tool to retrieve playlist images associated with a specific playlist. Use when fetching custom thumbnail images for playlists. |
| `YOUTUBE_LIST_PLAYLIST_ITEMS` | List Playlist Items | Tool to list videos in a playlist, with pagination support. Use when walking through a channel's uploads playlist to enumerate all videos. |
| `YOUTUBE_LIST_SUPER_CHAT_EVENTS` | List Super Chat Events | Lists Super Chat events for a channel, showing supporter purchases during live streams. Returns Super Chat and Super Sticker events from the past 30 days. Use to track and acknowledge supporter contributions. |
| `YOUTUBE_LIST_USER_PLAYLISTS` | List user playlists | Retrieves playlists owned by the authenticated user, implicitly using mine=True. |
| `YOUTUBE_LIST_USER_SUBSCRIPTIONS` | List user subscriptions | Retrieves the authenticated user's YouTube channel subscriptions, allowing specification of response parts and pagination. |
| `YOUTUBE_LIST_VIDEO_ABUSE_REPORT_REASONS` | List Video Abuse Report Reasons | Tool to retrieve a list of abuse report reasons that can be used to report abusive videos on YouTube. Use when you need to display available reporting categories or before calling videos.reportAbuse. Returns localized reason labels and optional secondary categorizations. |
| `YOUTUBE_LIST_VIDEO_CATEGORIES` | List Video Categories | Tool to list YouTube video categories that can be associated with videos. Use when you need to retrieve available video categories for a specific region or get details about specific category IDs. |
| `YOUTUBE_LOAD_CAPTIONS` | Download YouTube caption track | Downloads a specific YouTube caption track, which must be owned by the authenticated user, and returns its content as text. Note: This action requires you to own the video (YouTube Data API v3 restriction). Non-owned videos will return 403 Forbidden errors, including many auto-generated caption tracks. |
| `YOUTUBE_MULTIPART_UPLOAD_VIDEO` | Multipart upload video | Uploads a video to YouTube using multipart upload in a single request. Use when you want to upload both metadata and video file together. This action uploads the video file and metadata in one request, unlike resumable upload which requires two steps. |
| `YOUTUBE_POST_COMMENT` | Post Comment on Video | Tool to post a new top-level comment on a YouTube video. Use when creating comments to engage with video content or respond to user requests. |
| `YOUTUBE_RATE_VIDEO` | Rate Video | Tool to add a like or dislike rating to a YouTube video, or remove an existing rating. Use when you need to rate videos on behalf of the authenticated user. |
| `YOUTUBE_REPORT_VIDEO_ABUSE` | Report Video for Abuse | Tool to report a YouTube video for containing abusive content. Use when you need to flag videos that violate YouTube's community guidelines or contain harmful content. |
| `YOUTUBE_SEARCH_YOU_TUBE` | Search YouTube | Searches YouTube for videos, channels, or playlists using a query term, returning the raw API response. |
| `YOUTUBE_SET_COMMENT_MODERATION_STATUS` | Set Comment Moderation Status | Tool to set the moderation status of one or more YouTube comments. Use when moderating comments to hold for review, publish, or reject them. Optionally ban the comment author when rejecting. |
| `YOUTUBE_SUBSCRIBE_CHANNEL` | Subscribe to channel | Subscribes the authenticated user to a specified YouTube channel, identified by its unique `channelId` which must be valid and existing. |
| `YOUTUBE_UNSUBSCRIBE_CHANNEL` | Unsubscribe from channel | Tool to unsubscribe the authenticated user from a YouTube channel by deleting a subscription. Use when you need to remove an existing subscription. The subscription ID can be obtained from the `YOUTUBE_LIST_USER_SUBSCRIPTIONS` tool. |
| `YOUTUBE_UPDATE_CAPTION` | Update caption track | Updates a YouTube caption track's metadata such as name, language, or draft status. Use this to modify existing caption track properties without uploading new caption content. Note: Only properties specified in the snippet will be updated; unspecified properties retain their current values. |
| `YOUTUBE_UPDATE_CHANNEL` | Update channel | Updates a channel's metadata including branding settings and localizations. Only brandingSettings, invideoPromotion, and localizations properties can be updated. Requires the channel to be owned by the authenticated user. |
| `YOUTUBE_UPDATE_CHANNEL_SECTION` | Update Channel Section | Tool to update an existing YouTube channel section by ID. Use when modifying section properties like title, position, or featured content. |
| `YOUTUBE_UPDATE_COMMENT` | Update Comment | Tool to modify the text of an existing YouTube comment. Use when updating or correcting a previously posted comment. |
| `YOUTUBE_UPDATE_PLAYLIST` | Update Playlist | Tool to modify an existing YouTube playlist's metadata (title, description, privacy status). Use when updating playlist information for the authenticated user's channel. |
| `YOUTUBE_UPDATE_PLAYLIST_ITEM` | Update Playlist Item | Tool to modify a playlist item's properties such as position or note. Use when reordering videos in a playlist or updating item metadata. |
| `YOUTUBE_UPDATE_THUMBNAIL` | Update thumbnail | Sets the custom thumbnail for a YouTube video using an image from a URL. Requirements: - The authenticated user must own the video or have permission to edit it - The YouTube channel must be verified (phone verification required) to upload custom thumbnails - Image must be JPG, PNG, or GIF; under 2MB; recommended 1280x720 resolution (16:9 aspect ratio) |
| `YOUTUBE_UPDATE_VIDEO` | Update video | Updates metadata for a YouTube video identified by videoId, which must exist; an empty list for tags removes all existing tags. |
| `YOUTUBE_UPLOAD_VIDEO` | Upload video | Uploads a video from a local file path to a YouTube channel; the video file must be in a YouTube-supported format. |

## Supported Triggers

| Trigger slug | Name | Description |
|---|---|---|
| `YOUTUBE_NEW_ACTIVITY_TRIGGER` | New YouTube Activity | Triggers when a new activity is detected on a YouTube channel. |
| `YOUTUBE_NEW_PLAYLIST_ITEM_TRIGGER` | New Item in YouTube Playlist | Triggers when a new item is added to a YouTube playlist. |
| `YOUTUBE_NEW_PLAYLIST_TRIGGER` | New Playlist in YouTube Channel | Triggers when a new playlist is added to a YouTube channel. |
| `YOUTUBE_NEW_SUBSCRIPTION_TRIGGER` | New YouTube Channel Subscription | Triggers when a new channel is subscribed. |

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

The Youtube MCP server is an implementation of the Model Context Protocol that connects your AI agent to Youtube. It provides structured and secure access so your agent can perform Youtube 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 Youtube account and project
- Basic familiarity with async Python/Typescript

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

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 Youtube 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, youtube)
- 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 Youtube 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=["youtube"],
    )

    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 Youtube actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Youtube 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: ["youtube"],
    },
  );

  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 Youtube 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 Youtube
```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 Youtube, 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=["youtube"],
    )

    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 Youtube actions."
    system_prompt = """
    You are a helpful assistant connected to Composio Tool Router.
    Use the available tools to answer user queries and perform Youtube 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: ["youtube"],
    },
  );

  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 Youtube 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 Youtube to LlamaIndex through Composio's Tool Router MCP layer.
Key takeaways:
- Tool Router dynamically exposes Youtube 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 Youtube MCP Agent with another framework

- [ChatGPT](https://composio.dev/toolkits/youtube/framework/chatgpt)
- [OpenAI Agents SDK](https://composio.dev/toolkits/youtube/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/youtube/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/youtube/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/youtube/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/youtube/framework/codex)
- [Cursor](https://composio.dev/toolkits/youtube/framework/cursor)
- [VS Code](https://composio.dev/toolkits/youtube/framework/vscode)
- [OpenCode](https://composio.dev/toolkits/youtube/framework/opencode)
- [OpenClaw](https://composio.dev/toolkits/youtube/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/youtube/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/youtube/framework/cli)
- [Google ADK](https://composio.dev/toolkits/youtube/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/youtube/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/youtube/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/youtube/framework/mastra-ai)
- [CrewAI](https://composio.dev/toolkits/youtube/framework/crew-ai)

## Related Toolkits

- [Amara](https://composio.dev/toolkits/amara) - Amara is a collaborative platform for creating and managing subtitles and captions for videos. It helps make content accessible and multilingual for global audiences.
- [Cats](https://composio.dev/toolkits/cats) - Cats is an API with a huge library of cat images, breed data, and cat facts. It makes finding adorable cat photos and trivia effortless for your apps and users.
- [Chatfai](https://composio.dev/toolkits/chatfai) - Chatfai is an AI platform that lets users talk to AI versions of fictional characters from books, movies, and games. It offers an engaging, interactive experience for fans to chat, roleplay, and explore creative dialogues.
- [Cincopa](https://composio.dev/toolkits/cincopa) - Cincopa is a multimedia platform for uploading, managing, and customizing videos, images, and audio. It helps you deliver engaging media experiences with robust APIs and flexible integrations.
- [Dungeon fighter online](https://composio.dev/toolkits/dungeon_fighter_online) - Dungeon Fighter Online (DFO) is an arcade-style, side-scrolling action RPG packed with dynamic combat and progression. Play solo or with friends to battle monsters, complete quests, and upgrade your characters.
- [Elevenlabs](https://composio.dev/toolkits/elevenlabs) - Elevenlabs is an advanced AI voice generation platform for lifelike, multilingual speech synthesis. Perfect for creating natural voices for videos, apps, and business content in seconds.
- [Elevenreader](https://composio.dev/toolkits/elevenreader) - Elevenreader is an AI-powered text-to-speech service by ElevenLabs that converts written content into lifelike audio. It enables fast, natural audio generation from any text.
- [Epic games](https://composio.dev/toolkits/epic_games) - Epic Games is a leading video game publisher and digital storefront, known for Fortnite and Unreal Engine. It lets gamers access, manage, and purchase games all in one place.
- [Fal.ai](https://composio.dev/toolkits/fal_ai) - Fal.ai is a generative media platform offering 600+ AI models for images, video, voice, and audio. Developers use Fal.ai for fast, scalable access to cutting-edge generative AI tools.
- [Giphy](https://composio.dev/toolkits/giphy) - Giphy is the largest online library for searching and sharing GIFs and stickers. Instantly add vibrant animated content to your apps, chats, and workflows.
- [Headout](https://composio.dev/toolkits/headout) - Headout is a global platform for booking travel experiences, tours, and entertainment. It helps users discover and secure activities at top destinations, all in one place.
- [Imagekit io](https://composio.dev/toolkits/imagekit_io) - ImageKit.io is a cloud-based media management platform for image and video delivery. Instantly optimize, transform, and deliver visuals globally via a lightning-fast CDN.
- [Listennotes](https://composio.dev/toolkits/listennotes) - Listennotes is a powerful podcast search engine with a massive global database. Discover, search, and curate podcasts from around the world in seconds.
- [News api](https://composio.dev/toolkits/news_api) - News api is a REST API for searching and retrieving live news articles from across the web. Instantly access headlines, coverage, and breaking stories from thousands of sources.
- [RAWG Video Games Database](https://composio.dev/toolkits/rawg_video_games_database) - RAWG Video Games Database is the largest video game discovery and info service. Instantly access comprehensive details, ratings, and release dates for thousands of games.
- [Seat geek](https://composio.dev/toolkits/seat_geek) - SeatGeek is a live event platform offering APIs for concerts, sports, and theater data. Instantly access events, venues, and performers info for smarter ticketing and discovery.
- [Shotstack](https://composio.dev/toolkits/shotstack) - Shotstack is a cloud platform for programmatically generating videos, images, and audio. Automate creative content production at scale with flexible RESTful APIs.
- [Spotify](https://composio.dev/toolkits/spotify) - Spotify is a streaming service for music and podcasts with millions of tracks from artists worldwide. Enjoy personalized playlists, recommendations, and seamless listening across all your devices.
- [Ticketmaster](https://composio.dev/toolkits/ticketmaster) - Ticketmaster is a global platform for event discovery, ticket sales, and live entertainment management. Get real-time access to events and streamline ticketing for fans and organizers.
- [Gmail](https://composio.dev/toolkits/gmail) - Gmail is Google's email service with powerful spam protection, search, and G Suite integration. It keeps your inbox organized and makes communication fast and reliable.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and Youtube MCP?

With a standalone Youtube MCP server, the agents and LLMs can only access a fixed set of Youtube tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Youtube 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 Youtube tools.

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

Yes, absolutely. You can configure which Youtube 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 Youtube data and credentials are handled as safely as possible.

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