Skip to main content
Glama
YouTube MCP Server

YouTube MCP Server

YouTube MCP Server

A read-only Python toolkit for the YouTube Data API v3 and YouTube Analytics API v2:

  • youtube/ — a typed Python library (channels, videos, search, playlists, analytics, revenue)

  • mcp_server/ — a Model Context Protocol server so AI agents (Claude Desktop, Claude Code, …) can call it as tools

  • cli.py — a command-line interface for manual testing

Everything is read-only: nothing here can upload, edit, or delete. (The one exception is cli.py reporting create-job, which schedules Google-generated reports and does not touch the channel.)

How authentication works

The library uses the best credentials it can find, in this order:

#

What exists

What happens

Supports

1

token.json, valid

Used as-is

Everything

2

token.json, expired

Refreshed automatically and saved

Everything

3

client_secret.json, no token

OAuth browser flow runs, token saved to token.json (CLI only — the MCP server never opens a browser)

Everything

4

YOUTUBE_API_KEY in .env

API key used

Public data only — no analytics

5

Nothing

Clear error listing what to set up

—

If OAuth can't be used (say the refresh token was revoked) and an API key exists, the library falls back to the key and says why. Analytics operations called with only an API key fail immediately with:

OAUTH_REQUIRED: 'get_top_videos' requires OAuth authentication; only an API key is available. Run `python cli.py auth` to set up OAuth.

Run python cli.py auth-status at any time to see what's available and which operations work.

Related MCP server: YouTube MCP Server

Setup

1. Install

Python 3.10+.

git clone <this repo> youtube-mcp-server && cd youtube-mcp-server
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate
pip install -e ".[dev]"

2. Create a Google Cloud project

In the Google Cloud console:

  1. Create a project, or select an existing one.

  2. APIs & Services → Library: enable YouTube Data API v3 and YouTube Analytics API (and YouTube Reporting API if you want bulk reports).

Go to Google Auth Platform (older consoles: APIs & Services → OAuth consent screen).

  1. Branding: set an app name and support email.

  2. Audience → User type: choose External. If it shows Internal, click Make external.

  3. Audience → Test users: add the Google account you will sign in with.

  4. Audience → Publishing status: click Publish app and confirm. Do not submit for verification.

