Skip to main content
Glama
leotruza

YouTube MCP

by leotruza

YouTube MCP — Node.js

English

Overview

This is the maintained Node.js implementation of the standalone YouTube MCP server. The previous Python implementation is preserved in the archive/python branch. It provides structured access to YouTube through Piped without directly interacting with youtube.com, without an official YouTube API key, and without controlling a browser.

AI-generated software disclaimer

This project was fully created with the assistance of artificial intelligence (AI), including its source code, documentation, configuration, and project structure. It has been reviewed and tested to the extent described in this repository, but users should independently review the code and verify that it meets their security, reliability, and legal requirements.

Architecture and features

The server dynamically downloads TeamPiped's official public-instance list, parses and deduplicates API URLs, health-checks each listed API instance, prefers healthy CDN instances with low latency and few failures, and automatically fails over when a backend fails. It keeps state and caches in memory. Playback URLs use the official https://piped.video frontend and a correctly encoded instance parameter.

The project uses the official @modelcontextprotocol/sdk JavaScript SDK. Browser automation is outside the MCP boundary: there are no Playwright, Selenium, CDP, browser profiles, or browser-launching dependencies.

Requirements and installation

Node.js 20 or newer is recommended:

npm install

Running and configuration

Run the default local stdio server:

npm start

Environment variables:

Variable

Default

YOUTUBE_MCP_HOST

127.0.0.1

YOUTUBE_MCP_PORT

8083

YOUTUBE_MCP_TRANSPORT

stdio

YOUTUBE_MCP_INSTANCE_LIST_URL

TeamPiped official raw Markdown URL

YOUTUBE_MCP_INVIDIOUS_INSTANCES

Official public Invidious list; comma-separated overrides

YOUTUBE_MCP_INSTANCE_REFRESH_MINUTES

30

YOUTUBE_MCP_HEALTH_CHECK_MINUTES

5

YOUTUBE_MCP_TIMEOUT_SECONDS

30

For Streamable HTTP, use YOUTUBE_MCP_TRANSPORT=streamable-http; the MCP endpoint is /mcp. The default configuration intentionally binds locally.

Invidious fallback is enabled by default using the five HTTPS clearnet instances currently listed in the official Invidious instance documentation: inv.nadeko.net, invidious.nerdvpn.de, yt.chocolatemoo53.com, invidious.tiekoetter.com, and invidious.f5.si. Set YOUTUBE_MCP_INVIDIOUS_INSTANCES to one or more comma-separated Invidious base URLs to override the list, or set it to an empty string to disable the fallback. Piped remains the primary backend; Invidious is tried only when Piped has no usable instance. Invidious public instances are independent services and may have different availability or privacy policies.

MCP tools

  • youtube_search(query, filter, limit) searches through Piped and returns concise result metadata.

  • youtube_video(video_id) retrieves metadata and normalized video/audio streams from /streams/{video_id}.

  • youtube_play(video_id, autoplay, listen, quality, sponsorblock) returns a browser-ready URL and never launches a browser.

Errors are returned as structured MCP error content with error and retryable fields. Temporary backend failures are retryable; unavailable videos are non-retryable when the backend returns HTTP 404.

Development and testing

npm test
npm run check

The tests use mocked HTTP responses and cover TeamPiped parsing, deduplication, invalid entries, health checks, CDN-aware selection, failover, search/video/stream normalization, URL encoding, and configuration. Before production use, perform a live integration check in an environment with outbound HTTPS. Public Piped instances can become unavailable or rate-limit requests.

Security and scope

No credentials, cookies, tokens, arbitrary shell execution, filesystem tools, or YouTube account access are included. The application only needs outbound HTTPS to the TeamPiped list, public Piped APIs, and the Piped frontend. This project is licensed under the GNU General Public License version 3.0. See LICENSE.


Related MCP server: YouTube MCP Server

Português (Brasil)

Visão geral

Esta é a implementação mantida em Node.js do servidor MCP independente para YouTube. A implementação anterior em Python está preservada na branch archive/python. Ela oferece acesso estruturado ao YouTube por meio do Piped sem interagir diretamente com youtube.com, sem chave oficial da API do YouTube e sem controlar um navegador.

