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";
Behavior2/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. While it indicates this is a data retrieval operation ('取得します'), it doesn't disclose important behavioral traits like whether this requires authentication, has rate limits, returns paginated results, or what format the data comes in. For a data retrieval tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

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

Conciseness4/5

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

The description is appropriately concise with two sentences. The first sentence states the core purpose, and the second provides use case context. There's no wasted verbiage or unnecessary repetition. While it could be slightly more specific, every sentence earns its place by adding value.

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?

For a data retrieval tool with 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what 'trend data' specifically includes, how results are structured, whether there are limitations on date ranges or metrics, or how this differs from similar sibling tools. The description provides basic purpose but lacks the contextual richness needed for confident tool selection and invocation.

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 100%, so the schema already documents all 4 parameters thoroughly. The description adds no parameter-specific information beyond what's in the schema. It mentions '日別のトレンドデータ' (daily trend data) which aligns with the date parameters, but provides no additional semantic context about parameter usage, relationships, or constraints. Baseline 3 is appropriate when 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: '日別のトレンドデータを取得します' (retrieves daily trend data). It specifies the resource (trend data) and timeframe (daily), and mentions potential use cases (graph creation, trend analysis). However, it doesn't explicitly differentiate from sibling tools like 'get_hourly_traffic' or 'get_traffic_summary' which might also retrieve trend-related data.

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 alternatives. It mentions general use cases ('グラフ作成やトレンド分析に使用できます' - can be used for graph creation and trend analysis), but doesn't specify scenarios where this tool is preferred over siblings like 'compare_periods' for trend analysis or 'run_report' for custom data retrieval. There's no explicit when/when-not guidance or alternative tool references.

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