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",
      });

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