npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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@latest

Claude 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@latest

Manual / Other Clients

npx youtube-analytics-mcp@latest

Setup

Google API Credentials

  1. Go to the Google Cloud Console
  2. Create a new project or select an existing one
  3. Enable the YouTube Analytics API and YouTube Data API v3
  4. Go to "Credentials" and create a new OAuth 2.0 Client ID
  5. Download the credentials as JSON
  6. Save the file as credentials.json in the src/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 inspect

Architecture 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 configurations

Tool 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 information
  • get_channel_videos - Get list of channel videos with filters
  • get_video_details - Get detailed info for a specific video (title, tags, stats, duration)

Health Tools

  • get_channel_overview - Get channel vital signs and growth patterns
  • get_comparison_metrics - Compare metrics between time periods
  • get_average_view_percentage - Get average view percentage
  • get_watch_time_metrics - Get daily watch time breakdown
  • get_revenue_metrics - Get revenue, ad revenue, YouTube Premium revenue, and CPM
  • get_top_videos - Get top performing videos ranked by any metric

Audience Tools

  • get_video_demographics - Get age/gender breakdown
  • get_geographic_distribution - Get viewer geographic distribution
  • get_subscriber_analytics - Get subscriber vs non-subscriber analytics
  • get_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 patterns
  • get_traffic_sources - Get traffic source analysis
  • get_search_terms - Get search terms for SEO insights

Performance Tools

  • get_audience_retention - Track viewer retention patterns
  • get_retention_dropoff_points - Find exact drop-off moments
  • get_playlist_performance - Get playlist starts, views per start, and average time
  • get_card_endscreen_performance - Get card impressions, clicks, and click-through rate
  • get_video_performance_over_time - Get daily performance breakdown for a specific video

Engagement Tools

  • get_engagement_metrics - Analyze likes, comments, and shares
  • get_sharing_analytics - Get sharing service breakdown (WhatsApp, Twitter, etc.)

Authentication Tools

  • check_auth_status - Check YouTube authentication status
  • revoke_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

  1. Clean Separation: Tool definitions are separate from server setup
  2. Type Safety: Full TypeScript support for schemas and handlers
  3. Documentation: Config serves as living documentation
  4. Testing: Easier to unit test individual tools
  5. Extensibility: Simple to add new tool categories
  6. Maintainability: Consistent patterns across all tools
  7. 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.