Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_engagement_metrics

Retrieve engagement metrics like engagement rate and average engagement time from Google Analytics 4 to analyze user interaction patterns and behavior.

Instructions

エンゲージメント関連の詳細指標(エンゲージメント率、平均エンゲージメント時間など)を取得します。

Input Schema

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

Implementation Reference

  • The core async handler function that executes the tool logic: fetches GA4 report data for engagement metrics like engagementRate, userEngagementDuration, etc., computes derived metrics, and formats the output.
    export async function getEngagementMetrics(
      input: GetEngagementMetricsInput
    ): Promise<GetEngagementMetricsOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
    
      const response = await executeReport({
        property,
        dateRanges: [dateRange],
        metrics: [
          { name: "engagementRate" },
          { name: "userEngagementDuration" },
          { name: "engagedSessions" },
          { name: "totalUsers" },
          { name: "eventCount" },
          { name: "sessions" },
        ],
      });
    
      const metricValues = response.totals?.[0]?.metricValues || [];
      const getValue = (index: number): number => {
        const value = metricValues[index]?.value;
        return value ? parseFloat(value) : 0;
      };
    
      const engagementRate = getValue(0);
      const userEngagementDuration = getValue(1);
      const engagedSessions = getValue(2);
      const totalUsers = getValue(3);
      const eventCount = getValue(4);
      const sessions = getValue(5);
    
      // エンゲージセッション/ユーザー
      const engagedSessionsPerUser =
        totalUsers > 0 ? roundToDecimal(engagedSessions / totalUsers) : 0;
    
      // イベント/セッション
      const eventsPerSession =
        sessions > 0 ? roundToDecimal(eventCount / sessions) : 0;
    
      // 平均エンゲージメント時間
      const avgEngagementTime =
        totalUsers > 0
          ? formatDuration(userEngagementDuration / totalUsers)
          : "0秒";
    
      return {
        engagementRate: formatPercentageFromDecimal(engagementRate),
        avgEngagementTime,
        engagedSessionsPerUser,
        eventsPerSession,
        // スクロール深度は別途イベントベースの設定が必要なため省略
      };
    }
  • TypeScript interfaces defining the input (GetEngagementMetricsInput extending PropertyId with period) and output (GetEngagementMetricsOutput) schemas for the tool, including related ScrollDepth type.
    // get_engagement_metrics
    export interface GetEngagementMetricsInput extends PropertyId {
      period: ShortPeriod;
    }
    
    export interface ScrollDepth {
      reached25: string;
      reached50: string;
      reached75: string;
      reached100: string;
    }
    
    export interface GetEngagementMetricsOutput {
      engagementRate: string;
      avgEngagementTime: string;
      engagedSessionsPerUser: number;
      eventsPerSession: number;
      scrollDepth?: ScrollDepth;
    }
  • src/server.ts:523-539 (registration)
    MCP tool registration entry in the tools array, defining name, description, and inputSchema for 'get_engagement_metrics'.
    {
      name: "get_engagement_metrics",
      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:738-742 (registration)
    Dispatch case in the handleToolCall switch statement that invokes the getEngagementMetrics handler with parsed arguments.
    case "get_engagement_metrics":
      return await getEngagementMetrics({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
      });
  • Re-export of the getEngagementMetrics handler from its implementation file, allowing import from the analytics index.
    export { getEngagementMetrics } from "./getEngagementMetrics.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 read operation ('取得します' - get), it doesn't mention authentication requirements, rate limits, pagination, data freshness, or what specific metrics beyond the examples are included. For a metrics retrieval tool with no annotation coverage, this leaves significant behavioral gaps.

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 a single, efficient Japanese sentence that clearly states the tool's purpose. It's appropriately concise without being under-specified, though it could potentially be more structured with separate sentences for purpose and scope.

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 this is a metrics retrieval tool with no annotations and no output schema, the description is incomplete. It doesn't explain what format the metrics are returned in, what specific metrics beyond the examples are available, whether there are limitations on data availability, or how the metrics are calculated. For a tool that presumably returns complex engagement data, more context is needed.

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 both parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema. It mentions 'engagement metrics' generally but doesn't explain how parameters affect which metrics are returned or their calculation. 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: 'エンゲージメント関連の詳細指標(エンゲージメント率、平均エンゲージメント時間など)を取得します' translates to 'Get detailed engagement-related metrics (engagement rate, average engagement time, etc.)'. It specifies the verb ('取得します' - get) and resource (engagement metrics), but doesn't explicitly differentiate from sibling tools like 'get_traffic_summary' or 'get_user_journey' which might also involve engagement 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. With multiple sibling tools like 'get_traffic_summary', 'get_user_journey', and 'run_report' that might overlap with engagement metrics, there's no indication of when this specific engagement metrics tool is appropriate versus those other options.

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