带有MCP的YouTube下载器代理
一个使用(某技术/框架/方法)的完整AI代理示例 模型上下文协议(MCP) 用于下载YouTube视频和音频。此项目展示了通过HTTP上的SSE传输实现的MCP(可能是指某种客户端-服务器协议或框架,具体需根据上下文确定,此处保留原英文缩写)客户端-服务器架构的正确实现。
特点/特性
- MCP 服务器-客户端架构职责的适当分离
- 视频下载下载YouTube视频,获取最高可用分辨率
- 音频下载从YouTube视频中提取音频
- SSE运输基于HTTP的MCP通信
- 异步操作非阻塞工具执行
- 工具发现从MCP服务器自动检测工具
- 本地大型语言模型(Local LLM)使用本地llama.cpp服务器(无需外部API费用)
建筑学
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ LLM Server │ ←────→ │ MCP Client │ ←────→ │ MCP Server │
│ :8000 │ │ (main.py) │ HTTP │ :8001 │
└─────────────┘ └─────────────┘ └─────────────┘要求
- Python 3.11及以上版本
- 本地 llama.cpp 服务器运行在
localhost:8000(可定制) - 一个兼容的模型文件(例如,Gemma-3-4b-it.gguf)
快速入门
1. 安装依赖项
uv sync2. 启动本地LLM服务器(终端1)
llama-server -m path/to/your-model.gguf -p 8000 --jinja (not included in the project. You need to install llama-server yourself)3. 启动MCP服务器(终端2)
uv run mcp-server/yt-media-mcp.pyMCP服务器将在(指定时间/条件下)启动 http://localhost:8001
4. 运行代理(终端3)
uv run main.py5. 试试看!
=== YouTube Downloader Agent with MCP ===
Connecting to MCP server...
✓ Connected! Found 2 tools
Type 'exit' to quit
User: Download this video: https://youtube.com/watch?v=example to ./downloads
Agent:
-- Executing download_video on MCP server...
I've successfully downloaded the video to ./downloads/项目结构
yt-media-mcp-project/
├── main.py # MCP Client (AI Agent)
├── mcp-server/
│ └── yt-media-mcp.py # MCP Server (Tool Provider)
├── pyproject.toml # Dependencies
└── README.md # This file它是如何工作的
1. 工具发现
当客户端启动时,它会连接到MCP服务器并发现可用的工具:
available_tools = await discover_mcp_tools()
# Fetches tool schemas from http://localhost:8001/tools2. 用户请求 → 大语言模型(LLM)
用户输入连同可用的工具定义一起发送给大型语言模型(LLM):
resp = llm_client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
tools=available_tools # Auto-discovered from MCP server
)3. 在MCP服务器上执行工具
如果大型语言模型(LLM)决定使用某个工具,客户端将通过HTTP调用MCP服务器:
output = await call_mcp_tool(tool_name, arguments)
# POST to http://localhost:8001/call4. MCP服务器处理请求
服务器异步执行该工具:
@mcp.tool()
async def download_video(url: str, output_dir: str) -> str:
# Downloads video using pytubefix
# Returns result as JSON5. 最终回应
工具的结果被发送回大型语言模型(LLM),以生成自然语言的回复。
关键特性解析
MCP 客户端 (main.py)
- 工具发现自动从服务器获取可用工具
- HTTP通信通过SSE/HTTP连接到MCP服务器
- 异步操作非阻塞工具执行
- 大型语言模型(LLM)集成与任何兼容OpenAI的API一起工作
MCP 服务器(mcp-server/yt-media-mcp.py)
- FastMCP 框架基于装饰器的简单工具定义
- SSE运输(公司)基于HTTP的服务器,运行在8001端口
- 异步工具用途
asyncio.to_thread()用于阻塞操作 - 工具注册通过工具自动暴露
@mcp.tool()装饰器
配置
更改端口
MCP服务器 - 编辑 mcp-server/yt-media-mcp.py:
mcp = FastMCP(
"simple-yt-downloader",
host="127.0.0.1",
port=8001 # Change this port
)或者使用环境变量(无需更改代码):
FASTMCP_SERVER_HOST=0.0.0.0 FASTMCP_SERVER_PORT=9000 python mcp-server/yt-media-mcp.py客户 (main.py):
MCP_SERVER_URL = "http://127.0.0.1:8001" # Match server port大型语言模型服务器 (main.py):
LLM_BASE_URL = "http://localhost:8000/v1"使用远程大型语言模型(如OpenAI、Anthropic等)
更新于 main.py:
LLM_BASE_URL = "https://api.openai.com/v1"
LLM_API_KEY = "your-api-key-here"
MODEL_NAME = "gpt-4"