Aviso sobre software gerado por IA

Este projeto foi criado integralmente com o auxílio de inteligência artificial (IA), incluindo o código-fonte, a documentação, as configurações e a estrutura do projeto. O projeto foi revisado e testado conforme descrito neste repositório, mas os usuários devem analisar o código por conta própria e verificar se ele atende aos seus requisitos de segurança, confiabilidade e aspectos legais.

Arquitetura e recursos

O servidor baixa dinamicamente a lista oficial de instâncias públicas do TeamPiped, analisa e remove URLs duplicadas, verifica a saúde, prefere instâncias CDN saudáveis com baixa latência e poucas falhas e executa failover automático quando um backend falha. O estado e os caches ficam em memória. Os links de reprodução usam o frontend https://piped.video e um parâmetro instance corretamente codificado.

O projeto usa o SDK oficial @modelcontextprotocol/sdk para JavaScript. A automação de navegador fica fora do limite do MCP: não há Playwright, Selenium, CDP, perfis de navegador ou dependências para iniciar navegadores.

Requisitos e instalação

Recomenda-se Node.js 20 ou mais recente:

npm install

Execução e configuração

Execute o servidor local stdio padrão:

npm start

As variáveis de ambiente são equivalentes às listadas na seção em inglês: host 127.0.0.1, porta 8083, transporte stdio, lista oficial do TeamPiped, fallback Invidious habilitado por padrão, atualização da lista em 30 minutos, verificação de saúde em 5 minutos e timeout de 30 segundos. O link de reprodução usa o frontend oficial https://piped.video, com a API selecionada no parâmetro instance. Para Streamable HTTP, use YOUTUBE_MCP_TRANSPORT=streamable-http; o endpoint MCP é /mcp.

A compatibilidade com Invidious é habilitada por padrão usando as cinco instâncias HTTPS clearnet listadas atualmente na documentação oficial de instâncias do Invidious: inv.nadeko.net, invidious.nerdvpn.de, yt.chocolatemoo53.com, invidious.tiekoetter.com e invidious.f5.si. Defina YOUTUBE_MCP_INVIDIOUS_INSTANCES com uma ou mais URLs base separadas por vírgula para substituí-las, ou use uma string vazia para desabilitar o fallback. O Piped continua sendo o backend principal; o Invidious só é usado quando nenhuma instância Piped está disponível.

Ferramentas MCP

  • youtube_search(query, filter, limit) pesquisa por meio do Piped e retorna metadados concisos.

  • youtube_video(video_id) retorna metadados e streams de vídeo/áudio normalizados usando /streams/{video_id}.

  • youtube_play(video_id, autoplay, listen, quality, sponsorblock) retorna um link pronto para o navegador e nunca abre um navegador.

Erros são retornados como conteúdo MCP estruturado com os campos error e retryable. Falhas temporárias do backend permitem nova tentativa; vídeos indisponíveis são não recuperáveis quando o backend retorna HTTP 404.

Desenvolvimento e testes

Use npm test e npm run check. Os testes usam respostas HTTP simuladas e cobrem análise TeamPiped, duplicatas, entradas inválidas, saúde, seleção CDN, failover, normalização de busca/vídeo/streams, codificação de URLs e configuração. Antes de usar em produção, faça um teste de integração ao vivo em um ambiente com HTTPS de saída. Instâncias públicas do Piped podem ficar indisponíveis ou limitar requisições.

Segurança e escopo

Não há credenciais, cookies, tokens, execução arbitrária de shell, ferramentas de arquivos ou acesso a contas do YouTube. O aplicativo precisa somente de HTTPS de saída para a lista TeamPiped, APIs públicas do Piped e frontend do Piped. Este projeto está licenciado sob a GNU General Public License versão 3.0. Consulte LICENSE.

Available Tools

3 tools
youtube_playC

Generate a browser-ready Piped or Invidious URL without launching a browser.

ParametersJSON Schema
NameRequiredDescriptionDefault
listenNo
qualityNo
autoplayNo
video_idYes
sponsorblockNo

TDQS

