Skip to main content
Glama
wonyoungseong

GA4 MCP Server

ga4_validate_gtm_params

Validate that event parameters sent from Google Tag Manager are properly collected in Google Analytics 4 by checking custom dimension registration and actual data collection status.

Instructions

GTM에서 보내는 이벤트 파라미터가 GA4에 제대로 수집되는지 검증합니다.

사용 방법

방법 1: GTM 이벤트 목록 직접 전달

gtmEvents 배열로 이벤트별 파라미터를 전달합니다.

방법 2: GTM Container Export JSON 전달

GTM에서 컨테이너를 Export한 JSON 파일 내용을 gtmExportJson으로 전달하면 자동으로 파싱합니다.

검증 항목

  1. 파라미터가 GA4 커스텀 디멘션으로 등록되어 있는지

  2. 등록된 파라미터가 실제로 데이터를 수집하고 있는지

  3. 미등록/미수집 파라미터에 대한 권장사항

API 호출 효율성

  • 기존: 이벤트 수 × 파라미터 수 = N×M 호출

  • 최적화: 1(메타데이터) + 고유 파라미터 수 = 1+P 호출

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdYesGA4 속성 ID (예: 419573056)
gtmEventsNoGTM에서 설정한 이벤트-파라미터 목록
gtmExportJsonNoGTM Container Export JSON (gtmEvents 대신 사용 가능)
startDateNo시작일 (기본: 7daysAgo)
endDateNo종료일 (기본: yesterday)