Publish it, because in Testing the login expires every 7 days (an AI agent can't sign in again on its own), and signing in as a Brand Account channel is usually refused. A published but unverified app works fine for this tool: you click past a warning when signing in (step 5), and it is limited to 100 users.

4. Create the OAuth client

  1. Google Auth Platform → Clients → Create client (or APIs & Services → Credentials → Create credentials → OAuth client ID).

  2. Application type: Desktop app.

  3. Download the JSON and save it as client_secret.json in the project root.

5. Sign in

python cli.py auth                  # opens a browser
python cli.py auth --no-browser     # prints the URL instead
python cli.py auth --with-comments  # also allow reading comments over OAuth (see Comments)
python cli.py auth --read-only      # never ask; comments need YOUTUBE_API_KEY
  1. Sign in with the Google account that owns or manages the channel.

  2. If Google says "Google hasn't verified this app", click Advanced → Go to (app name).

  3. Choose the account: Google may list your personal profile and the channels you manage (Brand Account channels are labelled YouTube). Use the account that you want to connect.

  4. Accept the read-only permissions.

  5. The command prints the connected channel. Confirm it is the right one, then run:

python cli.py auth-status

The token is saved to token.json. "My channel" means the channel you picked, everywhere. To switch channels, delete token.json and run python cli.py auth again.

Analytics needs a role on the channel that can view analytics (Manager or Owner). Revenue also needs a monetized channel.

6. API key (optional)

For reading comments with a strictly read-only login (see Comments), and for public data without OAuth (e.g. as a fallback).

  1. APIs & Services → Credentials → Create credentials → API key.

  2. Edit API key → API restrictions → Restrict key → tick only YouTube Data API v3 → Save.

  3. Add it to .env:

    cp .env.example .env
    # edit .env: YOUTUBE_API_KEY=...

With only an API key there is no "my channel": pass --channel UC... / @handle, or set YOUTUBE_CHANNEL_ID in .env. Analytics is not available.

client_secret.json, token.json and .env are gitignored. Never commit them.

Troubleshooting sign-in

Error

Fix

Error 403: org_internal

The consent screen is Internal. Audience → Make external, then sign in again. If External is blocked by an organization policy, ask your Workspace admin, or create the Cloud project under a personal Google account.

Error 403: access_denied ("can only be accessed by developer-approved testers")

Add your account under Audience → Test users. If it is already listed, or the error appears after picking a Brand Account channel, publish the app (step 3.4). Then delete token.json and sign in again.

"Google hasn't verified this app"

Normal. Click Advanced → Go to (app name).

"could not be refreshed"

The login expired or was revoked. Run python cli.py auth. If it happens every 7 days, the app is still in Testing: publish it.

Scopes requested (all read-only): youtube.readonly, yt-analytics.readonly, yt-analytics-monetary.readonly. With --with-comments, also youtube.force-ssl (see Comments).

Comments

Google won't let a read-only login read comments: over OAuth it requires youtube.force-ssl, a scope that can also edit and delete. Choose one:

Option

How

Trade-off

API key (default)

Set YOUTUBE_API_KEY (step 6)

The OAuth token stays strictly read-only. Held-for-review comments are not visible.

OAuth with comments

Delete token.json, run python cli.py auth --with-comments

No API key needed, but the saved token could edit and delete on the channel. This tool never does.

python cli.py auth checks for the key: with YOUTUBE_API_KEY set it signs in read-only, and without one it asks whether to grant comment access (default no). --with-comments / --read-only skip the question. If the token has the comments scope, comments go through OAuth; otherwise through the API key.

Optional settings (.env)

Variable

Purpose

YOUTUBE_API_KEY

API key for public read-only calls

YOUTUBE_CHANNEL_ID

Default channel (ID or @handle) when only an API key is set

YOUTUBE_CLIENT_SECRET_FILE

Path to the OAuth client JSON (default client_secret.json)

YOUTUBE_TOKEN_FILE

Where to store the OAuth token (default token.json)

YOUTUBE_REPORT_WEBHOOK

Slack-compatible webhook for report and alerts (a secret)

Relative paths are resolved against the project root, so the server works no matter which directory it's launched from.

CLI

python cli.py auth                                   # OAuth flow
python cli.py auth-status                            # what works with current credentials
python cli.py channel [--channel @handle]            # channel info
python cli.py videos [--channel UC...] [-n 10]       # recent uploads
python cli.py video VIDEO_ID [VIDEO_ID ...]          # video details
python cli.py search "query" [--order viewCount] [--after 2025-01-01] [--before 2025-03-31] [--region US]
python cli.py analytics --start 2025-01-01 --end 2025-01-31 [--granularity day]   # OAuth
python cli.py video-analytics VIDEO_ID --days 28 [--section retention]            # OAuth
python cli.py top --metric views --days 30 [-n 10]   # OAuth; metrics: views, watch_time, likes, comments, shares, subscribers, engagement
python cli.py revenue --days 28                      # OAuth, monetized channels
python cli.py insights -b countries -b devices [--video VIDEO_ID] [-n 10]          # OAuth; see --help for all breakdowns
python cli.py search-terms --days 90 [--video VIDEO_ID]                          # OAuth
python cli.py comments [--video VIDEO_ID | --channel @handle] [--search text] [--order relevance (one video only)]   # API key or --with-comments
python cli.py replies THREAD_ID                                                                  # API key or --with-comments
python cli.py report --period last_week [--out report.md] [--webhook URL]   # OAuth; or --start/--end, --json
python cli.py alerts --days 14 [--threshold 2] [--webhook URL]              # OAuth; posts only when something is found
python cli.py export [-d channel_daily -d video_daily ...] --days 28 [--format jsonl] [--out-dir exports]   # OAuth
python cli.py compare mine @OtherChannel @AnotherOne [--recent 20]
python cli.py trending --region CA [--category 26]
python cli.py playlists [--channel @handle]
python cli.py playlist PLAYLIST_ID [--stats]

Output is JSON (report prints Markdown). Errors go to stderr prefixed with a code and exit with status 1.

Exporting data

export writes flat daily datasets, one file each, named <dataset>_<start>_<end>.<csv|jsonl>, ready for a spreadsheet, warehouse or BI tool:

Dataset

Rows

channel_daily

Channel totals per day: views, watch time, subscribers, likes, comments, shares

video_daily

Per video per day, for every upload

traffic_daily

Per day and traffic source

device_daily

Per day and device type

content_type_daily

Per day, Shorts vs long-form

subscribed_daily

Per day, subscribers vs not

videos

Every upload with its current views, likes and comments (a snapshot)

Run it daily for the last few days and upsert on day (+ the breakdown column): recent days keep changing until analytics settles.

Bulk reports (YouTube Reporting API)

For long history, or data the Analytics API doesn't offer (such as thumbnail impressions and click-through rate, in channel_reach_basic_a1), schedule a Reporting API job. Google then writes one CSV per day and keeps each for 60 days. Enable YouTube Reporting API in the Cloud project first.

python cli.py reporting types                                # what's available
python cli.py reporting create-job channel_reach_basic_a1    # once per type; first reports in ~48h
python cli.py reporting jobs
python cli.py reporting download JOB_ID --latest 7           # -> exports/reporting/<job>_<day>.csv

Creating a job is the only call in this project that changes anything: it schedules report generation for the channel and never touches videos or the channel itself. It is CLI-only, not an MCP tool.

Scheduled reports

report and alerts read the webhook from YOUTUBE_REPORT_WEBHOOK in .env (any Slack-compatible incoming webhook), so a cron job is enough. For example, a report every Monday at 9:00 and alerts every morning:

0 9 * * 1  cd /path/to/youtube-mcp-server && .venv/bin/python cli.py report --period last_week
30 8 * * *  cd /path/to/youtube-mcp-server && .venv/bin/python cli.py alerts --days 3

These need a working OAuth login. Publish the consent screen (setup step 3), or the login expires every 7 days and the jobs fail with AUTH_ERROR.

MCP server

Tools

Tool

Needs

Description

auth_status

Which credentials are available and which tools work

get_channel_info

Channel name, description, subscriber/video/view counts

list_channel_videos

A channel's uploads with basic stats (paginated)

get_video_details

Full details for one or more video IDs

search_videos

Keyword search with date, order, region and channel filters

list_playlists

A channel's playlists

get_playlist_items

Videos in a playlist

compare_channels

Benchmark up to 10 channels: subscribers, median views, engagement rate, upload frequency, share of Shorts

get_trending_videos

YouTube's most-popular chart for a country, optionally one category

get_channel_report

✓

Ready-made report: totals and change vs the previous period, top videos, audience, searches (JSON + Markdown)

detect_anomalies

✓

Days with unusual views (spikes/drops) or subscriber losses

get_channel_analytics

✓

Views, watch time, subscribers gained/lost over a date range

get_video_analytics

✓

Per-video traffic sources, audience retention, demographics

get_top_videos

✓

Top N videos by a metric over a date range

get_revenue

✓

Estimated revenue and CPM (monetized channels only)

get_audience_insights

✓

Countries, cities, devices, playback locations and embedding sites, traffic sources and referring sites, subscribers vs not, Shorts vs long-form, sharing, cards

get_search_terms

✓

The YouTube search terms that led viewers to your videos

list_comments

key*

Public comment threads on a video or a whole channel, with whether the channel replied

get_comment_replies

key*

All replies to one comment thread

✓ = OAuth. key* = YOUTUBE_API_KEY, or an OAuth login made with --with-comments (see Comments).

Every tool returns structured JSON, is annotated read-only, and documents each parameter. Analytics tools accept start_date/end_date (YYYY-MM-DD) or days (default 28). Errors reach the agent with a stable prefix: NO_CREDENTIALS, OAUTH_REQUIRED, AUTH_ERROR, QUOTA_EXCEEDED, NOT_FOUND, INVALID_REQUEST, API_ERROR.

The server never opens a browser. Run python cli.py auth once in a terminal; if you do this while the server is running, it picks up the new token on its next call.

Running it

python -m mcp_server            # from the project root, with the venv active

Adding it to Claude Desktop or Claude Code

{
  "mcpServers": {
    "youtube": {
      "command": "python",
      "args": ["-m", "mcp_server"]
    }
  }
}

That works when python is the venv's interpreter and the package is installed (pip install -e .). Claude Desktop does not inherit your shell's PATH or virtualenv, so in practice use absolute paths:

{
  "mcpServers": {
    "youtube": {
      "command": "/absolute/path/to/youtube-mcp-server/.venv/bin/python",
      "args": ["-m", "mcp_server"]
    }
  }
}
  • Claude Desktop: edit claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/, Windows: %APPDATA%\Claude\), then restart the app.

  • Claude Code:

    claude mcp add youtube -- /absolute/path/to/youtube-mcp-server/.venv/bin/python -m mcp_server

