get_traffic_sources
Retrieve Google Analytics 4 traffic source data to analyze channels, sources, media, and campaigns for marketing performance insights.
Instructions
流入元(チャネル、ソース、メディアなど)の分析結果を取得します。
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| propertyId | No | GA4プロパティID | |
| period | Yes | 集計期間 | |
| groupBy | Yes | グループ化の方法 |
Implementation Reference
- The main handler function implementing the get_traffic_sources tool. It queries the Google Analytics 4 API for traffic data grouped by the specified dimension (channel, source, etc.), processes the response to calculate percentages and format rates, and returns a list of traffic sources.export async function getTrafficSources( input: GetTrafficSourcesInput ): Promise<GetTrafficSourcesOutput> { const propertyId = getPropertyId(input.propertyId); const property = formatPropertyPath(propertyId); const dateRange = periodToDateRange(input.period); // groupBy に応じてディメンションを選択 const dimensionMap: Record<string, string> = { channel: "sessionDefaultChannelGroup", source: "sessionSource", medium: "sessionMedium", sourceMedium: "sessionSourceMedium", campaign: "sessionCampaignName", }; const dimension = dimensionMap[input.groupBy] || "sessionDefaultChannelGroup"; const response = await executeReport({ property, dateRanges: [dateRange], dimensions: [{ name: dimension }], metrics: [ { name: "sessions" }, { name: "totalUsers" }, { name: "bounceRate" }, ], orderBys: [{ metric: { metricName: "sessions" }, desc: true }], limit: 20, }); // 合計セッション数を取得 const totalSessions = response.totals?.[0]?.metricValues?.[0]?.value ? parseFloat(response.totals[0].metricValues[0].value) : 0; const sources: TrafficSource[] = []; for (const row of response.rows || []) { const dimensionValues = row.dimensionValues || []; const metricValues = row.metricValues || []; const getValue = (index: number): number => { const value = metricValues[index]?.value; return value ? parseFloat(value) : 0; }; const sessions = Math.round(getValue(0)); sources.push({ name: dimensionValues[0]?.value || "(不明)", sessions, users: Math.round(getValue(1)), percentage: calculatePercentage(sessions, totalSessions), bounceRate: formatPercentageFromDecimal(getValue(2)), }); } return { sources }; }
- src/types.ts:152-170 (schema)TypeScript type definitions for the tool's input parameters (period and groupBy), output structure, individual TrafficSource items, and groupBy options.export type TrafficSourceGroupBy = "channel" | "source" | "medium" | "sourceMedium" | "campaign"; export interface GetTrafficSourcesInput extends PropertyId { period: Period; groupBy: TrafficSourceGroupBy; } export interface TrafficSource { name: string; sessions: number; users: number; percentage: string; bounceRate: string; conversionRate?: string; } export interface GetTrafficSourcesOutput { sources: TrafficSource[]; }
- src/server.ts:247-268 (registration)MCP tool registration in the tools array, defining the tool's name, Japanese description, and JSON input schema matching the TypeScript types.{ name: "get_traffic_sources", description: "流入元(チャネル、ソース、メディアなど)の分析結果を取得します。", inputSchema: { type: "object" as const, properties: { propertyId: { type: "string", description: "GA4プロパティID" }, period: { type: "string", enum: ["7days", "28days", "30days", "90days"], description: "集計期間", }, groupBy: { type: "string", enum: ["channel", "source", "medium", "sourceMedium", "campaign"], description: "グループ化の方法", }, }, required: ["period", "groupBy"], }, },
- src/server.ts:645-656 (registration)Dispatch case in the handleToolCall switch statement that routes calls to the getTrafficSources handler function with parsed arguments.case "get_traffic_sources": return await getTrafficSources({ propertyId: args.propertyId as string | undefined, period: args.period as "7days" | "28days" | "30days" | "90days", groupBy: args.groupBy as | "channel" | "source" | "medium" | "sourceMedium" | "campaign", });