Implementation Reference

  • Main handler function that processes tool arguments, parses GTM export JSON (if provided), and calls the validation logic
    export async function handleGTMValidation(args: Record<string, unknown>): Promise<ToolResponse> {
      try {
        const propertyId = args.propertyId as string;
    
        let gtmEvents: GTMEventConfig[];
    
        if (args.gtmExportJson) {
          gtmEvents = parseGTMExport(args.gtmExportJson as Record<string, unknown>);
          if (gtmEvents.length === 0) {
            return createErrorResponse('GTM Export JSON에서 GA4 이벤트 태그를 찾을 수 없습니다', null);
          }
        } else if (args.gtmEvents) {
          gtmEvents = args.gtmEvents as GTMEventConfig[];
        } else {
          return createErrorResponse('gtmEvents 또는 gtmExportJson 중 하나는 필수입니다', null);
        }
    
        const dateRange = {
          startDate: (args.startDate as string) || '7daysAgo',
          endDate: (args.endDate as string) || 'yesterday'
        };
    
        const result = await validateGTMParameters(propertyId, gtmEvents, dateRange);
        return createSuccessResponse(result);
      } catch (error) {
        return createErrorResponse('GTM 파라미터 검증 실패', error);
      }
    }
  • Core validation logic that checks if GTM parameters are registered in GA4 custom dimensions and actually collecting data. Makes optimized API calls to fetch metadata and event data.
    export async function validateGTMParameters(
      propertyId: string,
      gtmEvents: GTMEventConfig[],
      dateRange: { startDate: string; endDate: string } = { startDate: '7daysAgo', endDate: 'yesterday' }
    ): Promise<ValidationSummary> {
      const dataClient = await getAnalyticsDataClient();
      const propertyResource = constructPropertyResourceName(propertyId);
      let apiCalls = 0;
    
      // 1단계: 커스텀 디멘션 메타데이터 조회
      log('Fetching custom dimensions metadata...');
      const metadataResponse = await dataClient.properties.getMetadata({
        name: `${propertyResource}/metadata`,
      });
      apiCalls++;
    
      const registeredDimensions = new Set<string>();
      metadataResponse.data.dimensions?.forEach(dim => {
        if (dim.customDefinition && dim.apiName) {
          // customEvent:param_name 형식에서 param_name 추출
          const match = dim.apiName.match(/^customEvent:(.+)$/);
          if (match) {
            registeredDimensions.add(match[1]);
          }
        }
      });
    
      log(`Found ${registeredDimensions.size} registered custom dimensions`);
    
      // 2단계: 모든 파라미터 추출 및 분류
      const allParameters = new Set<string>();
      gtmEvents.forEach(event => {
        event.parameters.forEach(param => allParameters.add(param));
      });
    
      const registeredParams = [...allParameters].filter(p => registeredDimensions.has(p));
      const notRegisteredParams = [...allParameters].filter(p => !registeredDimensions.has(p));
    
      // 3단계: 등록된 파라미터만 효율적으로 조회 (파라미터당 1번)
      const parameterData: Record<string, Record<string, number>> = {};
    
      log(`Querying ${registeredParams.length} parameters (optimized: ${registeredParams.length} API calls instead of ${gtmEvents.length * registeredParams.length})...`);
    
      for (const param of registeredParams) {
        try {
          const reportResponse = await dataClient.properties.runReport({
            property: propertyResource,
            requestBody: {
              dateRanges: [dateRange],
              dimensions: [
                { name: 'eventName' },
                { name: `customEvent:${param}` }
              ],
              metrics: [{ name: 'eventCount' }],
              limit: "500"
            }
          });
          apiCalls++;
    
          parameterData[param] = {};
          const responseData = reportResponse.data as { rows?: Array<{ dimensionValues?: Array<{ value?: string }>; metricValues?: Array<{ value?: string }> }> };
          const rows = responseData.rows || [];
          for (const row of rows) {
            const eventName = row.dimensionValues?.[0]?.value || '';
            const paramValue = row.dimensionValues?.[1]?.value || '';
            const count = parseInt(row.metricValues?.[0]?.value || '0');
    
            if (paramValue && paramValue !== '(not set)' && count > 0) {
              parameterData[param][eventName] = (parameterData[param][eventName] || 0) + count;
            }
          }
        } catch (error) {
          log(`Error querying parameter ${param}: ${error}`);
        }
      }
    
      // 4단계: 결과 집계
      const results: ValidationResult[] = [];
      let collected = 0;
      let notCollected = 0;
      let notRegistered = 0;
    
      for (const event of gtmEvents) {
        for (const param of event.parameters) {
          if (!registeredDimensions.has(param)) {
            results.push({
              eventName: event.eventName,
              parameter: param,
              status: 'not_registered',
              message: `파라미터 '${param}'이 GA4 커스텀 디멘션에 등록되지 않음`
            });
            notRegistered++;
          } else {
            const count = parameterData[param]?.[event.eventName] || 0;
            if (count > 0) {
              results.push({
                eventName: event.eventName,
                parameter: param,
                status: 'collected',
                count,
                message: `정상 수집 (${count.toLocaleString()}건)`
              });
              collected++;
            } else {
              results.push({
                eventName: event.eventName,
                parameter: param,
                status: 'not_collected',
                count: 0,
                message: `커스텀 디멘션 등록됨, 데이터 미수집`
              });
              notCollected++;
            }
          }
        }
      }
    
      // 5단계: 권장사항 생성
      const recommendations: string[] = [];
    
      if (notRegisteredParams.length > 0) {
        recommendations.push(
          `GA4 Admin에서 다음 파라미터를 커스텀 디멘션으로 등록하세요: ${notRegisteredParams.join(', ')}`
        );
      }
    
      const notCollectedByEvent: Record<string, string[]> = {};
      results
        .filter(r => r.status === 'not_collected')
        .forEach(r => {
          if (!notCollectedByEvent[r.eventName]) {
            notCollectedByEvent[r.eventName] = [];
          }
          notCollectedByEvent[r.eventName].push(r.parameter);
        });
    
      for (const [eventName, params] of Object.entries(notCollectedByEvent)) {
        recommendations.push(
          `이벤트 '${eventName}'에서 다음 파라미터가 수집되지 않음: ${params.join(', ')}`
        );
      }
    
      return {
        totalEvents: gtmEvents.length,
        totalParameters: allParameters.size,
        collected,
        notCollected,
        notRegistered,
        details: results,
        recommendations,
        apiCalls
      };
    }
  • Tool definition with name, description, and input schema for the ga4_validate_gtm_params MCP tool. Accepts propertyId, gtmEvents array, or gtmExportJson object.
    export const gtmValidatorToolDefinition = {
      name: 'ga4_validate_gtm_params',
      description: `GTM에서 보내는 이벤트 파라미터가 GA4에 제대로 수집되는지 검증합니다.
    
    ## 사용 방법
    
    ### 방법 1: GTM 이벤트 목록 직접 전달
    gtmEvents 배열로 이벤트별 파라미터를 전달합니다.
    
    ### 방법 2: GTM Container Export JSON 전달
    GTM에서 컨테이너를 Export한 JSON 파일 내용을 gtmExportJson으로 전달하면 자동으로 파싱합니다.
    
    ## 검증 항목
    1. 파라미터가 GA4 커스텀 디멘션으로 등록되어 있는지
    2. 등록된 파라미터가 실제로 데이터를 수집하고 있는지
    3. 미등록/미수집 파라미터에 대한 권장사항
    
    ## API 호출 효율성
    - 기존: 이벤트 수 × 파라미터 수 = N×M 호출
    - 최적화: 1(메타데이터) + 고유 파라미터 수 = 1+P 호출`,
      inputSchema: {
        type: 'object' as const,
        properties: {
          propertyId: {
            type: 'string',
            description: 'GA4 속성 ID (예: 419573056)'
          },
          gtmEvents: {
            type: 'array',
            description: 'GTM에서 설정한 이벤트-파라미터 목록',
            items: {
              type: 'object',
              properties: {
                eventName: { type: 'string' },
                parameters: { type: 'array', items: { type: 'string' } }
              },
              required: ['eventName', 'parameters']
            }
          },
          gtmExportJson: {
            type: 'object',
            description: 'GTM Container Export JSON (gtmEvents 대신 사용 가능)'
          },
          startDate: {
            type: 'string',
            description: '시작일 (기본: 7daysAgo)'
          },
          endDate: {
            type: 'string',
            description: '종료일 (기본: yesterday)'
          }
        },
        required: ['propertyId']
      }
    };
  • Tool definition registered in the registerAllTools function
    gtmValidatorToolDefinition,
  • Handler routing in the handleToolCall switch statement that routes ga4_validate_gtm_params to handleGTMValidation
    case "ga4_validate_gtm_params":
      return await handleGTMValidation(args);
