compare_periods
Compare Google Analytics 4 data across different time periods to analyze trends, measure performance changes, and identify growth patterns using metrics like page views and user engagement.
Instructions
2つの期間を比較します。前週比、前月比、前年同期比などの分析が可能です。
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| propertyId | No | GA4プロパティID | |
| comparisonType | Yes | 比較タイプ(previousPeriod: 直前期間、previousYear: 前年同期、custom: カスタム) | |
| period | No | 基準期間(comparisonTypeがcustom以外の場合に使用) | |
| period1 | No | 比較期間1(comparisonTypeがcustomの場合に使用) | |
| period2 | No | 比較期間2(comparisonTypeがcustomの場合に使用) | |
| metrics | No | 比較するメトリクス(デフォルト: ["screenPageViews", "totalUsers", "sessions"]) |
Implementation Reference
- The async handler function that implements the core logic of the 'compare_periods' tool. It determines two date ranges based on input, fetches GA4 report data for specified metrics from each period, computes changes and trends, and returns a comparison 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, }; }
- src/server.ts:311-356 (schema)MCP tool schema definition for 'compare_periods' including name, description, and detailed inputSchema with properties for propertyId, comparisonType, periods, and metrics.{ 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"], }, },
- src/types.ts:223-251 (schema)TypeScript type definitions for ComparePeriodInput, ComparePeriodOutput, and supporting types used by the handler.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:671-686 (registration)Registration in the tool dispatch switch statement in handleToolCall, mapping 'compare_periods' to the comparePeriods function call with parsed arguments.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, });
- src/server.ts:60-356 (registration)The 'compare_periods' tool is registered in the 'tools' array used for listing available tools. Specific object at lines 311-356.const tools = [ // 基本ツール { name: "list_accounts", description: "GA4のアカウントとプロパティの一覧を取得します。どのプロパティIDを使うべきか確認する際に便利です。", inputSchema: { type: "object" as const, properties: {}, required: [], }, }, { name: "get_property_details", description: "指定したGA4プロパティの詳細情報(名前、タイムゾーン、通貨など)を取得します。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID(例: 123456789)", }, }, required: ["propertyId"], }, }, { name: "run_report", description: "GA4の汎用レポートを実行します。任意のディメンションとメトリクスを指定して柔軟にデータを取得できます。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID(省略時は環境変数GA4_PROPERTY_IDを使用)", }, startDate: { type: "string", description: '開始日(YYYY-MM-DD形式、または "today", "yesterday", "7daysAgo" など)', }, endDate: { type: "string", description: '終了日(YYYY-MM-DD形式、または "today", "yesterday" など)', }, dimensions: { type: "array", items: { type: "string" }, description: 'ディメンション名の配列(例: ["pagePath", "deviceCategory"])', }, metrics: { type: "array", items: { type: "string" }, description: 'メトリクス名の配列(例: ["screenPageViews", "sessions"])', }, dimensionFilter: { type: "object", description: "ディメンションフィルター(オプション)", properties: { fieldName: { type: "string" }, stringFilter: { type: "object", properties: { matchType: { type: "string", enum: [ "EXACT", "BEGINS_WITH", "ENDS_WITH", "CONTAINS", "REGEXP", ], }, value: { type: "string" }, caseSensitive: { type: "boolean" }, }, }, }, }, orderBy: { type: "object", description: "ソート設定(オプション)", properties: { metric: { type: "string" }, dimension: { type: "string" }, desc: { type: "boolean" }, }, }, limit: { type: "number", description: "取得件数(デフォルト: 10、最大: 100000)", }, }, required: ["startDate", "endDate", "dimensions", "metrics"], }, }, { name: "run_realtime_report", description: "リアルタイムレポートを実行し、現在のアクティブユーザー数などを取得します。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID(省略時は環境変数を使用)", }, dimensions: { type: "array", items: { type: "string" }, description: 'ディメンション(デフォルト: ["country", "deviceCategory"])', }, metrics: { type: "array", items: { type: "string" }, description: 'メトリクス(デフォルト: ["activeUsers"])', }, }, required: [], }, }, { name: "get_metadata", description: "利用可能なディメンションとメトリクスの一覧を取得します。run_reportで使える項目を確認できます。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID(省略時は環境変数を使用)", }, }, required: [], }, }, // 分析ツール { name: "get_traffic_summary", description: "指定期間のトラフィック概要(PV数、ユーザー数、セッション数、直帰率など)を取得します。ダッシュボード的な使い方に最適です。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["today", "yesterday", "7days", "28days", "30days", "90days"], description: "集計期間", }, }, required: ["period"], }, }, { name: "get_top_pages", description: "人気ページのランキングを取得します。PV数、滞在時間、直帰率などを確認できます。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["today", "yesterday", "7days", "28days", "30days"], description: "集計期間", }, limit: { type: "number", description: "取得件数(デフォルト: 10)", }, pathFilter: { type: "string", description: 'パスのフィルター(例: "/blog" で /blog 配下のみを取得)', }, }, required: ["period"], }, }, { name: "get_traffic_sources", description: "流入元(チャネル、ソース、メディアなど)の分析結果を取得します。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["7days", "28days", "30days", "90days"], description: "集計期間", }, groupBy: { type: "string", enum: ["channel", "source", "medium", "sourceMedium", "campaign"], description: "グループ化の方法", }, }, required: ["period", "groupBy"], }, }, { name: "get_device_breakdown", description: "デバイス別(PC/モバイル/タブレット)のアクセス内訳を取得します。OS別、ブラウザ別の情報も含まれます。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["7days", "28days", "30days"], description: "集計期間", }, }, required: ["period"], }, }, { name: "get_geo_breakdown", description: "地域別(国または市区町村)のアクセス分析結果を取得します。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["7days", "28days", "30days"], description: "集計期間", }, level: { type: "string", enum: ["country", "city"], description: "地域レベル", }, limit: { type: "number", description: "取得件数(デフォルト: 10)", }, }, required: ["period", "level"], }, }, { 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"], }, },