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;
      };
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions flexibility but doesn't address important behavioral aspects: authentication requirements, rate limits, whether this is a read-only operation, expected response format, error handling, or performance characteristics. The description is insufficient for a tool with 8 parameters and complex nested objects.

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 key capability. There's no wasted language, though it could be slightly more informative given the tool's complexity. The structure is front-loaded with the core purpose stated first.

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?

For a complex tool with 8 parameters (including nested objects), no annotations, and no output schema, the description is inadequate. It doesn't explain what kind of data structure is returned, how results are formatted, pagination behavior, or error conditions. The description should provide more context about the tool's behavior and output given the absence of structured metadata.

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. The description adds minimal value beyond the schema, only mentioning that arbitrary dimensions and metrics can be specified. It doesn't provide additional context about parameter interactions, best practices, or common use patterns that would help an agent use the tool effectively.

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: 'GA4の汎用レポートを実行します' (runs GA4 general reports) with the ability to specify arbitrary dimensions and metrics for flexible data retrieval. It's specific about the resource (GA4 reports) and action (execute/run), though it doesn't explicitly differentiate from sibling tools like 'run_realtime_report' or other specialized GA4 tools.

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. With many sibling tools available (compare_periods, get_daily_trend, run_realtime_report, etc.), there's no indication of when this flexible report tool is preferable to more specialized ones, nor any mention of prerequisites or constraints.

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