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으로 전달하면 자동으로 파싱합니다.
검증 항목
파라미터가 GA4 커스텀 디멘션으로 등록되어 있는지
등록된 파라미터가 실제로 데이터를 수집하고 있는지
미등록/미수집 파라미터에 대한 권장사항
API 호출 효율성
기존: 이벤트 수 × 파라미터 수 = N×M 호출
최적화: 1(메타데이터) + 고유 파라미터 수 = 1+P 호출
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| propertyId | Yes | GA4 속성 ID (예: 419573056) | |
| gtmEvents | No | GTM에서 설정한 이벤트-파라미터 목록 | |
| gtmExportJson | No | GTM Container Export JSON (gtmEvents 대신 사용 가능) | |
| startDate | No | 시작일 (기본: 7daysAgo) | |
| endDate | No | 종료일 (기본: yesterday) |
Implementation Reference
- src/tools/gtm-validator.ts:323-350 (handler)Main handler function that processes tool arguments, parses GTM export JSON (if provided), and calls the validation logicexport 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); } }
- src/tools/gtm-validator.ts:39-191 (handler)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 }; }
- src/tools/gtm-validator.ts:267-321 (schema)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'] } };
- src/tools/index.ts:243-243 (registration)Tool definition registered in the registerAllTools functiongtmValidatorToolDefinition,
- src/tools/index.ts:300-301 (registration)Handler routing in the handleToolCall switch statement that routes ga4_validate_gtm_params to handleGTMValidationcase "ga4_validate_gtm_params": return await handleGTMValidation(args);