Skip to main content
Glama
ruchernchong

mcp-server-google-analytics

by ruchernchong

getPageViews

Retrieve page view metrics from Google Analytics 4 for specified date ranges and dimensions to analyze website traffic patterns.

Instructions

Get page view metrics for a specific date range

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
startDateYesStart date in YYYY-MM-DD format
endDateYesEnd date in YYYY-MM-DD format
dimensionsNoDimensions to group by (e.g., page, country)

Implementation Reference

  • Handler for the getPageViews tool. Extracts startDate, endDate, and optional dimensions (defaults to 'page'), validates the date range, and invokes fetchAnalyticsData with appropriate dimensions and the 'screenPageViews' metric.
    case "getPageViews": {
      const {
        startDate,
        endDate,
        dimensions = ["page"],
      } = args as {
        startDate: string;
        endDate: string;
        dimensions?: string[];
      };
    
      validateDateRange(startDate, endDate);
    
      return fetchAnalyticsData({
        dateRanges: [{ startDate, endDate }],
        dimensions: dimensions.map((dimension) => ({ name: dimension })),
        metrics: [{ name: "screenPageViews" }],
      });
    }
  • src/index.ts:177-199 (registration)
    Registration of the getPageViews tool in the ListTools response, including name, description, and input schema.
    {
      name: "getPageViews",
      description: "Get page view metrics for a specific date range",
      inputSchema: {
        type: "object",
        properties: {
          startDate: {
            type: "string",
            description: "Start date in YYYY-MM-DD format",
          },
          endDate: {
            type: "string",
            description: "End date in YYYY-MM-DD format",
          },
          dimensions: {
            type: "array",
            items: { type: "string" },
            description: "Dimensions to group by (e.g., page, country)",
          },
        },
        required: ["startDate", "endDate"],
      },
    },
  • Helper function fetchAnalyticsData that performs the actual Google Analytics API call using runReport and formats the response.
    async function fetchAnalyticsData(
      reportConfig: Partial<Omit<RunReportRequest, "property">> & {
        dateRanges: RunReportRequest["dateRanges"];
        dimensions?: RunReportRequest["dimensions"];
        metrics?: RunReportRequest["metrics"];
      },
    ) {
      try {
        const [response] = await analyticsDataClient.runReport({
          property: `properties/${propertyId}`,
          ...reportConfig,
        });
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(response, null, 2),
            },
          ],
        };
      } catch (error) {
        // Handle Google Analytics API errors
        if (error instanceof Error) {
          throw new McpError(
            ErrorCode.InternalError,
            `Google Analytics API error: ${error.message}`,
          );
        }
        throw new McpError(ErrorCode.InternalError, "An unexpected error occurred");
      }
    }
  • Helper function validateDateRange used by the handler to validate input dates.
    function validateDateRange(startDate: string, endDate: string): void {
      if (!validateDateFormat(startDate)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `Invalid startDate format. Expected YYYY-MM-DD, got: ${startDate}`,
        );
      }
    
      if (!validateDateFormat(endDate)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          `Invalid endDate format. Expected YYYY-MM-DD, got: ${endDate}`,
        );
      }
    
      if (new Date(startDate) > new Date(endDate)) {
        throw new McpError(
          ErrorCode.InvalidParams,
          "startDate cannot be after endDate",
        );
      }
    }

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/ruchernchong/mcp-server-google-analytics'

If you have feedback or need assistance with the MCP directory API, please join our Discord server