Library usage

from youtube import YouTubeClient, get_channel_info, get_top_videos, search_videos, YouTubeError

client = YouTubeClient()  # resolves credentials lazily; may run the OAuth flow if needed

print(get_channel_info(client, "@SomeHandle"))
print(search_videos(client, "python tutorial", order="viewCount", published_after="2025-01-01"))

try:
    print(get_top_videos(client, "2025-01-01", "2025-01-31", metric="watch_time", limit=5))
except YouTubeError as exc:
    print(exc.code, exc)

Or get a raw googleapiclient service with the best available credentials:

from youtube import get_youtube_service, get_analytics_service

yt = get_youtube_service()

Quota

The YouTube Data API has a daily quota (10,000 units by default, reset at midnight Pacific). Most reads cost 1 unit; search costs 100. list_channel_videos reads the channel's uploads playlist rather than searching, so it's cheap. Quota and rate-limit errors are reported as QUOTA_EXCEEDED with guidance rather than a stack trace.

Development

pytest          # offline; never reads your real .env or tokens

Project layout

youtube/
  auth.py        credential discovery, OAuth flow, get_youtube_service()
  client.py      YouTubeClient: lazy services, error translation, token reload
  errors.py      typed exceptions + Google API error mapping
  operations.py  registry of operations and their OAuth requirement
  channels.py    channel info, channel videos
  videos.py      video details, bulk stats, search
  playlists.py   playlists, playlist items
  comments.py    comment threads, replies
  benchmark.py   channel comparison, trending chart
  reports.py     period reports, Markdown rendering, anomaly alerts, webhook
  export.py      daily datasets as CSV / JSON Lines
  reporting.py   YouTube Reporting API: report types, jobs, CSV downloads
  analytics.py   channel/video analytics, top videos, revenue
  insights.py    audience breakdowns, search terms
