youtube-analytics-mcp
v1.0.6
Published
YouTube Analytics MCP
Downloads
95
Readme
YouTube Analytics MCP Server
A Model Context Protocol (MCP) server for YouTube Analytics — 26 tools for channel health, video performance, audience insights, revenue, and more.
Installation
Claude Code
claude mcp add youtube-analytics --scope user -- npx youtube-analytics-mcp@latestClaude Desktop
Add to your claude_desktop_config.json:
{
"mcpServers": {
"youtube-analytics": {
"command": "npx",
"args": ["youtube-analytics-mcp@latest"]
}
}
}Codex
codex mcp add youtube-analytics -- npx youtube-analytics-mcp@latestManual / Other Clients
npx youtube-analytics-mcp@latestSetup
Google API Credentials
- Go to the Google Cloud Console
- Create a new project or select an existing one
- Enable the YouTube Analytics API and YouTube Data API v3
- Go to "Credentials" and create a new OAuth 2.0 Client ID
- Download the credentials as JSON
- Save the file as
credentials.jsonin thesrc/auth/directory
On first use, the server will open a browser window for OAuth authentication. Tokens are cached locally for subsequent use.
Privacy Note: All data processing happens locally on your computer. Your credentials and analytics data never leave your machine.
Development
# Install dependencies
npm install
# Build the project
npm run build
# Run in development mode
npm run dev
# Inspect with MCP Inspector
npm run inspectArchitecture Overview
Project Structure
src/
├── index.ts # Main server entry point (config-driven)
├── tool-configs.ts # Central tool configuration aggregator
├── types.ts # TypeScript interfaces and types
├── auth/
│ ├── tool-configs.ts # Authentication tool configurations
│ └── ...
├── server/
│ ├── info-configs.ts # Server info tool configurations
│ └── ...
└── youtube/tools/
├── channel-configs.ts # Channel analysis tool configurations
├── health-configs.ts # Channel health tool configurations
├── audience-configs.ts # Audience demographics tool configurations
├── discovery-configs.ts # Traffic source tool configurations
├── performance-configs.ts # Performance analysis tool configurations
└── engagement-configs.ts # Engagement metrics tool configurationsTool Configuration Structure
Each tool is defined by a configuration object:
interface ToolConfig<T = any> {
name: string; // Tool name
description: string; // Tool description
schema: any; // Zod schema for validation
handler: (params: T, context: ToolContext) => Promise<ToolResult>;
category?: string; // Optional grouping
}Available Tools (26)
Channel Tools
get_channel_info- Get basic channel informationget_channel_videos- Get list of channel videos with filtersget_video_details- Get detailed info for a specific video (title, tags, stats, duration)
Health Tools
get_channel_overview- Get channel vital signs and growth patternsget_comparison_metrics- Compare metrics between time periodsget_average_view_percentage- Get average view percentageget_watch_time_metrics- Get daily watch time breakdownget_revenue_metrics- Get revenue, ad revenue, YouTube Premium revenue, and CPMget_top_videos- Get top performing videos ranked by any metric
Audience Tools
get_video_demographics- Get age/gender breakdownget_geographic_distribution- Get viewer geographic distributionget_subscriber_analytics- Get subscriber vs non-subscriber analyticsget_device_analytics- Get device type and OS breakdown (mobile, desktop, TV, etc.)
Discovery Tools
get_optimal_posting_time- Get optimal posting time analysis with day-of-week patternsget_traffic_sources- Get traffic source analysisget_search_terms- Get search terms for SEO insights
Performance Tools
get_audience_retention- Track viewer retention patternsget_retention_dropoff_points- Find exact drop-off momentsget_playlist_performance- Get playlist starts, views per start, and average timeget_card_endscreen_performance- Get card impressions, clicks, and click-through rateget_video_performance_over_time- Get daily performance breakdown for a specific video
Engagement Tools
get_engagement_metrics- Analyze likes, comments, and sharesget_sharing_analytics- Get sharing service breakdown (WhatsApp, Twitter, etc.)
Authentication Tools
check_auth_status- Check YouTube authentication statusrevoke_auth- Revoke authentication and clear tokens
Adding New Tools
To add a new tool, simply create a configuration object and add it to the appropriate config file:
// In src/youtube/tools/new-category-configs.ts
export const newCategoryToolConfigs: ToolConfig[] = [
{
name: "new_tool_name",
description: "Description of what the tool does",
category: "new_category",
schema: z.object({
// Define your parameters here
param1: z.string().describe("Description of parameter 1"),
param2: z.number().optional().describe("Optional parameter 2"),
}),
handler: async ({ param1, param2 }, { getYouTubeClient }: ToolContext) => {
try {
const youtubeClient = await getYouTubeClient();
// Your tool implementation here
return {
content: [{
type: "text",
text: "Tool result here"
}]
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}
},
},
];
// Then add to src/tool-configs.ts
export const allToolConfigs = [
// ... existing configs
...newCategoryToolConfigs,
];Benefits of Config-Driven Architecture
- Clean Separation: Tool definitions are separate from server setup
- Type Safety: Full TypeScript support for schemas and handlers
- Documentation: Config serves as living documentation
- Testing: Easier to unit test individual tools
- Extensibility: Simple to add new tool categories
- Maintainability: Consistent patterns across all tools
- Scalability: Easy to manage many tools without cluttering main file
Server Registration Pattern
The server automatically registers all tools from configuration:
// Automatic registration from configs - no manual server.tool() calls needed
allToolConfigs.forEach((toolConfig) => {
server.tool(
toolConfig.name, // Tool name from config
toolConfig.description, // Description from config
toolConfig.schema, // Zod schema from config
async (params: any) => { // Handler wrapper
return toolConfig.handler(params, {
authManager,
getYouTubeClient,
clearYouTubeClientCache
});
}
);
});Error Handling
All tools follow a consistent error handling pattern:
try {
// Tool implementation
return {
content: [{ type: "text", text: "Success result" }]
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error: ${error instanceof Error ? error.message : String(error)}`
}],
isError: true
};
}Context Injection
Tools receive a context object with shared dependencies:
interface ToolContext {
authManager: AuthManager;
getYouTubeClient: () => Promise<YouTubeClient>;
clearYouTubeClientCache: () => void;
}This architecture makes the codebase more maintainable, scalable, and easier to extend while preserving all existing functionality.
