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";
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 but offers minimal information. It states this is a retrieval operation ('取得します') but doesn't describe what format the analysis results take, whether there are rate limits, authentication requirements, pagination behavior, or what happens when parameters are omitted. For a data retrieval tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient Japanese sentence that directly states the tool's purpose without unnecessary words. It's appropriately sized for what it communicates and front-loads the core functionality. Every word earns its place in conveying the essential information.

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?

Given the complexity of an analytics tool with 3 parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't explain what the analysis results look like, what metrics are included, how data is formatted, or any behavioral constraints. The agent would need to guess about the output structure and operational characteristics when invoking this tool.

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?

The schema description coverage is 100%, so the schema already fully documents all three parameters with descriptions and enum values. The description doesn't add any parameter-specific information beyond what's in the schema. According to the scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no parameter information in the description.

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: '取得します' (get/retrieve) traffic source analysis results, specifying the resource as '流入元(チャネル、ソース、メディアなど)' (traffic sources like channel, source, medium). It distinguishes itself from siblings by focusing specifically on traffic source analysis rather than other analytics dimensions like devices, geography, or pages. However, it doesn't explicitly contrast with the most similar sibling 'get_traffic_summary'.

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. It doesn't mention when this tool is appropriate, what prerequisites might exist, or how it differs from similar tools like 'get_traffic_summary' or 'run_report'. The agent must infer usage context solely from the tool name and description.

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