Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_top_pages

Retrieve top-performing pages from Google Analytics 4 to analyze pageviews, session duration, and bounce rates for specific time periods.

Instructions

人気ページのランキングを取得します。PV数、滞在時間、直帰率などを確認できます。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間
limitNo取得件数(デフォルト: 10)
pathFilterNoパスのフィルター(例: "/blog" で /blog 配下のみを取得)

Implementation Reference

  • Main handler function implementing the get_top_pages tool logic. Fetches GA4 report data for top pages by page views, processes dimensions and metrics, formats results into TopPage objects ranked by page views.
    export async function getTopPages(
      input: GetTopPagesInput
    ): Promise<GetTopPagesOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
      const limit = input.limit || 10;
    
      const response = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "pagePath" }, { name: "pageTitle" }],
        metrics: [
          { name: "screenPageViews" },
          { name: "totalUsers" },
          { name: "averageSessionDuration" },
          { name: "bounceRate" },
        ],
        orderBys: [{ metric: { metricName: "screenPageViews" }, desc: true }],
        limit,
        ...(input.pathFilter && {
          dimensionFilter: {
            filter: {
              fieldName: "pagePath",
              stringFilter: {
                matchType: "BEGINS_WITH",
                value: input.pathFilter,
              },
            },
          },
        }),
      });
    
      const pages: TopPage[] = [];
      let rank = 1;
    
      for (const row of response.rows || []) {
        const dimensionValues = row.dimensionValues || [];
        const metricValues = row.metricValues || [];
    
        const getValue = (index: number): number => {
          const value = metricValues[index]?.value;
          return value ? parseFloat(value) : 0;
        };
    
        pages.push({
          rank: rank++,
          pagePath: dimensionValues[0]?.value || "",
          pageTitle: dimensionValues[1]?.value || "(タイトルなし)",
          pageViews: Math.round(getValue(0)),
          uniquePageViews: Math.round(getValue(1)),
          avgTimeOnPage: formatDuration(getValue(2)),
          bounceRate: formatPercentageFromDecimal(getValue(3)),
        });
      }
    
      return { pages };
    }
  • TypeScript interfaces defining input (GetTopPagesInput), output (GetTopPagesOutput), and data structure (TopPage) for the get_top_pages tool.
    export interface GetTopPagesInput extends PropertyId {
      period: ShortPeriod;
      limit?: number;
      pathFilter?: string;
    }
    
    export interface TopPage {
      rank: number;
      pagePath: string;
      pageTitle: string;
      pageViews: number;
      uniquePageViews: number;
      avgTimeOnPage: string;
      bounceRate: string;
    }
    
    export interface GetTopPagesOutput {
      pages: TopPage[];
    }
  • src/server.ts:221-246 (registration)
    MCP tool registration in the tools array, defining name, description, and inputSchema for get_top_pages.
    {
      name: "get_top_pages",
      description:
        "人気ページのランキングを取得します。PV数、滞在時間、直帰率などを確認できます。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          period: {
            type: "string",
            enum: ["today", "yesterday", "7days", "28days", "30days"],
            description: "集計期間",
          },
          limit: {
            type: "number",
            description: "取得件数(デフォルト: 10)",
          },
          pathFilter: {
            type: "string",
            description:
              'パスのフィルター(例: "/blog" で /blog 配下のみを取得)',
          },
        },
        required: ["period"],
      },
    },
  • src/server.ts:632-643 (registration)
    Dispatch handler in switch statement that calls the getTopPages function with parsed arguments.
    case "get_top_pages":
      return await getTopPages({
        propertyId: args.propertyId as string | undefined,
        period: args.period as
          | "today"
          | "yesterday"
          | "7days"
          | "28days"
          | "30days",
        limit: args.limit as number | undefined,
        pathFilter: args.pathFilter as string | undefined,
      });
  • Re-export of the getTopPages handler from its implementation file for convenient import in server.ts.
    export { getTopPages } from "./getTopPages.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 retrieves rankings and lists metrics, but doesn't describe behavioral traits such as whether it's a read-only operation, potential rate limits, authentication requirements, or what the output format looks like. For a data retrieval tool with zero annotation coverage, this is a significant gap in transparency.

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 that directly state the tool's purpose and capabilities. There's no unnecessary information or repetition. However, it could be slightly more front-loaded by immediately clarifying the ranking aspect, though the current structure is still efficient.

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 a ranking tool with 4 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain the ranking methodology (e.g., sorted by page views?), output format, or behavioral constraints. While it mentions metrics, it lacks details needed for the agent to fully understand how to use and interpret results from this tool.

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?

The schema description coverage is 100%, so all parameters are documented in the schema. The description doesn't add any parameter-specific information beyond what's in the schema (e.g., it doesn't explain how 'pathFilter' interacts with ranking or what 'limit' prioritizes). This meets the baseline of 3 since the schema does the heavy lifting, but the description doesn't compensate with additional semantic context.

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: '人気ページのランキングを取得します' (get ranking of popular pages). It specifies the verb ('取得します' - get/retrieve) and resource ('人気ページのランキング' - ranking of popular pages), making the purpose understandable. However, it doesn't explicitly distinguish this tool from similar siblings like 'get_landing_pages' or 'get_exit_pages', which might also retrieve page-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 what metrics can be checked ('PV数、滞在時間、直帰率など' - page views, dwell time, bounce rate, etc.), but doesn't specify use cases, prerequisites, or comparisons to sibling tools like 'get_landing_pages' or 'get_traffic_summary'. This leaves the agent with insufficient context for optimal tool selection.

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