Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_hourly_traffic

Analyze hourly traffic patterns from Google Analytics 4 data to optimize content publishing and campaign timing decisions.

Instructions

時間帯別のアクセス状況を分析します。投稿やキャンペーンのタイミング最適化に活用できます。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間

Implementation Reference

  • The core handler function that executes the get_hourly_traffic tool logic. It queries GA4 for hourly data, computes daily averages for users and page views, identifies peak and quiet hours based on thresholds, and returns structured output.
    export async function getHourlyTraffic(
      input: GetHourlyTrafficInput
    ): Promise<GetHourlyTrafficOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
      const dayCount = getDayCount(dateRange);
    
      const response = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "hour" }],
        metrics: [{ name: "totalUsers" }, { name: "screenPageViews" }],
        orderBys: [{ dimension: { dimensionName: "hour" }, desc: false }],
        limit: 24,
      });
    
      // 時間ごとのデータを初期化(0-23時)
      const hourlyMap = new Map<number, { users: number; pageViews: number }>();
      for (let i = 0; i < 24; i++) {
        hourlyMap.set(i, { users: 0, pageViews: 0 });
      }
    
      // レスポンスからデータを収集
      for (const row of response.rows || []) {
        const hour = parseInt(row.dimensionValues?.[0]?.value || "0", 10);
        const users = row.metricValues?.[0]?.value
          ? parseFloat(row.metricValues[0].value)
          : 0;
        const pageViews = row.metricValues?.[1]?.value
          ? parseFloat(row.metricValues[1].value)
          : 0;
    
        hourlyMap.set(hour, { users, pageViews });
      }
    
      // 平均を計算してHourlyData配列を作成
      const hourlyData: HourlyData[] = [];
      let maxUsers = 0;
      let minUsers = Infinity;
    
      for (let hour = 0; hour < 24; hour++) {
        const data = hourlyMap.get(hour)!;
        const avgUsers = roundToDecimal(data.users / dayCount);
        const avgPageViews = roundToDecimal(data.pageViews / dayCount);
    
        if (avgUsers > maxUsers) maxUsers = avgUsers;
        if (avgUsers < minUsers) minUsers = avgUsers;
    
        hourlyData.push({
          hour,
          avgUsers,
          avgPageViews,
          peakIndicator: false, // 後で設定
        });
      }
    
      // ピーク判定の閾値(平均値の1.5倍以上)
      const avgAllHours =
        hourlyData.reduce((sum, h) => sum + h.avgUsers, 0) / 24;
      const peakThreshold = avgAllHours * 1.5;
      const quietThreshold = avgAllHours * 0.5;
    
      // ピーク時間帯と閑散時間帯を特定
      const peakHours: number[] = [];
      const quietHours: number[] = [];
    
      for (const data of hourlyData) {
        if (data.avgUsers >= peakThreshold) {
          data.peakIndicator = true;
          peakHours.push(data.hour);
        }
        if (data.avgUsers <= quietThreshold) {
          quietHours.push(data.hour);
        }
      }
    
      return {
        hourlyData,
        peakHours,
        quietHours,
      };
    }
  • TypeScript interfaces defining the input (GetHourlyTrafficInput), data structure (HourlyData), and output (GetHourlyTrafficOutput) for the get_hourly_traffic tool.
    // get_hourly_traffic
    export interface GetHourlyTrafficInput extends PropertyId {
      period: ShortPeriod;
    }
    
    export interface HourlyData {
      hour: number;
      avgUsers: number;
      avgPageViews: number;
      peakIndicator: boolean;
    }
    
    export interface GetHourlyTrafficOutput {
      hourlyData: HourlyData[];
      peakHours: number[];
      quietHours: number[];
    }
  • src/server.ts:463-479 (registration)
    MCP tool registration in the tools array, defining name, description, and input schema for get_hourly_traffic.
    {
      name: "get_hourly_traffic",
      description:
        "時間帯別のアクセス状況を分析します。投稿やキャンペーンのタイミング最適化に活用できます。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          period: {
            type: "string",
            enum: ["7days", "28days", "30days"],
            description: "集計期間",
          },
        },
        required: ["period"],
      },
    },
  • src/server.ts:718-722 (registration)
    Dispatch handler in the switch statement that calls the getHourlyTraffic function when the tool is invoked.
    case "get_hourly_traffic":
      return await getHourlyTraffic({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
      });
  • Re-export of the getHourlyTraffic handler from its module for use in server.ts.
    export { getHourlyTraffic } from "./getHourlyTraffic.js";
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the tool's purpose and potential use case but doesn't describe what the tool actually returns (e.g., hourly traffic counts, percentages), whether it requires specific permissions, rate limits, or any side effects. For a read operation with zero annotation coverage, this leaves significant gaps in understanding the tool's behavior.

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 concise (two sentences) and front-loaded with the core purpose. Both sentences add value: the first states what the tool does, and the second suggests a use case. There's no wasted text, though it could be slightly more structured for clarity.

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 has no annotations, no output schema, and the description lacks behavioral details, it's incomplete for effective use. The agent won't know what format the hourly traffic data returns (e.g., JSON structure, metrics included) or any operational constraints. For a data analysis tool with 2 parameters, this leaves too much unspecified.

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%, with both parameters (propertyId and period) well-documented in the schema. The description doesn't add any parameter-specific information beyond what's already in the schema (e.g., it doesn't explain format of propertyId or clarify period enum values). Baseline 3 is appropriate when the schema handles parameter documentation effectively.

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: 'analyzes hourly access patterns' (時間帯別のアクセス状況を分析します) and mentions it can be used for 'optimizing posting or campaign timing' (投稿やキャンペーンのタイミング最適化に活用できます). It specifies the resource (access patterns) and verb (analyzes), but doesn't explicitly differentiate from sibling tools like get_daily_trend or get_traffic_summary beyond the hourly focus.

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

Usage Guidelines3/5

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

The description implies usage context ('for optimizing posting or campaign timing'), suggesting when this analysis might be useful. However, it doesn't provide explicit guidance on when to use this tool versus alternatives like get_daily_trend or get_traffic_sources, nor does it mention any prerequisites or exclusions.

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