사전 지식
이 글에서는 YouTube API와 MCP 서버를 활용한 AI 비서 도구를 만들어봅니다. 본격적인 실습에 앞서 아래 사전 지식이 있으면 학습이 훨씬 수월합니다.
- Python 프로그래밍: 함수 정의, 모듈 불러오기 등 기본적인 문법
- REST API 사용 경험: API 키 인증, GET/POST 요청 구조 이해
- Claude나 Cursor IDE 사용자: MCP를 기반으로 작동하는 LLM 기반 도구를 사용해 본 경험이 있다면 실습이 더욱 직관적입니다.
물론, 이 중 일부만 알고 있어도 실습을 따라 하는 데에는 문제가 없도록 설명을 단계별로 구성하였습니다.
유튜브는 이제 단순한 동영상 플랫폼을 넘어 지식, 뉴스, 엔터테인먼트, 마케팅의 거대한 집합소가 되었습니다. 하지만 이 방대한 콘텐츠 속에서 원하는 정보를 빠르고 효율적으로 추출해 내는 일은 여전히 쉽지 않습니다.
이 글에서는 이러한 문제를 해결할 수 있는 방법을 배웁니다. 특히 Claude Desktop과 Cursor IDE 같은 MCP를 지원하는 환경에서 직접 활용 가능한 형태로 YouTube 도구를 구현해 볼 것입니다. MCP (Model Context Protocol)를 기반으로 동작하는 AI 도구를 직접 구현하며, YouTube API와의 연동을 통해 영상 검색, 메타 정보 추출, 자막 요약 등 다양한 기능을 AI 비서에게 부여하는 방법을 알아볼 것입니다.
github: https://github.com/jikime/py-mcp-youtube-toolbox
GitHub - jikime/py-mcp-youtube-toolbox
Contribute to jikime/py-mcp-youtube-toolbox development by creating an account on GitHub.
github.com
smithery: https://smithery.ai/server/@jikime/py-mcp-youtube-toolbox
YouTube MCP 서버의 구성
YouTube MCP 서버는 AI 비서가 YouTube 콘텐츠와 상호작용할 수 있도록 도와주는 백엔드 도구입니다. 이 서버는 다음과 같은 핵심 기능을 제공합니다.
구성 요소
- server.py: MCP 서버의 핵심 로직이 구현된 파일입니다.
- client.py: MCP 클라이언트를 이용하여 서버와 통신하고 테스트할 수 있는 터미널 기반 인터페이스입니다.
- .env: API 키와 같은 환경 설정을 저장하는 파일입니다.
- requirements.txt: 필요한 파이썬 패키지를 정의합니다.
지원 기능
- YouTube 영상 검색 (search_videos)
- 영상 상세 정보 조회 (get_video_details)
- 채널 정보 조회 (get_channel_details)
- 댓글 조회 (get_video_comments)
- 영상 자막 추출 (get_video_transcript)
- 고급 자막 처리 (get_video_enhanced_transcript)
- 관련 영상 추천 (get_related_videos)
- 인기 영상 조회 (get_trending_videos)
- 영상 요약 프롬프트 생성 (transcript_summary)
- MCP 리소스 호출 (youtube://video/..., youtube://channel/... 등)
Google Console에서 YouTube API 키 발급받기
YouTube 관련 기능을 사용하려면 Google Cloud에서 발급받은 API 키가 반드시 필요합니다. 아래 단계를 따라 키를 발급받아. env.local 파일에 추가해 주세요.
1단계: Google Cloud 콘솔 접속
- Google Cloud Console에 접속하여 로그인합니다.
- 좌측 상단의 프로젝트 선택 드롭다운에서 [새 프로젝트]를 클릭합니다.
- 적당한 프로젝트 이름을 넣고 [만들기]를 클릭하여 프로젝트 생성을 완료합니다.
2단계: YouTube Data API 활성화
- 생성한 프로젝트로 이동한 뒤, 왼쪽 사이드바에서 [API 및 서비스] > [라이브러리]를 클릭합니다.
- 검색창에 YouTube Data API v3를 입력하고 클릭합니다.
- [사용] 버튼을 눌러 API를 활성화합니다.
3단계: API 키 발급
- 왼쪽 사이드바에서 [API 및 서비스] > [사용자 인증 정보]를 클릭합니다.
- [사용자 인증 정보 만들기] > [API 키]를 클릭합니다.
- 생성된 API 키를 복사하여. env.local 파일에 붙여 넣습니다.
# .env.local 파일 예시
YOUTUBE_API_KEY=your_youtube_api_key
주요 기능 소개
YouTube MCP 서버는 Claude Desktop 또는 MCP CLI에서 직접 실행 가능한 여러 가지 도구(Tool)와 리소스를 제공합니다.
아래 각 툴별로 기능 설명, 실행 명령어와 결과 예시를 함께 확인해 봅시다.
🔍 search_videos
YouTube에서 키워드를 기준으로 관련 영상을 검색할 수 있습니다.
uv run client.py search_videos query="MCP" max_results=3
예시 결과:
{
"items": [
{
"videoId": "BP7zNWtbyO4",
"title": "Warp Is Now The BEST MCP Client in 2025",
"channelId": "UCkVfrGwV-iG9bSsgCbrNPxQ",
"channelTitle": "Better Stack",
"publishedAt": "2025-05-06T18:20:31Z",
"description": "Unlock the power of Warp Terminal with its new MCP support. This guide demonstrates how to add MCP servers to Warp Preview, ...",
...생략...
"url": "https://www.youtube.com/watch?v=BP7zNWtbyO4"
}
],
"totalResults": 1000000,
"nextPageToken": "CAUQAA"
}
ℹ️ get_video_details
특정 YouTube 영상의 메타데이터(제목, 채널명, 조회수, 업로드 날짜, 길이 등)를 조회합니다.
uv run client.py get_video_details video_id=BP7zNWtbyO4
예시 결과:
{
"id": "BP7zNWtbyO4",
"title": "Warp Is Now The BEST MCP Client in 2025",
"description": "Unlock the power of Warp Terminal with its new MCP support. This guide demonstrates how to add MCP servers to Warp Preview, sync configurations to Warp Drive, and build a complete rock-paper-scissors game using Vite, React, TypeScript, Tailwind, and ShadCN UI. Learn how Warp integrates with LLMs and offers powerful tools that make it stand out from other terminals or tools like Cursor AI, Claude Code, Windsurf and VSCode with Copilot.\n\n\n🔗 Relevant Links\nTry Warp - https://app.warp.dev/referral/28VYE6\nMy favourite features - https://www.youtube.com/watch?v=HSgHiRxsFzg\nMCP support doc - https://docs.warp.dev/features/warp-ai/mcp\n\n❤️ More about us\nRadically better observability stack: https://betterstack.com/\nWritten tutorials: https://betterstack.com/community/\nExample projects: https://github.com/BetterStackHQ\n\n📱 Socials\nTwitter: https://twitter.com/betterstackhq\nInstagram: https://www.instagram.com/betterstackhq/\nTikTok: https://www.tiktok.com/@betterstack\nLinkedIn: https://www.linkedin.com/company/betterstack\n\n📌 Chapters:\n00:00 - Introduction to Warp's MCP Support\n00:34 - Configuring MCP Servers\n01:31 - Testing with a React Game Project\n02:23 - Project Result Demo\n02:50 - Improvement Suggestions",
"publishedAt": "2025-05-06T18:20:31Z",
"channelId": "UCkVfrGwV-iG9bSsgCbrNPxQ",
"channelTitle": "Better Stack",
...생략...
}
💬 get_video_comments
영상에 달린 댓글 목록을 가져올 수 있으며, 정렬 조건과 댓글 수를 지정할 수 있습니다. 답글 포함 여부도 설정 가능합니다.
uv run client.py get_video_comments video_id=BP7zNWtbyO4 max_results=10 order=time
예시 결과:
{
"comments": [
{
"id": "Ugzya6yRbgZKG1_uY9J4AaABAg",
"text": "i wish everyone would stop promoting this shitty ass terminal",
"author": "@FroggyTheGamer",
"authorProfileImageUrl": "https://yt3.ggpht.com/j79kLShq6ETLkoPMK8WhPmPTSDBLwuy0lGl1ks2lEa1qkutAsThE2X6ENefWKy6RD7VosRBacA=s48-c-k-c0x00ffffff-no-rj",
"likeCount": 0,
"publishedAt": "2025-05-07T02:10:10Z",
"updatedAt": "2025-05-07T02:10:10Z",
"replyCount": 0
},
...생략...
],
"nextPageToken": null,
"totalResults": 2
}
🧾 get_video_transcript
지원되는 언어로 영상의 자막(트랜스크립트)을 추출합니다. 영상 내용을 요약하거나 검색하는 데 활용할 수 있습니다.
uv run client.py get_video_transcript video_id=BP7zNWtbyO4 language=ko
예시 결과:
{
"metadata": {
"videoId": "BP7zNWtbyO4",
"title": "Warp Is Now The BEST MCP Client in 2025",
"channelTitle": "Better Stack",
"language": "ko",
"segmentCount": 44
},
"transcript": [
{
"text": "Today we're going to talk about Warp's MCP support which in my opinion makes it the best",
"start": 0.0,
"duration": 6.0,
"timestamp": "00:00"
},
{
"text": "MCP client out there. Well, almost. Now if you know nothing about the amazing Warp terminal,",
"start": 6.0,
"duration": 6.479,
"timestamp": "00:06"
},
...생략...
}
📌 get_related_videos
특정 영상과 유사한 주제의 추천 영상을 가져옵니다. 제목 기반 검색을 활용하여 관련 콘텐츠를 탐색합니다.
uv run client.py get_related_videos video_id=BP7zNWtbyO4 max_results=5
예시 결과:
{
"videos": [
{
"videoId": "V9Mpmidh69E",
"title": "Breakthrough: Scientists Make Warp Drive Closer Than You Think!",
"channelTitle": "NASASpaceNews",
"publishedAt": "2024-05-09T08:07:08Z",
"description": "Dive into the latest breakthroughs in warp drive technology! Discover how recent physics advancements could turn the dream of ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/V9Mpmidh69E/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/V9Mpmidh69E/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/V9Mpmidh69E/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"url": "https://www.youtube.com/watch?v=V9Mpmidh69E"
},
...생략...
]
}
🌍 get_trending_videos
국가별 인기 영상 목록을 조회합니다. ISO 국가 코드를 기반으로 지역을 지정할 수 있습니다.
uv run client.py get_trending_videos region_code=ko max_results=10
예시 결과:
{
"videos": [
{
"id": "GHsao4wyB48",
"title": "[61회 백상] 방송부문 남자 조연상 - 최대훈 | 폭싹 속았수다 | JTBC 250505 방송",
"description": "[61회 백상예술대상]\n방송부문 남자 조연상 - 최대훈 | 폭싹 속았수다\n\n#제61회백상예술대상 #방송부문남자조연상 #최대훈",
"publishedAt": "2025-05-05T13:52:27Z",
"channelId": "UCVXN28NHfphVQrdtjooc33g",
"channelTitle": "백상예술대상",
"viewCount": "1849316",
"likeCount": "40698",
"commentCount": "3696",
...생략...
"url": "https://www.youtube.com/watch?v=GHsao4wyB48"
},
...생략...
]
}
🧠 get_video_enhanced_transcript
시간 범위 필터, 키워드 검색, 세그먼트 분할 등 고급 설정이 가능한 트랜스크립트 추출 기능입니다.
uv run client.py get_video_enhanced_transcript video_ids=zRgAEIoZEVQ language=ko format=timestamped include_metadata=true start_time=100 end_time=200 query=에이전트 case_sensitive=true segment_method=equal segment_count=2
예시 결과:
{
"videos": [
{
"videoId": "zRgAEIoZEVQ",
"metadata": {
"id": "zRgAEIoZEVQ",
"title": "코딩 없이 누구나 Cursor AI로 인공지능 비서, AI 에이전트 만들기 | MCP, Google ADK",
"channelTitle": "코드깎는노인",
"publishedAt": "2025-04-19T04:19:59Z",
"duration": "PT12M48S"
},
"segments": [
{
"index": 0,
"segments": [
{
"text": "셀렉트 항목을 선택을 해 줘야",
"start": 174.72,
"duration": 4.56,
"timestamp": "02:54"
},
...생략...
]
}
MCP 코드 구조 이해하기
MCP 서버는 @mcp. tool, @mcp. prompt, @mcp. resource 세 가지 주요 데코레이터를 통해 기능을 정의합니다. 아래는 각각의 구성 방식과 실제 코드 예시입니다.
🛠 Tool: YouTube 기능을 실행하는 작업 단위
Tool은 서버가 외부 요청에 대해 실행하는 기능입니다. 예를 들어, search_videos 툴은 다음과 같이 정의됩니다:
@mcp.tool(
name="search_videos",
description="Search for YouTube videos with advanced filtering options",
)
async def search_videos(query: str, max_results: Optional[int] = 10, ...):
...
이 함수는 사용자로부터 검색어(query)를 입력받아 YouTube API를 통해 검색 결과를 반환합니다.
💬 Prompt: LLM이 사용할 프롬프트 생성기
Prompt는 LLM이 참조할 입력 메시지를 동적으로 구성합니다. 예시는 다음과 같습니다:
@mcp.prompt(
name="transcript_summary",
description="Generate a summary of a YouTube video based on its transcript."
)
async def transcript_summary(video_id: str, ...):
return {
'messages': [{
'role': 'user',
'content': formatted_transcript_with_prompt
}]
}
이 프롬프트는 영상 자막을 기반으로 LLM이 요약을 생성할 수 있도록 구성된 메시지를 반환합니다.
📦 Resource: 데이터나 정보 리소스를 직접 제공하는 엔드포인트
Resource는 정적인 결과나 특정 데이터에 대한 정보 제공에 특화된 구조입니다. 예:
@mcp.resource(
uri="youtube://video/{video_id}",
name="video",
description="Get detailed information about a specific YouTube video"
)
async def get_video_resource(video_id: str) -> Dict[str, Any]:
video_data = youtube_service.get_video_details(video_id)
...
이 리소스는 youtube://video/영상 ID 형식으로 접근할 수 있으며, 영상의 메타정보를 반환합니다.
이러한 구조 덕분에 Claude Desktop이나 Cursor 같은 AI 플랫폼은 툴과 리소스를 호출하거나 프롬프트 생성을 요청할 수 있으며, 이는 곧 강력한 YouTube AI 기능으로 이어집니다.
설치 및 설정
설치
# 1. 저장소 클론
git clone https://github.com/jikime/py-mcp-youtube-toolbox.git
cd py-mcp-youtube-toolbox
# 2. UV 설치 및 환경 구성
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv -p 3.12
source .venv/bin/activate
uv pip install -r requirements.txt
# 3. .env 파일 생성 후 API 키 입력
cp env.example .env
vi .env
YOUTUBE_API_KEY=your_key_here
실행 방법
# MCP 서버 실행
mcp run server.py
# MCP Inspector 실행
mcp dev server.py
# 클라이언트 예시 호출
uv run client.py search_videos query="AI"
도커로 서버 실행하기 및 Dockerfile 설명
YouTube MCP 서버는 Docker를 사용하여 간편하게 배포할 수 있습니다. 아래는 Dockerfile의 구성 요소에 대한 설명입니다.
Dockerfile 내용
# Generated by https://smithery.ai. See: https://smithery.ai/docs/config#dockerfile
FROM python:3.12-slim
# Set a working directory
WORKDIR /app
# Copy all files to the container
COPY . .
# Install Python dependencies
RUN pip install --no-cache-dir google-api-python-client mcp[cli] python-dotenv youtube-transcript-api
# Set environment variables placeholders (they will be overridden by startCommand config)
ENV YOUTUBE_API_KEY=your_youtube_api_key
# Command to run the MCP server
CMD ["python", "server.py"]
주요 항목 설명
- FROM python:3.12-slim: Python 3.12 경량 이미지 기반으로 도커 환경을 구성합니다. 가볍고 빠른 실행을 위해 slim 버전을 사용합니다.
- WORKDIR /app: 컨테이너 내 작업 디렉터리를 /app으로 설정합니다.
- COPY..: 현재 프로젝트 디렉터리의 모든 파일을 컨테이너 내부 /app 디렉터리로 복사합니다.
- RUN pip install...: 필요한 Python 라이브러리들을 설치합니다. google-api-python-client, mcp [cli], dotenv, youtube-transcript-api 등이 포함됩니다.
- ENV YOUTUBE_API_KEY=...: 환경 변수로 YouTube API 키를 선언합니다. 실제 실행 시 외부에서 주입되므로 값은 교체됩니다.
- CMD ["python", "server.py"]: 컨테이너 시작 시 실행할 명령어를 정의합니다. MCP 서버가 자동으로 시작됩니다.
실행 방법
docker build -t py-mcp-youtube-toolbox .
docker run -e YOUTUBE_API_KEY=your_api_key py-mcp-youtube-toolbox
이 방식은 로컬 개발 환경이 없어도 동일한 설정으로 서버를 실행할 수 있도록 해줍니다. 특히 클라우드 환경이나 교육용 데모에 유용하게 활용됩니다.
Claude Desktop 및 Cursor에서 사용
YouTube MCP 서버를 Claude Desktop 앱이나 Cursor IDE에서 직접 호출할 수 있도록 설정하려면 MCP 서버 설정 정보를 등록해야 합니다.
Claude Desktop 설정
- 설정 파일 위치: ~/Library/Application Support/Claude/claude_desktop_config.json
- 설정 예시:
{
"mcpServers": {
"YouTube Toolbox": {
"command": "/usr/local/bin/uv",
"args": [
"--directory",
"/path/to/py-mcp-youtube-toolbox",
"run",
"server.py"
],
"env": {
"YOUTUBE_API_KEY": "your_youtube_api_key"
}
}
}
}
Cursor I설정
- 설정 파일 위치: ~/. cursor/mcp.json
- 설정 예시:
{
"mcpServers": {
"YouTube Toolbox": {
"command": "/usr/local/bin/uv",
"args": [
"--directory",
"/path/to/py-mcp-youtube-toolbox",
"run",
"server.py"
],
"env": {
"YOUTUBE_API_KEY": "your_youtube_api_key"
}
}
}
}
Docker 설정
{
"mcpServers": {
"YouTube Toolbox": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e", "YOUTUBE_API_KEY=your_youtube_api_key",
"py-mcp-youtube-toolbox"
]
}
}
}
'Cook AI' 카테고리의 다른 글
Context7 MCP: LLM 코드 생성의 한계를 넘어서는 최신 정보 활용법 (1) | 2025.05.10 |
---|---|
GitHub 저장소를 이용한 Smithery 서버 등록 및 배포 (6) | 2025.05.09 |
코딩의 첫걸음: 도구와 프로젝트 구성 (5) | 2025.05.05 |
커서의 챗 기능: AI로 혁신하는 코드 편집과 관리 (3) | 2025.05.04 |
네이버 검색 API를 활용한 MCP 서버를 만들어보자. (0) | 2025.04.30 |