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";

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