Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_search_terms

Analyzes site search keywords from Google Analytics 4 data to identify user search patterns and content needs within your website.

Instructions

サイト内検索キーワードを分析します。GA4でサイト内検索が設定されている場合のみ有効です。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間
limitNo取得件数(デフォルト: 20)

Implementation Reference

  • The main handler function that executes the get_search_terms tool logic. It queries GA4 using executeReport for searchTerm dimension filtered by view_search_results event, processes the data to compute search counts, unique searches, pageviews, and exit rates.
    export async function getSearchTerms(
      input: GetSearchTermsInput
    ): Promise<GetSearchTermsOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
      const limit = input.limit || 20;
    
      // サイト内検索キーワードを取得
      // GA4では searchTerm ディメンションを使用
      const response = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "searchTerm" }],
        metrics: [
          { name: "eventCount" },
          { name: "totalUsers" },
          { name: "screenPageViews" },
        ],
        orderBys: [{ metric: { metricName: "eventCount" }, desc: true }],
        limit,
        // view_search_results イベントでフィルター
        dimensionFilter: {
          filter: {
            fieldName: "eventName",
            stringFilter: {
              matchType: "EXACT",
              value: "view_search_results",
            },
          },
        },
      });
    
      // 合計イベント数を取得(検索離脱率計算用)
      const totalSearches =
        response.totals?.[0]?.metricValues?.[0]?.value
          ? parseFloat(response.totals[0].metricValues[0].value)
          : 0;
    
      const searchTerms: SearchTerm[] = [];
    
      for (const row of response.rows || []) {
        const term = row.dimensionValues?.[0]?.value || "";
        const metricValues = row.metricValues || [];
    
        const getValue = (index: number): number => {
          const value = metricValues[index]?.value;
          return value ? parseFloat(value) : 0;
        };
    
        const searchCount = Math.round(getValue(0));
        const uniqueSearches = Math.round(getValue(1));
        const resultsPageviews = Math.round(getValue(2));
    
        // 検索離脱率: 結果ページを見た後に離脱した割合(概算)
        // 正確な計算には追加のイベント分析が必要
        const searchExitRate = calculatePercentage(
          searchCount - resultsPageviews,
          searchCount
        );
    
        searchTerms.push({
          term,
          searchCount,
          uniqueSearches,
          resultsPageviews,
          searchExitRate,
        });
      }
    
      return { searchTerms };
    }
  • TypeScript interfaces defining the input schema (GetSearchTermsInput with period and optional limit), output schema (GetSearchTermsOutput), and SearchTerm structure for the tool.
    // get_search_terms
    export interface GetSearchTermsInput extends PropertyId {
      period: ShortPeriod;
      limit?: number;
    }
    
    export interface SearchTerm {
      term: string;
      searchCount: number;
      uniqueSearches: number;
      resultsPageviews: number;
      searchExitRate: string;
    }
    
    export interface GetSearchTermsOutput {
      searchTerms: SearchTerm[];
    }
  • src/server.ts:540-560 (registration)
    Tool registration in the tools array, defining the name 'get_search_terms', description, and inputSchema for MCP protocol compliance.
    {
      name: "get_search_terms",
      description:
        "サイト内検索キーワードを分析します。GA4でサイト内検索が設定されている場合のみ有効です。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          period: {
            type: "string",
            enum: ["7days", "28days", "30days"],
            description: "集計期間",
          },
          limit: {
            type: "number",
            description: "取得件数(デフォルト: 20)",
          },
        },
        required: ["period"],
      },
    },
  • src/server.ts:744-749 (registration)
    Dispatch handler in the switch statement that calls the getSearchTerms function with parsed arguments when the tool is invoked.
    case "get_search_terms":
      return await getSearchTerms({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
        limit: args.limit as number | undefined,
      });
  • Re-export of the getSearchTerms handler from its module for convenient import in server.ts.
    export { getSearchTerms } from "./getSearchTerms.js";
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 the prerequisite (GA4 site search configuration) but doesn't describe what the analysis entails (e.g., metrics returned, format, whether it's read-only or has side effects). For a tool with no annotations, this leaves significant gaps in understanding its behavior and safety profile.

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 with two sentences that directly address purpose and a key usage condition. It's front-loaded with the main function and avoids unnecessary details. However, it could be slightly more structured by explicitly separating purpose from prerequisites 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 no annotations and no output schema, the description is incomplete for a tool with three parameters and analytical functionality. It lacks details on what the analysis returns (e.g., metrics like search volume or trends), behavioral traits (e.g., read-only status, rate limits), and how it differs from siblings. This leaves the agent with insufficient context for effective use.

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 three parameters (propertyId, period, limit) with descriptions. The description doesn't add any parameter-specific details beyond what's in the schema, such as explaining how 'propertyId' relates to GA4 or what 'limit' affects in the analysis. Baseline 3 is appropriate when the schema handles parameter documentation.

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 site search keywords). It specifies the resource (site search keywords) and verb (analyzes), making the function clear. However, it doesn't explicitly differentiate from sibling tools like 'get_top_pages' or 'get_traffic_sources' that might also involve keyword analysis.

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 some usage context: 'GA4でサイト内検索が設定されている場合のみ有効です' (only valid when site search is configured in GA4). This implies a prerequisite condition but doesn't explicitly state when to use this tool versus alternatives like 'get_top_pages' for general page analysis or 'run_report' for custom reports. The guidance is implied rather than explicit.

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