YouTube MCP

YouTube MCP

Enables searching for songs on YouTube and automatically playing them in a web browser using the official YouTube Data API v3. It supports cross-platform execution on Windows, macOS, and Linux with built-in input validation.

Category
Visit Server

README

YouTube MCP

Una implementación de Model Context Protocol (MCP) para buscar y reproducir canciones en YouTube directamente desde tu navegador.

Tabla de Contenidos

Características

  • 🔍 Buscar canciones en YouTube usando la API oficial
  • 🎵 Reproducir canciones en el navegador automáticamente
  • 🖥️ Soporte multi-plataforma (Windows, macOS, Linux)
  • 📦 Fácil integración con herramientas que soporten MCP
  • ✅ Validación completa de inputs (API Keys, URLs, búsquedas)
  • 📝 Type hints modernos (Python 3.9+)
  • 🧪 Cobertura de tests completa (59 tests, 100% passing)
  • 📊 Logging estructurado y centralización de configuración

Instalación

1. Clonar/Crear el proyecto

cd youtube_mcp
# O: git clone https://github.com/roquevaamonde/youtube-mcp.git youtube_mcp

2. Crear el virtual environment

python -m venv venv
source venv/bin/activate  # En Windows: venv\Scripts\activate

3. Instalar dependencias

pip install -r requirements.txt

4. Configurar API Key

Sigue estos pasos para obtener tu API Key de YouTube:

  1. Acceder a Google Cloud Console: Dirígete a Google Cloud Console
  2. Crear un nuevo proyecto:
    • Haz clic en el selector de proyecto en la parte superior
    • Selecciona "Nuevo Proyecto"
    • Asigna un nombre (ej: "YouTube MCP")
    • Clic en "Crear"
  3. Habilitar YouTube Data API v3:
  4. Crear una API Key:
  5. Configurar en tu proyecto:
cp .env.example .env
# Edita .env y añade tu YOUTUBE_API_KEY
# YOUTUBE_API_KEY=tu_clave_aqui

5. Configurar en VS Code

  1. Abre las configuraciones de VS Code (Cmd+Shift+P → "Preferences: Open User Settings (JSON)")
  2. Localiza o crea la sección "modelContextProtocol"
  3. Agrega la configuración del servidor YouTube:
{
  "modelContextProtocol": {
    "servers": {
      "youtube": {
        "type": "stdio",
        "command": "{python-path}",
        "args": ["{project-path}/youtube_mcp_server.py"],
        "disabled": false,
        "autoApprove": [],
        "env": {
          "YOUTUBE_API_KEY": "your_api_key_here"
        }
      }
    }
  }
}

Reemplaza:

  • {python-path}: Ruta completa a tu Python (ej: /usr/bin/python3 o C:\Python\python.exe)
  • {project-path}: Ruta del proyecto (ej: /home/user/projects/youtube_mcp)
  • your_api_key_here: Tu API Key de YouTube

Uso

from youtube_mcp.server import YouTubeMCPServer

server = YouTubeMCPServer(api_key="your_api_key")

# Ejemplo 1: Reproducir el primer resultado (tema suelto)
results = server.handle_search_youtube(query="Bohemian Rhapsody Queen", max_results=5)
if results.get("success") and results.get("results"):
    first_url = results["results"][0]["url"]
    server.handle_play_youtube(first_url)

Snippets MCP (JSON) para el mismo flujo:

{
  "tool": "search_youtube",
  "params": {
    "query": "Bohemian Rhapsody Queen",
    "max_results": 5
  }
}

Con el url del primer resultado devuelto, reproducir:

{
  "tool": "play_youtube",
  "params": {
    "url": "https://www.youtube.com/watch?v=<VIDEO_ID>"
  }
}

Ejemplos avanzados

  • Playlist con orden explícito (por IDs conocidos):

    Python:

    video_ids = ["VIDEO1", "VIDEO2", "VIDEO3", "VIDEO4"]
    # Método recomendado (determinista): watch_videos con video_ids
    playlist_url = f"https://www.youtube.com/watch_videos?video_ids={','.join(video_ids)}"
    server.handle_play_youtube(playlist_url)
    

    JSON MCP:

    {
      "tool": "play_youtube",
      "params": {
        "url": "https://www.youtube.com/watch_videos?video_ids=VIDEO1,VIDEO2,VIDEO3,VIDEO4"
      }
    }
    

    Alternativa (menos determinista en algunos navegadores):

    {
      "tool": "play_youtube",
      "params": {
        "url": "https://www.youtube.com/watch?v=VIDEO1&playlist=VIDEO2,VIDEO3,VIDEO4&autoplay=1"
      }
    }
    
  • Reproducción continua (Mix de YouTube) para un tema:

    Python:

    video_id = "VIDEO_ID"
    mix_url = f"https://www.youtube.com/watch?v={video_id}&list=RD{video_id}&autoplay=1"
    server.handle_play_youtube(mix_url)
    

    JSON MCP:

    {
      "tool": "play_youtube",
      "params": {
        "url": "https://www.youtube.com/watch?v=VIDEO_ID&list=RDVIDEO_ID&autoplay=1"
      }
    }
    