C2.7/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It discloses one key behavior — that no browser is launched — and implies the output is a URL, but it does not state whether the tool makes network calls, how instances are chosen, whether the video_id is validated, failure behavior, or the return format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single efficient sentence with no wasted words, and it front-loads the core purpose and key behavioral caveat. It is appropriately sized for a simple tool, though it sacrifices informative content for brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 5 parameters, no output schema, and no annotations, this description is incomplete. An agent still lacks definitions for parameters like listen and sponsorblock, does not know what structure the returned URL takes, and cannot predict side effects — all of which the description should supply given the absence of structured context.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate for the 5 parameters, but it adds nothing about listen, quality, autoplay, sponsorblock, or video_id beyond what the bare names suggest. The output framing ('browser-ready URL') weakly implies the parameters configure the generated URL, which is some value, but well short of adequate compensation.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a specific verb ('Generate') and resource ('Piped or Invidious URL'), making the tool's output clear. It implicitly differentiates from siblings by describing a URL-generation function rather than search or metadata retrieval, though it never names the siblings explicitly.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is given on when to choose this tool over youtube_search or youtube_video, and no alternatives or exclusions are mentioned. The phrase 'without launching a browser' hints at a programmatic use case, but the conditions that would select this tool are left entirely to inference.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

youtube_videoB

Retrieve video metadata and streams through Piped, with optional Invidious fallback.

ParametersJSON Schema
NameRequiredDescriptionDefault
video_idYes

TDQS

B3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries full disclosure responsibility. It does reveal that the tool uses Piped and may fall back to Invidious, which is useful, but it does not mention failure behavior, external network effects, or the shape of the returned data. 'Retrieve' implies read-only, yet that safety trait is not explicitly confirmed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, tightly written sentence that front-loads the action and adds a meaningful fallback detail. There is no redundancy or filler, making it appropriately concise for a one-parameter tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

The tool has no annotations and no output schema, so the description needs to explain more: what metadata fields are returned, what stream variants are provided, and what happens if Piped or Invidious fails. Without this, an agent can invoke it but cannot predict the response or handle common failures.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema contains only video_id with a type and pattern, and the description adds no parameter-level explanation. With 0% schema description coverage, the description should have clarified that video_id is a YouTube video ID rather than a URL and explained any format expectations beyond the regex.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description uses a clear retrieval verb and identifies the resource as 'video metadata and streams,' which separates it from youtube_search and youtube_play. It does not explicitly mention that the target is identified by video_id, and 'streams' could be more specific, but the core purpose is understandable.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage context is implied by the verb and resource: use this when you need metadata or streams for a specific video. However, there is no explicit guidance about when not to use it or how it relates to youtube_search and youtube_play, so the agent must infer the distinction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

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

  1. 3 tool updatesv1.2.0
    • First observedyoutube_play
    • First observedyoutube_search
    • First observedyoutube_video

TDQS

B3.2/5.0

Scored across 3 tools

Disambiguation5/5

Each tool serves a distinct purpose: youtube_search for searching, youtube_video for retrieving metadata, and youtube_play for generating playback URLs. No overlap or confusion exists between them.

Naming Consistency4/5

All tools share a consistent 'youtube_' prefix, but the suffixes mix verbs (search, play) and a noun (video), which is a minor deviation from a strict verb_noun pattern. Still predictable and readable.

Tool Count4/5

Three tools is lean but appropriate for a focused YouTube client covering search, metadata, and playback URL generation. It feels slightly thin but not underdeveloped for its stated scope.

Completeness3/5

The tool surface covers core operations (search, retrieve metadata, generate playable URL) but lacks common YouTube features like channel or playlist access, comments, or uploads. Some notable gaps exist for broader use cases.

Maintenance

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Enables YouTube content browsing, video searching, and metadata retrieval via the YouTube Data API v3. It also facilitates fetching video transcripts for summarization and analysis within MCP-compatible AI clients.
    7
    19 npm
    1
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI assistants to search videos, read channels, browse playlists, fetch comments, and get transcripts from YouTube using the YouTube Data API v3 and InnerTube API for captions.
    2
    GPL 3.0