mcp_server/
  server.py      MCP tools
cli.py           click CLI
tests/           offline pytest suite

License

MIT

Available Tools

19 tools
auth_statusShow which credentials are availableA
Read-onlyIdempotent

Which credentials are available (API key, OAuth token, both, or neither) and which tools work with them.

Includes next steps for enabling anything unsupported. Never opens a browser.

Inputs: no named parameters. Returns: object

compare_channelsCompare channelsA
Read-onlyIdempotent

Benchmark channels side by side: subscribers, total views, and over their recent uploads the median views, engagement rate, upload frequency, share of Shorts and top video.

Public data; about 3 quota units per channel. Good for competitor tracking.

Inputs: channels (required), recent_videos. Returns: object

detect_anomaliesDetect unusual days (OAuth)A
Read-onlyIdempotent

Find recent days with unusual views (spikes and drops against the median of the days before) and days that lost subscribers.

Data ends ~2 days ago because analytics lag. Requires OAuth.

Inputs: days, threshold, baseline_days. Returns: object

get_audience_insightsGet audience insights (OAuth)A
Read-onlyIdempotent

Who watches and how: countries, cities, devices, playback locations (incl. embeds on websites), traffic sources, subscribers vs not, Shorts vs long-form, sharing, cards.

Each breakdown lists rows sorted by views with their share of the total. Requires OAuth.

Inputs: days, limit, end_date, video_id, +2 more. Returns: object

get_channel_analyticsGet channel analytics (OAuth)A
Read-onlyIdempotent

Views, watch time (estimatedMinutesWatched), average view duration, subscribers gained/lost, likes, comments and shares for your channel.

Requires OAuth; returns an OAUTH_REQUIRED error with setup steps otherwise.

Inputs: days, end_date, start_date, granularity. Returns: object

get_channel_infoGet channel overviewC
Read-onlyIdempotent

Channel name, description, subscriber count, video count, total views, and uploads playlist ID.

Inputs: channel. Returns: object

get_channel_reportBuild a channel report (OAuth)A
Read-onlyIdempotent

A ready-made performance report: totals and % change vs the previous period, net subscribers, top videos, audience highlights and top YouTube searches.

Includes the same report rendered as Markdown under markdown, ready to share. Requires OAuth.

Inputs: top_n, period, end_date, start_date. Returns: object

get_comment_repliesGet replies to a commentA
Read-onlyIdempotent

All replies to one comment thread, for threads with more replies than list_comments includes.

Inputs: comment_id (required), page_token, max_results. Returns: object

get_playlist_itemsList videos in a playlistB
Read-onlyIdempotent

Videos in a playlist, in playlist order, plus the playlist's own details on the first page. Paginated.

