Skip to main content
Glama

query_channel_analytics

Retrieve YouTube Analytics data for your channel, including views, watch time, and traffic sources. Supports date ranges and optional grouping by dimensions like day or video.

Instructions

Query YouTube Analytics for the authenticated channel. Returns tabular data — useful for views/watch-time/retention/traffic-source reports. Date-ranged and optionally grouped by dimensions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
start_dateYesYYYY-MM-DD (inclusive)
end_dateYesYYYY-MM-DD (inclusive)
metricsNoComma-separated metric names (see YouTube Analytics API). Defaults cover the most common creator-dashboard stats.views,estimatedMinutesWatched,averageViewDuration,subscribersGained
dimensionsNoComma-separated dimensions, e.g. 'day', 'video', 'country'. Omit for channel totals.
filtersNoFilter expression, e.g. 'video==VIDEO_ID' to scope to one video, or 'country==US'.
sortNoSort spec, e.g. '-views' for descending by views
max_resultsNo

Implementation Reference

  • The handler function that executes the query_channel_analytics tool logic. It calls client.analyticsQuery() with the parsed arguments and formats the result as a tabular text response.
      async (args) => {
        const res = await client.analyticsQuery({
          startDate: args.start_date,
          endDate: args.end_date,
          metrics: args.metrics,
          dimensions: args.dimensions,
          filters: args.filters,
          sort: args.sort,
          maxResults: args.max_results,
        });
        const header = res.columnHeaders.map((c) => c.name).join(" | ");
        const rows = res.rows.map((r) => r.join(" | "));
        return {
          content: [
            {
              type: "text" as const,
              text: [
                `Analytics ${args.start_date} → ${args.end_date}:`,
                "",
                header,
                "-".repeat(Math.max(10, header.length)),
                ...rows,
              ].join("\n"),
            },
          ],
        };
      },
    );
  • Input schema for query_channel_analytics, defined with zod. Defines start_date, end_date, metrics (with defaults), dimensions, filters, sort, and max_results.
    const analyticsSchema = {
      start_date: z
        .string()
        .regex(/^\d{4}-\d{2}-\d{2}$/)
        .describe("YYYY-MM-DD (inclusive)"),
      end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).describe("YYYY-MM-DD (inclusive)"),
      metrics: z
        .string()
        .default("views,estimatedMinutesWatched,averageViewDuration,subscribersGained")
        .describe(
          "Comma-separated metric names (see YouTube Analytics API). Defaults cover the most common creator-dashboard stats.",
        ),
      dimensions: z
        .string()
        .optional()
        .describe(
          "Comma-separated dimensions, e.g. 'day', 'video', 'country'. Omit for channel totals.",
        ),
      filters: z
        .string()
        .optional()
        .describe(
          "Filter expression, e.g. 'video==VIDEO_ID' to scope to one video, or 'country==US'.",
        ),
      sort: z
        .string()
        .optional()
        .describe("Sort spec, e.g. '-views' for descending by views"),
      max_results: z.number().int().min(1).max(200).optional(),
    };
  • Registration of the tool via server.tool() with name 'query_channel_analytics', description, schema, and handler.
    export function registerAnalyticsTool(server: McpServer, client: YouTubeClient): void {
      server.tool(
        "query_channel_analytics",
        "Query YouTube Analytics for the authenticated channel. Returns tabular data — useful for views/watch-time/retention/traffic-source reports. Date-ranged and optionally grouped by dimensions.",
        analyticsSchema,
        async (args) => {
          const res = await client.analyticsQuery({
            startDate: args.start_date,
            endDate: args.end_date,
            metrics: args.metrics,
            dimensions: args.dimensions,
            filters: args.filters,
            sort: args.sort,
            maxResults: args.max_results,
          });
          const header = res.columnHeaders.map((c) => c.name).join(" | ");
          const rows = res.rows.map((r) => r.join(" | "));
          return {
            content: [
              {
                type: "text" as const,
                text: [
                  `Analytics ${args.start_date} → ${args.end_date}:`,
                  "",
                  header,
                  "-".repeat(Math.max(10, header.length)),
                  ...rows,
                ].join("\n"),
              },
            ],
          };
        },
      );
    }
  • Helper method on YouTubeClient that builds and sends the YouTube Analytics API request with channel==MINE and the provided parameters.
    async analyticsQuery(params: {
      startDate: string;
      endDate: string;
      metrics: string;
      dimensions?: string;
      filters?: string;
      sort?: string;
      maxResults?: number;
    }): Promise<AnalyticsResponse> {
      return this.analyticsGet<AnalyticsResponse>("/reports", {
        ids: "channel==MINE",
        "start-date": params.startDate,
        "end-date": params.endDate,
        metrics: params.metrics,
        dimensions: params.dimensions,
        filters: params.filters,
        sort: params.sort,
        maxResults: params.maxResults ? String(params.maxResults) : undefined,
      });
    }
  • Low-level helper that constructs the YouTube Analytics API URL with query parameters and performs a GET request via the shared request method.
    async analyticsGet<T>(path: string, params: Record<string, string | undefined>): Promise<T> {
      const url = new URL(`${ANALYTICS_API}${path}`);
      for (const [k, v] of Object.entries(params)) {
        if (v !== undefined) url.searchParams.set(k, v);
      }
      return this.request<T>(url.toString(), { method: "GET" });
    }
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses that the tool returns tabular data and supports date-range and optional grouping, but does not mention authentication requirements, rate limits, error handling, or pagination behavior. The description provides some transparency but is incomplete.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences long, front-loaded with the primary purpose, and contains no unnecessary words. Every sentence adds value, making it highly concise and well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool has 7 parameters and no output schema, the description is brief. It does not explain the return format beyond 'tabular data', lacks details on error handling or edge cases, and does not cover how to interpret results. This leaves gaps for an agent using the tool in complex scenarios.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is high (86%), so the schema already documents parameters well. The description adds minimal value beyond the schema, only referencing date-range and optional grouping. It does not provide additional semantic meaning for parameters like 'filters' or 'sort'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it queries YouTube Analytics for the authenticated channel, specifying it returns tabular data for common metrics like views and watch-time. The verb 'Query' and resource 'YouTube Analytics for the authenticated channel' are specific, and it distinguishes from siblings like 'get_shorts_analytics' by being for general channel analytics.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description mentions the tool is useful for certain reports but does not explicitly say when to use it versus alternatives like 'get_shorts_analytics'. There is no guidance on when not to use it or exclusions, leaving the agent to infer usage context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/miller-joe/youtube-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server