Skip to main content
Glama
Shin-sibainu

GA4 MCP Server

by Shin-sibainu

get_device_breakdown

Retrieve device breakdown analytics from Google Analytics 4, showing access distribution across PCs, mobiles, and tablets with OS and browser details.

Instructions

デバイス別(PC/モバイル/タブレット)のアクセス内訳を取得します。OS別、ブラウザ別の情報も含まれます。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
propertyIdNoGA4プロパティID
periodYes集計期間

Implementation Reference

  • The main handler function that implements the get_device_breakdown tool logic. It fetches GA4 reports for device categories, operating systems, and browsers, processes the data, and returns formatted breakdown statistics.
    export async function getDeviceBreakdown(
      input: GetDeviceBreakdownInput
    ): Promise<GetDeviceBreakdownOutput> {
      const propertyId = getPropertyId(input.propertyId);
      const property = formatPropertyPath(propertyId);
      const dateRange = periodToDateRange(input.period);
    
      // デバイスカテゴリ別のデータ取得
      const deviceResponse = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "deviceCategory" }],
        metrics: [
          { name: "totalUsers" },
          { name: "sessions" },
          { name: "bounceRate" },
          { name: "averageSessionDuration" },
        ],
        orderBys: [{ metric: { metricName: "totalUsers" }, desc: true }],
      });
    
      // 合計ユーザー数を取得
      const totalUsers =
        deviceResponse.totals?.[0]?.metricValues?.[0]?.value
          ? parseFloat(deviceResponse.totals[0].metricValues[0].value)
          : 0;
    
      const devices: DeviceData[] = [];
    
      for (const row of deviceResponse.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 users = Math.round(getValue(0));
        const deviceCategory = dimensionValues[0]?.value || "unknown";
    
        devices.push({
          deviceCategory: deviceCategory as "desktop" | "mobile" | "tablet",
          users,
          sessions: Math.round(getValue(1)),
          percentage: calculatePercentage(users, totalUsers),
          bounceRate: formatPercentageFromDecimal(getValue(2)),
          avgSessionDuration: formatDuration(getValue(3)),
        });
      }
    
      // OS別のデータ取得
      const osResponse = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "operatingSystem" }],
        metrics: [{ name: "totalUsers" }],
        orderBys: [{ metric: { metricName: "totalUsers" }, desc: true }],
        limit: 10,
      });
    
      const operatingSystems: OSData[] = [];
    
      for (const row of osResponse.rows || []) {
        const dimensionValues = row.dimensionValues || [];
        const metricValues = row.metricValues || [];
    
        const users = metricValues[0]?.value
          ? Math.round(parseFloat(metricValues[0].value))
          : 0;
    
        operatingSystems.push({
          name: dimensionValues[0]?.value || "(不明)",
          users,
          percentage: calculatePercentage(users, totalUsers),
        });
      }
    
      // ブラウザ別のデータ取得
      const browserResponse = await executeReport({
        property,
        dateRanges: [dateRange],
        dimensions: [{ name: "browser" }],
        metrics: [{ name: "totalUsers" }],
        orderBys: [{ metric: { metricName: "totalUsers" }, desc: true }],
        limit: 10,
      });
    
      const browsers: BrowserData[] = [];
    
      for (const row of browserResponse.rows || []) {
        const dimensionValues = row.dimensionValues || [];
        const metricValues = row.metricValues || [];
    
        const users = metricValues[0]?.value
          ? Math.round(parseFloat(metricValues[0].value))
          : 0;
    
        browsers.push({
          name: dimensionValues[0]?.value || "(不明)",
          users,
          percentage: calculatePercentage(users, totalUsers),
        });
      }
    
      return {
        devices,
        operatingSystems,
        browsers,
      };
    }
  • TypeScript interfaces defining the input (GetDeviceBreakdownInput with propertyId and period) and output (GetDeviceBreakdownOutput with devices, operatingSystems, browsers) schemas, along with supporting types DeviceData, OSData, BrowserData.
    // get_device_breakdown
    export interface GetDeviceBreakdownInput extends PropertyId {
      period: ShortPeriod;
    }
    
    export interface DeviceData {
      deviceCategory: "desktop" | "mobile" | "tablet";
      users: number;
      sessions: number;
      percentage: string;
      bounceRate: string;
      avgSessionDuration: string;
    }
    
    export interface OSData {
      name: string;
      users: number;
      percentage: string;
    }
    
    export interface BrowserData {
      name: string;
      users: number;
      percentage: string;
    }
    
    export interface GetDeviceBreakdownOutput {
      devices: DeviceData[];
      operatingSystems?: OSData[];
      browsers?: BrowserData[];
    }
  • src/server.ts:269-285 (registration)
    MCP tool registration in the tools array, defining name, description, and JSON inputSchema for get_device_breakdown.
    {
      name: "get_device_breakdown",
      description:
        "デバイス別(PC/モバイル/タブレット)のアクセス内訳を取得します。OS別、ブラウザ別の情報も含まれます。",
      inputSchema: {
        type: "object" as const,
        properties: {
          propertyId: { type: "string", description: "GA4プロパティID" },
          period: {
            type: "string",
            enum: ["7days", "28days", "30days"],
            description: "集計期間",
          },
        },
        required: ["period"],
      },
    },
  • src/server.ts:657-661 (registration)
    Dispatch handler in the switch statement that calls the getDeviceBreakdown function with parsed arguments.
    case "get_device_breakdown":
      return await getDeviceBreakdown({
        propertyId: args.propertyId as string | undefined,
        period: args.period as "7days" | "28days" | "30days",
      });
Behavior2/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 states what data is returned (device breakdown with OS/browser info) but doesn't describe the return format, pagination, rate limits, authentication needs, or whether this is a read-only operation. For a data retrieval tool with zero annotation coverage, this leaves significant gaps in understanding how the tool behaves.

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 appropriately sized and front-loaded. The first sentence clearly states the core purpose, and the second sentence adds valuable supplementary information about included data (OS and browser details). There's no wasted language or redundancy.

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

Completeness3/5

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

For a simple 2-parameter read tool with no output schema, the description provides basic purpose but lacks important context. It doesn't explain the return format, data structure, or what 'アクセス内訳' (access breakdown) specifically entails. While it mentions OS and browser information are included, it doesn't describe how this data is organized or presented.

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 both parameters (propertyId and period with enum values). The description doesn't add any parameter-specific information beyond what's in the schema. It doesn't explain how these parameters affect the device breakdown results or provide additional context about parameter usage.

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: 'デバイス別(PC/モバイル/タブレット)のアクセス内訳を取得します' (Get access breakdown by device - PC/mobile/tablet). It specifies the verb ('取得します' - get/retrieve) and resource ('アクセス内訳' - access breakdown) with device categories. However, it doesn't explicitly differentiate from sibling tools like 'get_geo_breakdown' or 'get_traffic_sources' beyond mentioning it includes OS and browser information.

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 (e.g., for device-specific analysis) or when other tools like 'get_traffic_summary' or 'get_engagement_metrics' might be better suited. There's no context about prerequisites or exclusions.

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