Tests

pytest tests/

Cobertura de Tests: 59 tests que cubren:

  • ✅ Búsqueda de canciones en YouTube (YouTubeClient)
  • ✅ Reproducción de videos en navegador (BrowserController)
  • ✅ Detección de Sistema Operativo (Windows, macOS, Linux, WSL)
  • ✅ Gestión de procesos de navegador
  • ✅ Validadores de URL, API Keys, búsquedas y max_results
  • ✅ Servidor MCP y orquestación de herramientas
  • ✅ Manejo de errores y casos edge

Para ver la cobertura de código:

pytest tests/ --cov=youtube_mcp --cov-report=term-missing

Calidad de Código

Este proyecto incluye:

  • Validación de inputs: Módulo validators.py con validación completa para:

    • API Keys (longitud mínima 20 caracteres)
    • URLs de YouTube (validación con regex)
    • Queries de búsqueda (1-300 caracteres)
    • Max results (1-50)
  • Type hints modernos: Uso de dict, list, tuple en lugar de typing (Python 3.9+)

  • Logging estructurado: Setup centralizado con logger.py

  • Constantes: Configuración centralizada en constants.py para:

    • Mensajes de error y éxito
    • Detectores de SO (Windows, macOS, Linux, WSL)
    • Configuración por defecto (región, max_results)
    • Formato de logging

Estructura del proyecto

youtube_mcp/
├── youtube_mcp/
│   ├── __init__.py
│   ├── youtube_client.py      # Cliente de YouTube API
│   ├── browser_controller.py   # Controlador de navegador multi-plataforma
│   ├── server.py              # Servidor MCP con herramientas
│   ├── validators.py          # Validación de inputs
│   ├── constants.py           # Constantes y configuración centralizada
│   └── logger.py              # Setup de logging
├── tests/                      # Tests con pytest (59 tests, 100% passing)
├── config/                     # Archivos de configuración
├── docs/                       # Documentación
├── requirements.txt
├── .env.example
└── README.md

Herramientas disponibles

search_youtube

Busca una canción en YouTube.

Parámetros:

  • query (string, requerido): Nombre de la canción o artista
  • max_results (integer, opcional): Número máximo de resultados (default: 5)
  • play (boolean, opcional): Si es true, abre el primer resultado en el navegador

Ejemplo:

{
  "query": "Bohemian Rhapsody Queen",
  "max_results": 5,
  "play": false
}

play_youtube

Reproduce una canción en YouTube abriendo el enlace del video en el navegador.

Parámetros:

  • url (string, requerido): Enlace de YouTube del video a reproducir

Ejemplo:

{
  "url": "https://www.youtube.com/watch?v=<VIDEO_ID>"
}

También puedes pasar URLs de playlist o Mix:

{
  "url": "https://www.youtube.com/watch?v=VIDEO1&playlist=VIDEO2,VIDEO3,VIDEO4&autoplay=1"
}
{
  "url": "https://www.youtube.com/watch?v=VIDEO_ID&list=RDVIDEO_ID&autoplay=1"
}

Ejemplos de Prompts

A continuación tienes ejemplos prácticos para pedir búsquedas, listas/colas y reproducción en bucle o continua. Puedes combinarlos y ser específico con el orden, el artista y la cantidad.

  • Reproducción directa (tema suelto):

    • "Pon King Kong de Midas Alonso"
    • "Reproduce Bohemian Rhapsody de Queen y súbelo a 1080p si hay opción"
  • Reproducción en bucle o continua:

    • "Déjalo en bucle" (el agente puede activar el modo loop del reproductor o usar el Mix de YouTube cuando corresponda)
    • "Activa el Mix de YouTube de esta canción para que siga solo"
    • "Ponlo en repetición por 30 minutos"
  • Listas/colas personalizadas (orden explícito):

    • "Prepárame una cola con BRIXTON, GRAND PRIX, CLUEDO y TYRION de Midas Alonso en ese orden y reprodúcela"
    • "Crea una playlist de 8 temas de Yung Beef empezando por Me Perdí en Madrid y mezclando con artistas similares"
  • Búsquedas versátiles y por criterios:

    • "Busca 5 temas de PXXR GVNG y pon el mejor resultado oficial"
    • "Haz una playlist de 10 temas de rap español 2015–2018 y reprodúcela"
    • "Mezcla clásicos de Yung Beef con temas nuevos y activa autoplay"

Notas:

  • Para reproducción en bucle exacta de un único tema, el agente puede usar el modo loop del reproductor en tu navegador. Si no está disponible, intentará alternativas como el Mix o repetir la pista al finalizar.
  • Para colas dinámicas, el agente puede crear una playlist temporal en YouTube y abrirla con autoplay.

Requisitos de API Key

La API Key necesita las siguientes APIs habilitadas:

  • YouTube Data API v3

Soporte de sistemas operativos

  • ✅ Windows
  • ✅ macOS
  • ✅ Linux

Licencia

Ver archivo LICENSE

Contribuciones

Ver archivo CONTRIBUTING.md

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
E2B

E2B

Using MCP to run code via e2b.

Official
Featured