Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

compare_periods

Compare Google Analytics 4 data between two time periods to analyze trends, identify changes in metrics like page views and user engagement, and track performance over time.

Instructions

2つの期間を比較します。前週比、前月比、前年同期比などの分析が可能です。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
comparisonTypeYes比較タイプ(previousPeriod: 直前期間、previousYear: 前年同期、custom: カスタム)
periodNo基準期間(comparisonTypeがcustom以外の場合に使用)
period1No比較期間1(comparisonTypeがcustomの場合に使用)
period2No比較期間2(comparisonTypeがcustomの場合に使用)
metricsNo比較するメトリクス(デフォルト: ["screenPageViews", "totalUsers", "sessions"])

Implementation Reference

  • The core asynchronous handler function `comparePeriods` that implements the tool's logic. It processes input to determine two date ranges (based on comparison type: previousPeriod, previousYear, or custom), fetches GA4 reports using `executeReport` for specified metrics, computes comparisons (change, percentage, trend), and returns formatted output.
    export async function comparePeriods(
      input: ComparePeriodInput
    ): Promise<ComparePeriodOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
    
      // 期間を決定
      let period1: DateRange;
      let period2: DateRange;
    
      if (input.comparisonType === "custom") {
        if (!input.period1 || !input.period2) {
          throw new Error(
            "custom 比較タイプの場合は period1 と period2 を指定してください"
          );
        }
        period1 = input.period1;
        period2 = input.period2;
      } else {
        const period = input.period || "7days";
        period1 = periodToDateRange(period);
    
        if (input.comparisonType === "previousYear") {
          period2 = getPreviousYearPeriod(period1);
        } else {
          // previousPeriod
          period2 = getPreviousPeriod(period1);
        }
      }
    
      // 比較するメトリクス
      const metrics = input.metrics || [
        "screenPageViews",
        "totalUsers",
        "sessions",
      ];
    
      // 期間1のデータ取得
      const response1 = await executeReport({
        property,
        dateRanges: [period1],
        metrics: metrics.map((name) => ({ name })),
      });
    
      // 期間2のデータ取得
      const response2 = await executeReport({
        property,
        dateRanges: [period2],
        metrics: metrics.map((name) => ({ name })),
      });
    
      // 結果を比較
      const comparison: MetricComparison[] = [];
    
      const metricValues1 = response1.totals?.[0]?.metricValues || [];
      const metricValues2 = response2.totals?.[0]?.metricValues || [];
    
      for (let i = 0; i < metrics.length; i++) {
        const metricName = metrics[i];
        const value1 = metricValues1[i]?.value
          ? parseFloat(metricValues1[i].value!)
          : 0;
        const value2 = metricValues2[i]?.value
          ? parseFloat(metricValues2[i].value!)
          : 0;
    
        const changeData = formatChange(value1, value2);
    
        comparison.push({
          metric: formatMetricName(metricName),
          period1Value: Math.round(value1),
          period2Value: Math.round(value2),
          ...changeData,
        });
      }
    
      return {
        period1: { ...period1, label: getPeriodLabel(period1) },
        period2: { ...period2, label: getPeriodLabel(period2) },
        comparison,
      };
    }
  • TypeScript interfaces and types defining the input (ComparePeriodInput), output (ComparePeriodOutput), and supporting types (ComparisonType, DateRange, MetricComparison) for the compare_periods tool.
    // compare_periods
    export type ComparisonType = "previousPeriod" | "previousYear" | "custom";
    
    export interface DateRange {
      startDate: string;
      endDate: string;
    }
    
    export interface ComparePeriodInput extends PropertyId {
      comparisonType: ComparisonType;
      period?: "7days" | "28days" | "30days";
      period1?: DateRange;
      period2?: DateRange;
      metrics?: string[];
    }
    
    export interface MetricComparison {
      metric: string;
      period1Value: number;
      period2Value: number;
      change: number;
      changePercent: string;
      trend: "up" | "down" | "flat";
    }
    
    export interface ComparePeriodOutput {
      period1: DateRange & { label: string };
      period2: DateRange & { label: string };
      comparison: MetricComparison[];
    }
  • src/server.ts:311-356 (registration)
    Registration of the 'compare_periods' tool in the MCP server's tools array, including name, description, and Zod-compatible input schema matching the TypeScript types.
    {
      name: "compare_periods",
      description:
        "2つの期間を比較します。前週比、前月比、前年同期比などの分析が可能です。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          comparisonType: {
            type: "string",
            enum: ["previousPeriod", "previousYear", "custom"],
            description:
              "比較タイプ(previousPeriod: 直前期間、previousYear: 前年同期、custom: カスタム)",
          },
          period: {
            type: "string",
            enum: ["7days", "28days", "30days"],
            description:
              "基準期間(comparisonTypeがcustom以外の場合に使用)",
          },
          period1: {
            type: "object",
            properties: {
              startDate: { type: "string" },
              endDate: { type: "string" },
            },
            description: "比較期間1(comparisonTypeがcustomの場合に使用)",
          },
          period2: {
            type: "object",
            properties: {
              startDate: { type: "string" },
              endDate: { type: "string" },
            },
            description: "比較期間2(comparisonTypeがcustomの場合に使用)",
          },
          metrics: {
            type: "array",
            items: { type: "string" },
            description:
              '比較するメトリクス(デフォルト: ["screenPageViews", "totalUsers", "sessions"])',
          },
        },
        required: ["comparisonType"],
      },
    },
  • Dispatch handler in the switch statement of handleToolCall that invokes the comparePeriods function with parsed arguments for the 'compare_periods' tool call.
    case "compare_periods":
      return await comparePeriods({
        propertyId: args.propertyId as string | undefined,
        comparisonType: args.comparisonType as
          | "previousPeriod"
          | "previousYear"
          | "custom",
        period: args.period as "7days" | "28days" | "30days" | undefined,
        period1: args.period1 as
          | { startDate: string; endDate: string }
          | undefined,
        period2: args.period2 as
          | { startDate: string; endDate: string }
          | undefined,
        metrics: args.metrics as string[] | undefined,
      });
  • Re-export of the comparePeriods handler from its module, allowing barrel import in server.ts.
    export { comparePeriods } from "./comparePeriods.js";
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While it states the tool performs comparisons, it doesn't describe what the comparison output looks like, whether it requires specific permissions, what happens with invalid date ranges, or any rate limits. For a tool with 6 parameters including nested objects, this is insufficient behavioral context.

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 extremely concise - just two sentences in Japanese that efficiently convey the core functionality. Every word earns its place, with no redundant information. The structure is front-loaded with the main purpose followed by specific examples.

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

Completeness2/5

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

Given the tool's complexity (6 parameters including nested objects), lack of annotations, and no output schema, the description is incomplete. It doesn't explain what the comparison output looks like, how results are formatted, what metrics are available beyond the defaults, or any error conditions. For a comparison tool with multiple parameter configurations, more context is needed.

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?

The schema description coverage is 100%, so all parameters are documented in the schema. The description mentions comparison types (week-over-week, month-over-month, year-over-year) which aligns with the comparisonType enum values, but adds little beyond what's already in the comprehensive schema descriptions. Baseline 3 is appropriate when the schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool's purpose as 'compare two periods' and provides specific examples of comparison types (week-over-week, month-over-month, year-over-year analysis). However, it doesn't explicitly differentiate this comparison tool from other analytics tools in the sibling list, which includes various reporting tools like get_daily_trend and run_report.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus the many other analytics tools available (like get_daily_trend, run_report, get_traffic_summary). It mentions what types of comparisons are possible but gives no context about appropriate use cases or when to choose this over alternative tools.

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/Shin-sibainu/ga4-mcp-server'

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