Skip to main content
Glama

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";

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