YouTube MCP Server
Posts channel reports and alert digests to a Slack-compatible webhook, so scheduled reports and threshold-based alerts (e.g. unusual drops in views over the last 14 days) can be pushed into a Slack channel.
Provides read-only access to the YouTube Data API v3 and YouTube Analytics API v2: channel details, recent uploads and video details, search (including date and region filters), playlists, trending videos, comments and replies, plus OAuth-only analytics such as daily channel metrics, per-video retention, top videos by metric (views, watch time, likes, comments, shares, subscribers, engagement), revenue, audience breakdowns (countries, devices), search terms, and daily dataset exports for BI tools.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@YouTube MCP Server get my channel's analytics for the last 30 days"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 toolscli.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 |
| Used as-is | Everything |
2 |
| Refreshed automatically and saved | Everything |
3 |
| OAuth browser flow runs, token saved to | Everything |
4 |
| 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:
Create a project, or select an existing one.
APIs & Services → Library: enable YouTube Data API v3 and YouTube Analytics API (and YouTube Reporting API if you want bulk reports).
3. Configure the OAuth consent screen
Go to Google Auth Platform (older consoles: APIs & Services → OAuth consent screen).
Branding: set an app name and support email.
Audience → User type: choose External. If it shows Internal, click Make external.
Audience → Test users: add the Google account you will sign in with.
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
Google Auth Platform → Clients → Create client (or APIs & Services → Credentials → Create credentials → OAuth client ID).
Application type: Desktop app.
Download the JSON and save it as
client_secret.jsonin 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_KEYSign in with the Google account that owns or manages the channel.
If Google says "Google hasn't verified this app", click Advanced → Go to (app name).
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.
Accept the read-only permissions.
The command prints the connected channel. Confirm it is the right one, then run:
python cli.py auth-statusThe 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).
APIs & Services → Credentials → Create credentials → API key.
Edit API key → API restrictions → Restrict key → tick only YouTube Data API v3 → Save.
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 |
| 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. |
| 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 |
"Google hasn't verified this app" | Normal. Click Advanced → Go to (app name). |
"could not be refreshed" | The login expired or was revoked. Run |
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 | The OAuth token stays strictly read-only. Held-for-review comments are not visible. |
OAuth with comments | Delete | 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 |
| API key for public read-only calls |
| Default channel (ID or |
| Path to the OAuth client JSON (default |
| Where to store the OAuth token (default |
| Slack-compatible webhook for |
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 totals per day: views, watch time, subscribers, likes, comments, shares |
| Per video per day, for every upload |
| Per day and traffic source |
| Per day and device type |
| Per day, Shorts vs long-form |
| Per day, subscribers vs not |
| 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>.csvCreating 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 3These 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 |
| Which credentials are available and which tools work | |
| Channel name, description, subscriber/video/view counts | |
| A channel's uploads with basic stats (paginated) | |
| Full details for one or more video IDs | |
| Keyword search with date, order, region and channel filters | |
| A channel's playlists | |
| Videos in a playlist | |
| Benchmark up to 10 channels: subscribers, median views, engagement rate, upload frequency, share of Shorts | |
| YouTube's most-popular chart for a country, optionally one category | |
| ✓ | Ready-made report: totals and change vs the previous period, top videos, audience, searches (JSON + Markdown) |
| ✓ | Days with unusual views (spikes/drops) or subscriber losses |
| ✓ | Views, watch time, subscribers gained/lost over a date range |
| ✓ | Per-video traffic sources, audience retention, demographics |
| ✓ | Top N videos by a metric over a date range |
| ✓ | Estimated revenue and CPM (monetized channels only) |
| ✓ | Countries, cities, devices, playback locations and embedding sites, traffic sources and referring sites, subscribers vs not, Shorts vs long-form, sharing, cards |
| ✓ | The YouTube search terms that led viewers to your videos |
| key* | Public comment threads on a video or a whole channel, with whether the channel replied |
| 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 activeAdding 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 tokensProject 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 suiteLicense
MIT
Available Tools
19 toolsauth_statusShow which credentials are availableARead-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 channelsARead-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)ARead-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)ARead-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)ARead-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 overviewCRead-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)ARead-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 commentARead-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 playlistBRead-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)ARead-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)ARead-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)ARead-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_trending_videosGet trending videosARead-onlyIdempotent
YouTube's most-popular videos in a country right now, optionally in one category, with stats. 1 quota unit.
Inputs: page_token, category_id, max_results, region_code. Returns: object
get_video_analyticsGet per-video analytics (OAuth)ARead-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 detailsARead-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 videosBRead-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 commentsARead-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 playlistsBRead-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 videosARead-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
Scored across 19 tools
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.
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.
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.
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
Related MCP Connectors
Your YouTube channels’ private analytics for AI assistants: revenue, views, retention. Read-only.
YouTube for AI agents: transcripts, comments, video stats, channel monitor, Shorts captions.
YouTube transcripts, search, channels, playlists and bulk transcript jobs for AI agents. 14 tools.
YouTube transcripts, search, channel/playlist listings and upload tracking for AI agents.
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables 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.632 npmMIT
- AlicenseBqualityCmaintenanceProvides comprehensive access to YouTube Data, Analytics, and Reporting APIs, enabling AI assistants to manage videos, analyze performance, handle comments, and extract transcripts.40MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to search videos, retrieve transcripts and metadata, analyze channels, and access trending and engagement analytics for YouTube content.18 npm-
- AlicenseAqualityCmaintenanceEnables AI assistants to retrieve YouTube channel overviews, Studio analytics, video performance, traffic source breakdowns, and comments for sentiment analysis using natural language prompts.82MIT