Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_daily_trend

Retrieve daily trend data from Google Analytics 4 for chart creation and trend analysis. Specify date ranges and metrics to analyze user behavior patterns over time.

Instructions

日別のトレンドデータを取得します。グラフ作成やトレンド分析に使用できます。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
startDateYes開始日(YYYY-MM-DD形式、または "30daysAgo" など)
endDateYes終了日(YYYY-MM-DD形式、または "today" など)
metricsNo取得するメトリクス(デフォルト: ["screenPageViews", "activeUsers"])

Implementation Reference

  • The main asynchronous handler function that implements the get_daily_trend tool. It queries GA4 for daily data using specified metrics over a date range, processes the response to create daily trend points, computes summary statistics (total, average, max, min), and returns structured output.
    export async function getDailyTrend(
      input: GetDailyTrendInput
    ): Promise<GetDailyTrendOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
    
      const startDate = resolveDate(input.startDate);
      const endDate = resolveDate(input.endDate);
    
      // デフォルトのメトリクス
      const metrics = input.metrics || ["screenPageViews", "activeUsers"];
    
      const response = await executeReport({
        property,
        dateRanges: [{ startDate, endDate }],
        dimensions: [{ name: "date" }],
        metrics: metrics.map((name) => ({ name })),
        orderBys: [{ dimension: { dimensionName: "date" }, desc: false }],
        limit: 366, // 最大1年分
      });
    
      const trend: DailyData[] = [];
      const metricSums: Record<string, number> = {};
      let maxRecord: DailyData | null = null;
      let minRecord: DailyData | null = null;
      let maxValue = -Infinity;
      let minValue = Infinity;
    
      // メトリクスの合計を初期化
      for (const metric of metrics) {
        metricSums[metric] = 0;
      }
    
      // メトリクスヘッダー
      const metricHeaders = response.metricHeaders || [];
    
      for (const row of response.rows || []) {
        const dateStr = row.dimensionValues?.[0]?.value || "";
        // YYYYMMDD を YYYY-MM-DD に変換
        const formattedDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
    
        const dataPoint: DailyData = { date: formattedDate };
        let primaryValue = 0;
    
        (row.metricValues || []).forEach((value, index) => {
          const metricName = metricHeaders[index]?.name || `metric${index}`;
          const numValue = value.value ? parseFloat(value.value) : 0;
          dataPoint[metricName] = numValue;
          metricSums[metricName] = (metricSums[metricName] || 0) + numValue;
    
          // 最初のメトリクスを使って最大/最小を判定
          if (index === 0) {
            primaryValue = numValue;
          }
        });
    
        trend.push(dataPoint);
    
        // 最大値の更新
        if (primaryValue > maxValue) {
          maxValue = primaryValue;
          maxRecord = dataPoint;
        }
    
        // 最小値の更新
        if (primaryValue < minValue) {
          minValue = primaryValue;
          minRecord = dataPoint;
        }
      }
    
      // サマリーの計算
      const count = trend.length || 1;
      const total: Record<string, number> = {};
      const average: Record<string, number> = {};
    
      for (const metric of metrics) {
        total[metric] = Math.round(metricSums[metric] || 0);
        average[metric] = roundToDecimal((metricSums[metric] || 0) / count);
      }
    
      // 最大/最小レコードの整形
      const formatSummaryRecord = (
        record: DailyData | null
      ): { date: string } & Record<string, number> => {
        if (!record) {
          const result: { date: string } & Record<string, number> = { date: "" };
          for (const metric of metrics) {
            result[metric] = 0;
          }
          return result;
        }
        const result: { date: string } & Record<string, number> = {
          date: record.date as string,
        };
        for (const metric of metrics) {
          result[metric] = typeof record[metric] === "number" ? record[metric] as number : 0;
        }
        return result;
      };
    
      return {
        trend,
        summary: {
          total,
          average,
          max: formatSummaryRecord(maxRecord),
          min: formatSummaryRecord(minRecord),
        },
      };
    }
  • TypeScript interfaces defining the input (GetDailyTrendInput) and output (GetDailyTrendOutput) schemas for the get_daily_trend tool, including supporting DailyData type.
    // get_daily_trend
    export interface GetDailyTrendInput extends PropertyId {
      startDate: string;
      endDate: string;
      metrics?: string[];
    }
    
    export interface DailyData {
      date: string;
      [metricName: string]: number | string;
    }
    
    export interface GetDailyTrendOutput {
      trend: DailyData[];
      summary: {
        total: Record<string, number>;
        average: Record<string, number>;
        max: { date: string } & Record<string, number>;
        min: { date: string } & Record<string, number>;
      };
    }
  • src/server.ts:480-504 (registration)
    MCP tool registration entry in the tools array, defining the name, description, and input schema for 'get_daily_trend'.
    {
      name: "get_daily_trend",
      description:
        "日別のトレンドデータを取得します。グラフ作成やトレンド分析に使用できます。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          startDate: {
            type: "string",
            description: '開始日(YYYY-MM-DD形式、または "30daysAgo" など)',
          },
          endDate: {
            type: "string",
            description: '終了日(YYYY-MM-DD形式、または "today" など)',
          },
          metrics: {
            type: "array",
            items: { type: "string" },
            description:
              '取得するメトリクス(デフォルト: ["screenPageViews", "activeUsers"])',
          },
        },
        required: ["startDate", "endDate"],
      },
  • src/server.ts:724-730 (registration)
    Dispatch handler in the switch statement within handleToolCall that invokes the getDailyTrend function for the 'get_daily_trend' tool.
    case "get_daily_trend":
      return await getDailyTrend({
        propertyId: args.propertyId as string | undefined,
        startDate: args.startDate as string,
        endDate: args.endDate as string,
        metrics: args.metrics as string[] | undefined,
      });
  • Re-export of the getDailyTrend handler from its module for use in server imports.
    export { getDailyTrend } from "./getDailyTrend.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