Skip to content
videodataapi.com
Python @tool + MCPSetup time: ~2 minutes · Zero proxy config

LangChain YouTube Transcript & Search Tool (Python/MCP)

Equip LangChain, LangGraph, and ReAct agents with typed Python @tool functions for real-time YouTube search and verbatim transcript extraction — or attach all 8 endpoints in 5 lines via our Model Context Protocol server.

$1.00 / 1K PAYG (~$0.60 / 1K on Pro · ~$0.40 / 1K on Business)

GET /v1/youtube/search →1 Credit / video (min 10)

$0.10 / 1K PAYG ($0.04–$0.06 / 1K on Pro & Business)

Copy or Download Template

Ready-to-Import Code & Configuration

Need an API key? Claim 3,000 Free Credits ($0.30) →
youtube_langchain_tools.py (@tool via langchain-core)
"""
VideoData API — Ready-to-Run LangChain @tool Definitions (langchain-core)
Install: pip install langchain-core langchain-openai httpx pydantic
Env:     export VIDEODATAAPI_KEY="yt_live_your_key"
"""

import os
from typing import Optional
import httpx
from pydantic import BaseModel, Field
from langchain_core.tools import tool

VIDEODATA_API_BASE = "https://api.videodataapi.com/v1/youtube"


def _headers() -> dict[str, str]:
    api_key = os.environ.get("VIDEODATAAPI_KEY", "").strip()
    if not api_key:
        raise RuntimeError("Set VIDEODATAAPI_KEY from https://videodataapi.com/dashboard")
    return {"x-api-key": api_key, "Accept": "application/json"}


class TranscriptInput(BaseModel):
    video_id: str = Field(
        description="11-character YouTube video ID or full watch/Shorts URL (e.g. 'dQw4w9WgXcQ')."
    )
    lang: str = Field(
        default="en",
        description="Preferred ISO 639-1 subtitle language code, e.g. 'en', 'es', 'de', 'ja'.",
    )


class SearchInput(BaseModel):
    query: str = Field(description="YouTube search keyword or topic phrase.")
    sort_by: str = Field(
        default="relevance",
        description="Sort order: 'relevance', 'upload_date', 'view_count', or 'rating'.",
    )
    limit: int = Field(default=10, ge=1, le=50, description="Max videos to return (1-50).")


@tool("youtube_transcript", args_schema=TranscriptInput)
def youtube_transcript(video_id: str, lang: str = "en") -> dict:
    """Fetch timed subtitle segments and full plain-text RAG transcript for a YouTube video (10 Credits = $0.001)."""
    with httpx.Client(timeout=20.0) as client:
        resp = client.get(
            f"{VIDEODATA_API_BASE}/transcript",
            params={"video_id": video_id, "lang": lang},
            headers=_headers(),
        )
        resp.raise_for_status()
        data = resp.json().get("data", {})
        return {
            "video_id": data.get("video_id", video_id),
            "language": data.get("language", lang),
            "available_languages": data.get("available_languages", []),
            "segment_count": len(data.get("segments", [])),
            "full_text": (data.get("full_text") or "")[:40000],
        }


@tool("youtube_search", args_schema=SearchInput)
def youtube_search(query: str, sort_by: str = "relevance", limit: int = 10) -> list[dict]:
    """Search YouTube videos & Shorts by keyword without Google 100-unit quota caps (1 Credit/video, min 10 Credits)."""
    with httpx.Client(timeout=20.0) as client:
        resp = client.get(
            f"{VIDEODATA_API_BASE}/search",
            params={"query": query, "sort_by": sort_by},
            headers=_headers(),
        )
        resp.raise_for_status()
        items = resp.json().get("items", [])[:limit]
        return [
            {
                "video_id": item.get("video_id") or item.get("id"),
                "title": item.get("title"),
                "channel": item.get("channel_handle") or item.get("channel_title"),
                "views": item.get("view_count"),
                "published": item.get("published_text") or item.get("published_at"),
                "url": f"https://www.youtube.com/watch?v={item.get('video_id') or item.get('id')}",
            }
            for item in items
        ]


if __name__ == "__main__":
    # Quick local smoke test with LangChain tool invocation:
    hits = youtube_search.invoke({"query": "RAG pipeline evaluation", "limit": 3})
    print("Top search hits:", hits)
    if hits and hits[0].get("video_id"):
        tx = youtube_transcript.invoke({"video_id": hits[0]["video_id"], "lang": "en"})
        print("Transcript preview:", tx["full_text"][:400])