Inputs: playlist_id (required), page_token, max_results, include_stats. Returns: object

get_revenueGet revenue (OAuth, monetized channels)A
Read-onlyIdempotent

Estimated revenue, ad revenue, gross revenue and CPM for your channel.

Returns available=false with the reason if the channel is not monetized or the token lacks the monetary scope. Requires OAuth.

Inputs: days, currency, end_date, start_date, +1 more. Returns: object

get_search_termsGet YouTube search terms (OAuth)A
Read-onlyIdempotent

The YouTube search terms viewers typed before watching your videos, with views and watch time per term.

Useful for titles, descriptions and tags. Requires OAuth.

Inputs: days, limit, end_date, video_id, +1 more. Returns: object

get_top_videosGet top-performing videos (OAuth)A
Read-onlyIdempotent

Your channel's top N videos by a metric over a date range, with titles and key metrics.

Requires OAuth; returns an OAUTH_REQUIRED error with setup steps otherwise.

Inputs: days, limit, metric, end_date, +1 more. Returns: object

get_video_analyticsGet per-video analytics (OAuth)A
Read-onlyIdempotent

Analytics for one video: summary metrics, traffic sources, audience retention curve, and viewer demographics.

Requires OAuth; returns an OAUTH_REQUIRED error with setup steps otherwise.

Inputs: video_id (required), days, end_date, sections, +1 more. Returns: object

get_video_detailsGet video detailsA
Read-onlyIdempotent

Full details for one or more videos: title, description, views, likes, comment count, duration, publish date, tags, thumbnails.

IDs that are deleted, private, or wrong are listed under not_found.

Inputs: video_ids (required). Returns: object

list_channel_videosList a channel's videosB
Read-onlyIdempotent

A channel's uploaded videos, newest first, with basic stats. Paginated via next_page_token.

Inputs: channel, page_token, max_results, include_stats. Returns: object

list_commentsList commentsA
Read-onlyIdempotent

Public comment threads on a video or on all of a channel's videos: text, author, likes, date, reply count, first replies.

owner_replied tells whether the channel answered in the included replies, which helps find unanswered questions. Paginated via next_page_token; 1 quota unit per page. Held-for-review comments are not visible.

Inputs: order, search, channel, video_id, +2 more. Returns: object

list_playlistsList a channel's playlistsB
Read-onlyIdempotent

A channel's playlists with title, description and item count. Paginated via next_page_token.

Inputs: channel, page_token, max_results. Returns: object

search_videosSearch YouTube videosA
Read-onlyIdempotent

Keyword search over public videos with date, order, region and channel filters. Costs ~100 quota units per call.

Inputs: query (required), order, channel_id, page_token, +4 more. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 19 tools

    Disambiguation4/5

    Most tools target a clear resource+action pair (public metadata retrieval vs. OAuth analytics vs. comments vs. playlists). The main soft spot is that get_channel_report bundles totals, top videos, audience highlights and search terms, which overlaps with get_channel_analytics, get_top_videos, get_audience_insights and get_search_terms, so an agent may hesitate between the bundle and the individual breakdowns. Descriptions do explicitly clarify the distinction, so confusion is limited rather than systemic.

    Naming Consistency4/5

    Strong, predictable verb_noun pattern throughout: get_/list_/search_/compare_/detect_ plus a domain noun (get_video_details, list_channel_videos, get_audience_insights). The only deviation is auth_status, which is a bare noun rather than a verb phrase—minor and still readable.

    Tool Count4/5

    19 tools is slightly above the ideal band but each maps to a recognizable YouTube resource or report type, and the public-data vs. OAuth split is coherent. The composite get_channel_report is the one arguably redundant entry given the granular tools it overlaps with, which keeps this from a 5.

    Completeness4/5

    Read and analytics coverage is genuinely thorough: channel/video metadata, playlists, comments and replies, trending, search, revenue, audience, search terms, anomalies and a shareable report. The gaps are on the write side—no uploading or updating videos, no posting comments/replies, no playlist creation—and no captions/transcript access, so the surface is read-only but that limitation is not stated up front.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      Enables AI assistants to access YouTube organic analytics, including channel stats, video performance, watch time, and audience engagement, via the YouTube Data API v3 and Analytics API v2.
      6
      32 npm
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI assistants to search videos, retrieve transcripts and metadata, analyze channels, and access trending and engagement analytics for YouTube content.
      18 npm
      -