Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_user_journey

Analyze pages viewed before or after a specific page to understand user navigation patterns in Google Analytics 4.

Instructions

特定ページの前後に閲覧されるページを分析します。ユーザーの回遊パターンの把握に便利です。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間
pagePathYes分析対象のページパス(例: "/product/123")
directionYesnext: 次に見たページ、previous: 前に見たページ
limitNo取得件数(デフォルト: 10)

Implementation Reference

  • The primary handler function implementing the get_user_journey tool. It analyzes pages viewed in the same session as the target page using GA4 reports.
    export async function getUserJourney(
      input: GetUserJourneyInput
    ): Promise<GetUserJourneyOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
      const limit = input.limit || 10;
    
      // GA4では直接的なページ遷移情報が取得しにくいため、
      // 対象ページと同じセッションで閲覧されたページを分析
      // より正確な分析にはBigQuery Export が必要
    
      // 対象ページにアクセスしたセッション数を取得
      const targetResponse = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "pagePath" }],
        metrics: [{ name: "sessions" }],
        dimensionFilter: {
          filter: {
            fieldName: "pagePath",
            stringFilter: {
              matchType: "EXACT",
              value: input.pagePath,
            },
          },
        },
      });
    
      const targetSessions =
        targetResponse.totals?.[0]?.metricValues?.[0]?.value
          ? Math.round(parseFloat(targetResponse.totals[0].metricValues[0].value))
          : 0;
    
      // 全ページのアクセス状況を取得
      const allPagesResponse = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "pagePath" }],
        metrics: [{ name: "sessions" }],
        orderBys: [{ metric: { metricName: "sessions" }, desc: true }],
        limit: limit + 1, // 対象ページ自体を除外するため+1
      });
    
      const relatedPages: RelatedPage[] = [];
    
      for (const row of allPagesResponse.rows || []) {
        const pagePath = row.dimensionValues?.[0]?.value || "";
        
        // 対象ページ自体は除外
        if (pagePath === input.pagePath) continue;
        
        const count = row.metricValues?.[0]?.value
          ? Math.round(parseFloat(row.metricValues[0].value))
          : 0;
    
        relatedPages.push({
          pagePath,
          count,
          percentage: calculatePercentage(count, targetSessions),
        });
    
        if (relatedPages.length >= limit) break;
      }
    
      return {
        targetPage: input.pagePath,
        direction: input.direction,
        relatedPages,
      };
    }
  • TypeScript interfaces defining the input (GetUserJourneyInput), supporting types (RelatedPage), and output (GetUserJourneyOutput) for the tool.
    // get_user_journey
    export interface GetUserJourneyInput extends PropertyId {
      period: ShortPeriod;
      pagePath: string;
      direction: "next" | "previous";
      limit?: number;
    }
    
    export interface RelatedPage {
      pagePath: string;
      count: number;
      percentage: string;
    }
    
    export interface GetUserJourneyOutput {
      targetPage: string;
      direction: "next" | "previous";
      relatedPages: RelatedPage[];
    }
  • src/server.ts:398-427 (registration)
    MCP tool registration defining the name, description, and input schema for get_user_journey.
    {
      name: "get_user_journey",
      description:
        "特定ページの前後に閲覧されるページを分析します。ユーザーの回遊パターンの把握に便利です。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          period: {
            type: "string",
            enum: ["7days", "28days", "30days"],
            description: "集計期間",
          },
          pagePath: {
            type: "string",
            description: '分析対象のページパス(例: "/product/123")',
          },
          direction: {
            type: "string",
            enum: ["next", "previous"],
            description: "next: 次に見たページ、previous: 前に見たページ",
          },
          limit: {
            type: "number",
            description: "取得件数(デフォルト: 10)",
          },
        },
        required: ["period", "pagePath", "direction"],
      },
    },
  • src/server.ts:702-709 (registration)
    Dispatch handler in the switch statement that calls the getUserJourney function when the tool is invoked.
    case "get_user_journey":
      return await getUserJourney({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
        pagePath: args.pagePath as string,
        direction: args.direction as "next" | "previous",
        limit: args.limit as number | undefined,
      });
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 analysis of pages before/after a target page but lacks details on output format (e.g., list of pages with counts), pagination (though limit parameter exists), rate limits, authentication needs, or data freshness. For a tool with 5 parameters and no annotations, this is a significant gap in behavioral context.

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 and front-loaded: the first sentence states the core purpose, and the second adds context. Both sentences earn their place by clarifying utility. However, it could be slightly more structured (e.g., explicitly mentioning parameters or output), but it avoids redundancy and waste.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 5 parameters, 100% schema coverage, no annotations, and no output schema, the description is minimally adequate. It covers the purpose and usage context but lacks details on behavioral traits (e.g., what the analysis returns, error handling) and doesn't compensate for the missing output schema. For a tool with moderate complexity, this leaves gaps in completeness.

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 parameters thoroughly (e.g., propertyId as GA4 property ID, period with enum values, pagePath with example). The description adds no additional parameter semantics beyond what the schema provides, such as explaining interactions between parameters (e.g., how direction affects results). 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: '特定ページの前後に閲覧されるページを分析します' (analyzes pages viewed before/after a specific page). It specifies the verb (analyzes) and resource (pages viewed around a target page), distinguishing it from siblings like get_top_pages or get_landing_pages. However, it doesn't explicitly differentiate from all siblings (e.g., get_exit_pages might overlap in analyzing page navigation).

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 provides implied usage context: 'ユーザーの回遊パターンの把握に便利です' (useful for understanding user navigation patterns). This suggests when to use it—for analyzing user flow patterns. However, it doesn't explicitly state when not to use it or name alternatives (e.g., compare_periods for temporal comparisons or get_conversion_funnel for conversion analysis), leaving some ambiguity.

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