youtube_mcp_agent.py (MultiServerMCPClient -> /mcp)
# Zero-Boilerplate Alternative: Connect directly to VideoData API's Remote Streamable HTTP MCP (/mcp)
# Install: pip install langchain-mcp-adapters langgraph langchain-openai

import asyncio
import os
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent


async def run_youtube_mcp_agent():
    client = MultiServerMCPClient(
        {
            "videodataapi": {
                "transport": "streamable_http",
                "url": "https://api.videodataapi.com/mcp",
                "headers": {"x-api-key": os.environ["VIDEODATAAPI_KEY"]},
            }
        }
    )
    tools = await client.get_tools()
    agent = create_react_agent("openai:gpt-4o-mini", tools)
    result = await agent.ainvoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": "Search top 3 LangGraph tutorials on YouTube and summarize the #1 video transcript.",
                }
            ]
        }
    )
    print(result["messages"][-1].content)


if __name__ == "__main__":
    asyncio.run(run_youtube_mcp_agent())

Using Claude Desktop, Claude Web, Cursor, or Windsurf alongside LangChain? View 1-click OAuth 2.1 and Streamable HTTP setup on our /mcp Model Context Protocol guide.

How This Pipeline Works

  1. 01

    Pydantic-Typed @tool Schemas (langchain-core)

    Exposes youtube_search and youtube_transcript with strict Pydantic v2 parameter descriptions so tool-calling LLMs pass valid 11-char IDs, sort modes, and ISO language codes.

  2. 02

    Quota-Free Discovery via GET /v1/youtube/search

    Replaces Google Data API v3's 100-unit search.list cap (which exhausts after 100 searches/day) with 50-item JSON pages at $0.10 per 1,000 videos.

  3. 03

    Pre-Joined RAG Corpus via GET /v1/youtube/transcript

    Returns both timed segments and a clean pre-joined full_text string ready for RecursiveCharacterTextSplitter or direct long-context agent injection.

  4. 04

    Optional 5-Line MCP Adapter (/mcp)

    Prefer zero custom tool code? Connect MultiServerMCPClient directly to https://api.videodataapi.com/mcp to unlock all 8 YouTube tools automatically.

Quick Setup Checklist

  1. 01Install dependencies: pip install langchain-core httpx pydantic (plus langchain-mcp-adapters langgraph if using MCP).
  2. 02Grab your instant API key with 3,000 Free Credits ($0.30, no card required) at videodataapi.com/signup and export VIDEODATAAPI_KEY=yt_live_...
  3. 03Bind [youtube_search, youtube_transcript] to ChatOpenAI / ChatAnthropic via llm.bind_tools(...) or pass directly to LangGraph create_react_agent.
  4. 04Explore full MCP configuration for Claude Desktop, Cursor, and Windsurf on our /mcp integration page.

Transparent Credit Pricing

  • • Transcripts / Video Metadata / Channels: 10 Credits = $1.00 / 1,000 PAYG (~$0.60/1K Pro · ~$0.40/1K Business)
  • • Search / Channel Videos / Shorts / Comments: 1 Credit / item (min 10) = $0.10 / 1,000 PAYG ($0.04–$0.06/1K Pro & Business)
  • • Zero-Risk Guarantee: 0 Credits charged on failed calls or empty results. Full rate card →

Frequently Asked Questions

Why use VideoData API instead of LangChain's built-in YoutubeLoader?

LangChain's default YoutubeLoader wraps the open-source youtube-transcript-api Python package, which scrapes youtube.com directly from your application server IP and fails on AWS, GCP, Fly.io, Render, and Vercel with IpBlocked / RequestBlocked exceptions. VideoData API handles upstream routing server-side over clean HTTPS.

What does each LangChain agent tool call cost in production?

youtube_search costs 1 Credit per returned video (minimum 10 Credits = $0.001 per call, or $0.10 per 1,000 videos; $0.04–$0.06/1K on Pro & Business). youtube_transcript costs a flat 10 Credits ($0.001 = $1.00 per 1,000 transcripts; ~$0.40–$0.58/1K on Pro & Business). Empty searches or missing transcripts cost 0 Credits.

Should I use the @tool Python functions or MultiServerMCPClient?

Use the @tool functions when you want explicit control over context truncation, chunking, or custom Pydantic schemas inside Python microservices. Use MultiServerMCPClient (see /mcp) when you want instant access to all 8 endpoints (transcripts, video info, search, comments, channels, trending, and Shorts) with zero tool wrapper maintenance.

More Workflow Integrations

← View All Integrations