Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_new_vs_returning

Compare new and returning user sessions and engagement time in Google Analytics 4 to analyze audience behavior patterns and retention.

Instructions

新規ユーザーとリピーターの比較分析を行います。それぞれのセッション数や滞在時間を確認できます。

Input Schema

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

Implementation Reference

  • The core handler function that fetches GA4 report data for new vs returning users using dimensions 'newVsReturning' and specific metrics, processes rows to compute counts, percentages, sessions, avg duration, and bounce rates for new and returning users.
    export async function getNewVsReturning(
      input: GetNewVsReturningInput
    ): Promise<GetNewVsReturningOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
    
      const response = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "newVsReturning" }],
        metrics: [
          { name: "totalUsers" },
          { name: "sessions" },
          { name: "averageSessionDuration" },
          { name: "bounceRate" },
        ],
      });
    
      // 合計ユーザー数を取得
      const totalUsers =
        response.totals?.[0]?.metricValues?.[0]?.value
          ? parseFloat(response.totals[0].metricValues[0].value)
          : 0;
    
      // デフォルト値
      const defaultUserData: UserTypeData = {
        count: 0,
        percentage: "0%",
        sessions: 0,
        avgSessionDuration: "0秒",
        bounceRate: "0%",
      };
    
      let newUsers: UserTypeData = { ...defaultUserData };
      let returningUsers: UserTypeData = { ...defaultUserData };
    
      for (const row of response.rows || []) {
        const userType = row.dimensionValues?.[0]?.value || "";
        const metricValues = row.metricValues || [];
    
        const getValue = (index: number): number => {
          const value = metricValues[index]?.value;
          return value ? parseFloat(value) : 0;
        };
    
        const count = Math.round(getValue(0));
        const userData: UserTypeData = {
          count,
          percentage: calculatePercentage(count, totalUsers),
          sessions: Math.round(getValue(1)),
          avgSessionDuration: formatDuration(getValue(2)),
          bounceRate: formatPercentageFromDecimal(getValue(3)),
        };
    
        if (userType === "new") {
          newUsers = userData;
        } else if (userType === "returning") {
          returningUsers = userData;
        }
      }
    
      return {
        newUsers,
        returningUsers,
      };
    }
  • src/server.ts:506-521 (registration)
    Tool registration in the MCP server, defining the tool name, description, and input schema (propertyId optional, period required).
    {
      name: "get_new_vs_returning",
      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:732-736 (registration)
    The switch case in handleToolCall that invokes the getNewVsReturning handler with parsed arguments.
    case "get_new_vs_returning":
      return await getNewVsReturning({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
      });
  • TypeScript interfaces defining the input (extends PropertyId with period), UserTypeData structure, and output (newUsers and returningUsers).
    export interface GetNewVsReturningInput extends PropertyId {
      period: ShortPeriod;
    }
    
    export interface UserTypeData {
      count: number;
      percentage: string;
      sessions: number;
      avgSessionDuration: string;
      bounceRate: string;
    }
    
    export interface GetNewVsReturningOutput {
      newUsers: UserTypeData;
      returningUsers: UserTypeData;
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions what the tool does but doesn't describe key behavioral traits such as whether it requires authentication, has rate limits, returns paginated results, or what format the output takes. For an analytics tool with no annotation coverage, this leaves significant gaps in understanding how it operates.

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 sentence in Japanese that clearly states the tool's purpose and available metrics. It's appropriately sized and front-loaded with the main function, though it could be slightly more structured by separating purpose from capabilities for better readability.

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 complexity of user behavior analysis, no annotations, and no output schema, the description is incomplete. It doesn't cover behavioral aspects like authentication needs, rate limits, or output format, and it lacks usage guidelines. For a tool with two parameters and analytical output, more context is needed to ensure proper agent 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 both parameters (propertyId and period) with descriptions and enum values for period. The description adds no additional meaning beyond what the schema provides, such as explaining how these parameters affect the analysis or providing usage examples. Baseline 3 is appropriate when the 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 performs 'comparative analysis of new vs returning users' and specifies what metrics can be checked (session counts and dwell time). This provides a specific verb ('compare analysis') and resource ('new vs returning users'), though it doesn't explicitly differentiate from sibling tools like 'get_engagement_metrics' or 'get_user_journey' that might overlap in user behavior analysis.

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 doesn't mention any prerequisites, exclusions, or comparisons to sibling tools such as 'get_engagement_metrics' or 'get_user_journey', which might offer similar or complementary user behavior insights. Usage is implied only by the tool's name and description.

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