Behavior4/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 effectively describes what the tool does (validation with specific checks), how it processes inputs (parsing JSON or using arrays), and performance characteristics (API call optimization from N×M to 1+P). However, it lacks details on error handling, rate limits, or authentication requirements, which are relevant for a tool interacting with GA4 APIs.

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 well-structured with clear sections (purpose, usage methods, validation items, API efficiency) and uses bullet points for readability. It is appropriately sized but could be more concise by integrating the API efficiency note into the purpose section, as it slightly elongates the text without adding critical usage guidance.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (5 parameters, nested objects, no output schema, no annotations), the description is mostly complete. It covers purpose, usage methods, validation scope, and performance optimizations. However, it lacks details on output format (e.g., what the validation results look like) and error scenarios, which are important for a tool with no output schema provided.

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. The description adds minimal semantic value beyond the schema: it clarifies that gtmEvents and gtmExportJson are alternative methods and mentions default values for startDate/endDate. However, it doesn't explain parameter interactions or provide examples beyond what's in the schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/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: '검증합니다' (validates) that event parameters sent from GTM are properly collected in GA4. It specifies the exact scope (GTM event parameters → GA4 collection validation) and distinguishes itself from sibling tools like ga4_run_report or ga4_custom_dimensions_metrics, which focus on reporting or metadata rather than validation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit usage guidelines under '사용 방법' (Usage Methods), detailing two alternative approaches: passing gtmEvents directly or providing gtmExportJson. It also implicitly guides when to use this tool (for validation of GTM-to-GA4 parameter collection) versus siblings (e.g., ga4_run_report for data retrieval, ga4_custom_dimensions_metrics for dimension management).

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/wonyoungseong/ga4-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server