Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

run_report

Retrieve Google Analytics 4 data by specifying custom dimensions and metrics for flexible reporting and analysis.

Instructions

GA4の汎用レポートを実行します。任意のディメンションとメトリクスを指定して柔軟にデータを取得できます。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID(省略時は環境変数GA4_PROPERTY_IDを使用)
startDateYes開始日(YYYY-MM-DD形式、または "today", "yesterday", "7daysAgo" など)
endDateYes終了日(YYYY-MM-DD形式、または "today", "yesterday" など)
dimensionsYesディメンション名の配列(例: ["pagePath", "deviceCategory"])
metricsYesメトリクス名の配列(例: ["screenPageViews", "sessions"])
dimensionFilterNoディメンションフィルター(オプション)
orderByNoソート設定(オプション)
limitNo取得件数(デフォルト: 10、最大: 100000)

Implementation Reference

  • The core handler function `runReport` that processes input parameters like dates, dimensions, metrics, filters, and sorting; constructs the GA4 API request options; executes the report via `executeReport`; parses and formats the response rows, totals, and metadata into structured ReportRow objects.
    export async function runReport(input: RunReportInput): Promise<RunReportOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
    
      // 日付を解決
      const startDate = resolveDate(input.startDate);
      const endDate = resolveDate(input.endDate);
    
      // リクエストオプションを構築
      const options: RunReportOptions = {
        property,
        dateRanges: [{ startDate, endDate }],
        dimensions: input.dimensions.map((name) => ({ name })),
        metrics: input.metrics.map((name) => ({ name })),
        limit: input.limit || 10,
      };
    
      // フィルターの設定
      if (input.dimensionFilter) {
        options.dimensionFilter = {
          filter: {
            fieldName: input.dimensionFilter.fieldName,
            stringFilter: {
              matchType: input.dimensionFilter.stringFilter.matchType,
              value: input.dimensionFilter.stringFilter.value,
              caseSensitive: input.dimensionFilter.stringFilter.caseSensitive,
            },
          },
        };
      }
    
      // ソートの設定
      if (input.orderBy) {
        options.orderBys = [];
        if (input.orderBy.metric) {
          options.orderBys.push({
            metric: { metricName: input.orderBy.metric },
            desc: input.orderBy.desc ?? true,
          });
        } else if (input.orderBy.dimension) {
          options.orderBys.push({
            dimension: { dimensionName: input.orderBy.dimension },
            desc: input.orderBy.desc ?? false,
          });
        }
      }
    
      // レポート実行
      const response = await executeReport(options);
    
      // 結果を整形
      const rows: ReportRow[] = [];
      const dimensionHeaders = response.dimensionHeaders || [];
      const metricHeaders = response.metricHeaders || [];
    
      for (const row of response.rows || []) {
        const dimensions: Record<string, string> = {};
        const metrics: Record<string, number | string> = {};
    
        // ディメンション値を取得
        (row.dimensionValues || []).forEach((value, index) => {
          const header = dimensionHeaders[index];
          if (header?.name) {
            dimensions[header.name] = value.value || "";
          }
        });
    
        // メトリクス値を取得
        (row.metricValues || []).forEach((value, index) => {
          const header = metricHeaders[index];
          if (header?.name) {
            const rawValue = value.value || "0";
            // 数値に変換可能なら数値に、そうでなければ文字列のまま
            const numValue = parseFloat(rawValue);
            metrics[header.name] = isNaN(numValue) ? rawValue : numValue;
          }
        });
    
        rows.push({ dimensions, metrics });
      }
    
      // 合計値の取得
      let totals: Record<string, number | string> | undefined;
      if (response.totals && response.totals.length > 0) {
        totals = {};
        const totalRow = response.totals[0];
        (totalRow.metricValues || []).forEach((value, index) => {
          const header = metricHeaders[index];
          if (header?.name) {
            const rawValue = value.value || "0";
            const numValue = parseFloat(rawValue);
            totals![header.name] = isNaN(numValue) ? rawValue : numValue;
          }
        });
      }
    
      return {
        rows,
        rowCount: rows.length,
        totals,
        metadata: {
          dataLossFromOtherRow: response.metadata?.dataLossFromOtherRow || false,
        },
      };
    }
  • src/server.ts:87-161 (registration)
    MCP tool registration for 'run_report', including name, description, and detailed inputSchema defining parameters like propertyId, dates, dimensions, metrics, filters, ordering, and limit.
    {
      name: "run_report",
      description:
        "GA4の汎用レポートを実行します。任意のディメンションとメトリクスを指定して柔軟にデータを取得できます。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: {
            type: "string",
            description:
              "GA4プロパティID(省略時は環境変数GA4_PROPERTY_IDを使用)",
          },
          startDate: {
            type: "string",
            description:
              '開始日(YYYY-MM-DD形式、または "today", "yesterday", "7daysAgo" など)',
          },
          endDate: {
            type: "string",
            description:
              '終了日(YYYY-MM-DD形式、または "today", "yesterday" など)',
          },
          dimensions: {
            type: "array",
            items: { type: "string" },
            description:
              'ディメンション名の配列(例: ["pagePath", "deviceCategory"])',
          },
          metrics: {
            type: "array",
            items: { type: "string" },
            description:
              'メトリクス名の配列(例: ["screenPageViews", "sessions"])',
          },
          dimensionFilter: {
            type: "object",
            description: "ディメンションフィルター(オプション)",
            properties: {
              fieldName: { type: "string" },
              stringFilter: {
                type: "object",
                properties: {
                  matchType: {
                    type: "string",
                    enum: [
                      "EXACT",
                      "BEGINS_WITH",
                      "ENDS_WITH",
                      "CONTAINS",
                      "REGEXP",
                    ],
                  },
                  value: { type: "string" },
                  caseSensitive: { type: "boolean" },
                },
              },
            },
          },
          orderBy: {
            type: "object",
            description: "ソート設定(オプション)",
            properties: {
              metric: { type: "string" },
              dimension: { type: "string" },
              desc: { type: "boolean" },
            },
          },
          limit: {
            type: "number",
            description: "取得件数(デフォルト: 10、最大: 100000)",
          },
        },
        required: ["startDate", "endDate", "dimensions", "metrics"],
      },
    },
  • src/server.ts:579-606 (registration)
    The switch case in handleToolCall that dispatches 'run_report' calls to the runReport handler function, casting and passing arguments appropriately.
    case "run_report":
      return await runReport({
        propertyId: args.propertyId as string | undefined,
        startDate: args.startDate as string,
        endDate: args.endDate as string,
        dimensions: args.dimensions as string[],
        metrics: args.metrics as string[],
        dimensionFilter: args.dimensionFilter as
          | {
              fieldName: string;
              stringFilter: {
                matchType:
                  | "EXACT"
                  | "BEGINS_WITH"
                  | "CONTAINS"
                  | "ENDS_WITH"
                  | "REGEXP";
                value: string;
                caseSensitive?: boolean;
              };
            }
          | undefined,
        orderBy: args.orderBy as
          | { metric?: string; dimension?: string; desc?: boolean }
          | undefined,
        limit: args.limit as number | undefined,
      });
  • TypeScript type definitions for RunReportInput (parameters), RunReportOutput (return type), and supporting types DimensionFilter, OrderBy, ReportRow used by the runReport handler.
    // run_report
    export interface DimensionFilter {
      fieldName: string;
      stringFilter: {
        matchType: "EXACT" | "BEGINS_WITH" | "CONTAINS" | "ENDS_WITH" | "REGEXP";
        value: string;
        caseSensitive?: boolean;
      };
    }
    
    export interface OrderBy {
      metric?: string;
      dimension?: string;
      desc?: boolean;
    }
    
    export interface RunReportInput extends PropertyId {
      startDate: string;
      endDate: string;
      dimensions: string[];
      metrics: string[];
      dimensionFilter?: DimensionFilter;
      orderBy?: OrderBy;
      limit?: number;
    }
    
    export interface ReportRow {
      dimensions: Record<string, string>;
      metrics: Record<string, number | string>;
    }
    
    export interface RunReportOutput {
      rows: ReportRow[];
      rowCount: number;
      totals?: Record<string, number | string>;
      metadata?: {
        dataLossFromOtherRow: boolean;
      };
    }

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