Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_traffic_sources

Retrieve Google Analytics 4 traffic source data by channel, source, medium, or campaign to analyze user acquisition patterns and marketing performance.

Instructions

流入元(チャネル、ソース、メディアなど)の分析結果を取得します。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間
groupByYesグループ化の方法

Implementation Reference

  • The core handler function implementing the get_traffic_sources tool. It queries GA4 for traffic sources based on groupBy (channel/source/etc.), computes percentages and formats data.
    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 };
    }
  • TypeScript interfaces defining input (GetTrafficSourcesInput) and output (GetTrafficSourcesOutput) schemas, including TrafficSourceGroupBy type for the tool.
    // get_traffic_sources
    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)
    Tool registration in the tools array, defining name, description, and inputSchema for MCP server.
    {
      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-655 (registration)
    Dispatch handler in the switch statement that calls the getTrafficSources 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",
      });
  • Re-export of the getTrafficSources handler from its module for convenient import in server.ts.
    export { getTrafficSources } from "./getTrafficSources.js";

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