# MCP (Model Context Protocol) Explained
## Table of Contents
1. [What is MCP](#what-is-mcp)
2. [Core Architecture](#core-architecture)
3. [Communication Flow](#communication-flow)
4. [Code Implementation](#code-implementation)
5. [FAQ](#faq)
---
## What is MCP?
**MCP (Model Context Protocol)** is an open protocol developed by Anthropic for standardized communication between AI applications and external tools/data sources.
### Core Benefits
- **Standardized**: Write once, use with any MCP-compatible AI
- **Secure**: Server runs locally, data stays private
- **Flexible**: Connect to any API, database, or local tool
- **Natural**: Users interact in natural language, AI handles tool selection
---
## Core Architecture
### Three-Layer Design
```
┌─────────────────────────────────────────────────────────┐
│ User Layer │
│ │
│ User asks in natural language: │
│ "Find trending AI Shorts from the last 24 hours" │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ AI Layer (Claude Desktop) │
│ │
│ 1. Understand user intent │
│ 2. Select appropriate tool │
│ 3. Construct tool parameters │
│ 4. Call Server via MCP │
│ 5. Present results to user │
└─────────────────────────────────────────────────────────┘
↓ MCP Protocol
┌─────────────────────────────────────────────────────────┐
│ Tool Layer (MCP Server) │
│ │
│ 1. Expose tool list │
│ 2. Receive tool calls │
│ 3. Execute business logic (YouTube API) │
│ 4. Return formatted results │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Data Layer (YouTube API) │
│ │
│ Provide raw video data │
└─────────────────────────────────────────────────────────┘
```
---
## Communication Flow
### Complete Interaction Flow
```
┌─────────────┐ ┌─────────────┐
│ Claude │ │ MCP Server │
│ Desktop │ │ │
└──────┬──────┘ └──────┬──────┘
│ │
│ ① Startup: Request tool list │
│────────────────────────────────────────>│
│ │
│ ② Return available tools │
│<────────────────────────────────────────│
│ │
│ ③ User input (natural language) │
│ "Find trending AI Shorts" │
│ │
│ ④ Claude parses and selects tool │
│ │
│ ⑤ Call tool │
│ call_tool( │
│ name="get_youtube_shorts_trends", │
│ arguments={"keyword": "AI"} │
│ ) │
│────────────────────────────────────────>│
│ │
│ ⑥ Server executes logic ┌────┴────┐
│ │ YouTube │
│ │ API │
│ └────┬────┘
│ │
│ ⑦ Return results │
│<────────────────────────────────────────│
│ │
│ ⑧ Claude formats and displays │
│ │
```
### Protocol Details
MCP uses **JSON-RPC 2.0** over **stdio** (standard input/output).
**Example: Tool List Request**
```json
// Claude → Server
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list"
}
// Server → Claude
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "get_youtube_shorts_trends",
"description": "Discover trending YouTube Shorts",
"inputSchema": {
"type": "object",
"properties": {
"keyword": {"type": "string"},
"hours_ago": {"type": "integer"}
}
}
}
]
}
}
```
---
## Code Implementation
### 1. Server Initialization
```python
from mcp.server import Server
app = Server("youtube-shorts-viral-agent")
```
**Purpose:** Create MCP Server instance with unique identifier.
---
### 2. Register Tool List
```python
@app.list_tools()
async def list_tools() -> list[Tool]:
return [
Tool(
name="get_youtube_shorts_trends",
description="Discover trending YouTube Shorts",
inputSchema={
"type": "object",
"properties": {
"keyword": {
"type": "string",
"description": "Search keyword",
"default": ""
},
"hours_ago": {
"type": "integer",
"description": "Time range in hours",
"default": 24
}
}
}
)
]
```
**Key Points:**
- `@app.list_tools()` decorator registers tool list function
- Claude calls this on startup to discover tools
- `inputSchema` uses JSON Schema format
- Claude uses `description` to understand when to use each tool
---
### 3. Handle Tool Calls
```python
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
if name == "get_youtube_shorts_trends":
# Execute business logic
client = YouTubeClient()
videos = client.get_trending_shorts(
keyword=arguments.get("keyword", ""),
hours_ago=arguments.get("hours_ago", 24)
)
# Generate report
report = "# Trending Report\n..."
# Return TextContent
return [TextContent(type="text", text=report)]
```
**Key Points:**
- `@app.call_tool()` decorator registers call handler
- Parameters: `name` (tool name), `arguments` (JSON object)
- Must return `list[TextContent]`
- Can return Markdown-formatted text
---
### 4. Start Server
```python
def main():
import asyncio
from mcp.server.stdio import stdio_server
async def run():
async with stdio_server() as (read_stream, write_stream):
await app.run(
read_stream,
write_stream,
app.create_initialization_options()
)
asyncio.run(run())
if __name__ == "__main__":
main()
```
**Key Points:**
- Uses `stdio_server` for stdin/stdout communication
- Claude Desktop launches this Python process
- Communicates via JSON-RPC messages
---
## FAQ
### Q1: How is MCP different from regular APIs?
**Regular API:**
```python
result = get_youtube_shorts_trends(keyword="AI", hours_ago=24)
```
**MCP:**
```
User: Find trending AI Shorts
Claude: [Auto-selects tool, calls it, displays results]
```
**Difference:** MCP uses AI to understand natural language, auto-selecting tools and parameters. Users don't need to learn API docs.
---
### Q2: Why stdio instead of HTTP?
**stdio Advantages:**
1. **Simple**: No port management or HTTP server
2. **Secure**: Process isolation, no network exposure
3. **Efficient**: Local communication, low latency
4. **Standard**: Supported on all operating systems
---
### Q3: How to debug MCP Server?
**Method 1: Check Claude Desktop logs**
- Windows: `%APPDATA%\Claude\logs\`
- macOS: `~/Library/Logs/Claude/`
**Method 2: Add logging**
```python
import sys
# Output to stderr (won't interfere with MCP)
print("Debug: Tool called", file=sys.stderr)
```
---
### Q4: What content types can be returned?
MCP supports multiple content types:
1. **TextContent**: Plain text or Markdown
2. **ImageContent**: Images (base64 or URL)
3. **ResourceContent**: Files or resources
This project uses **TextContent + Markdown** because Claude renders tables and links well.
---
## Summary
### MCP Core Advantages
1. **Natural Interaction**: Users speak naturally, no API learning needed
2. **Standardized**: Write once, works with all MCP clients
3. **Secure**: Runs locally, data stays private
4. **Flexible**: Connect to any data source or tool
### This Project's MCP Implementation
- **5 Tools**: Trends, video analysis, topics, story summary, niche discovery
- **Smart Algorithms**: VPH, engagement rate, viral score
- **Rich Output**: Markdown tables + detailed reports
- **Well-Documented**: Code includes detailed explanations
---
**References:**
- [MCP Official Docs](https://modelcontextprotocol.io/)
- [FastMCP GitHub](https://github.com/jlowin/fastmcp)
- [JSON-RPC 2.0 Spec](https://www.jsonrpc.org/specification)