Skip to main content
Glama
googleanalytics

Google Analytics MCP Server

Official

run_report

Generate custom Google Analytics reports by specifying dimensions, metrics, date ranges, and filters to extract actionable insights from your website or app data.

Instructions

      Runs a Google Analytics Data API report.

Note that the reference docs at
https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta
all use camelCase field names, but field names passed to this method should
be in snake_case since the tool is using the protocol buffers (protobuf)
format. The protocol buffers for the Data API are available at
https://github.com/googleapis/googleapis/tree/master/google/analytics/data/v1beta.

Args:
    property_id: The Google Analytics property ID. Accepted formats are:
      - A number
      - A string consisting of 'properties/' followed by a number
    date_ranges: A list of date ranges
      (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange)
      to include in the report.
    dimensions: A list of dimensions to include in the report.
    metrics: A list of metrics to include in the report.
    dimension_filter: A Data API FilterExpression
      (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression)
      to apply to the dimensions.  Don't use this for filtering metrics. Use
      metric_filter instead. The `field_name` in a `dimension_filter` must
      be a dimension, as defined in the `get_standard_dimensions` and
      `get_dimensions` tools.
    metric_filter: A Data API FilterExpression
      (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression)
      to apply to the metrics.  Don't use this for filtering dimensions. Use
      dimension_filter instead. The `field_name` in a `metric_filter` must
      be a metric, as defined in the `get_standard_metrics` and
      `get_metrics` tools.
    order_bys: A list of Data API OrderBy
      (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/OrderBy)
      objects to apply to the dimensions and metrics.
    limit: The maximum number of rows to return in each response. Value must
      be a positive integer <= 250,000. Used to paginate through large
      reports, following the guide at
      https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination.
    offset: The row count of the start row. The first row is counted as row
      0. Used to paginate through large
      reports, following the guide at
      https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination.
    currency_code: The currency code to use for currency values. Must be in
      ISO4217 format, such as "AED", "USD", "JPY". If the field is empty, the
      report uses the property's default currency.
    return_property_quota: Whether to return property quota in the response.


      ## Hints for arguments

      Here are some hints that outline the expected format and requirements
      for arguments.

      ### Hints for `dimensions`

      The `dimensions` list must consist solely of either of the following:

      1.  Standard dimensions defined in the HTML table at
          https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions.
          These dimensions are available to *every* property.
      2.  Custom dimensions for the `property_id`. Use the
          `get_custom_dimensions_and_metrics` tool to retrieve the list of
          custom dimensions for a property.

      ### Hints for `metrics`

      The `metrics` list must consist solely of either of the following:

      1.  Standard metrics defined in the HTML table at
          https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics.
          These metrics are available to *every* property.
      2.  Custom metrics for the `property_id`. Use the
          `get_custom_dimensions_and_metrics` tool to retrieve the list of
          custom metrics for a property.


      ### Hints for `date_ranges`:
      Example date_range arguments:
  1. A single date range:

    [ {"start_date": "2025-01-01", "end_date": "2025-01-31", "name": "Jan2025"} ]

  2. A relative date range using 'yesterday' and 'today':
    [ {"start_date": "yesterday", "end_date": "today", "name": "YesterdayAndToday"} ]

  3. A relative date range using 'NdaysAgo' and 'today':
    [ {"start_date": "30daysAgo", "end_date": "yesterday", "name": "Previous30Days"}]

  4. Multiple date ranges:
    [ {"start_date": "2025-01-01", "end_date": "2025-01-31", "name": "Jan2025"}, {"start_date": "2025-02-01", "end_date": "2025-02-28", "name": "Feb2025"} ]


      ### Hints for `dimension_filter`:
      Example dimension_filter arguments:
  1. A simple filter:
    {"filter": {"field_name": "eventName", "string_filter": {"match_type": 2, "value": "add", "case_sensitive": false}}}

  2. A NOT filter:
    {"not_expression": {"filter": {"field_name": "eventName", "string_filter": {"match_type": 2, "value": "add", "case_sensitive": false}}}}

  3. An empty value filter:
    {"filter": {"field_name": "source", "empty_filter": {}}}

  4. An AND group filter:
    {"and_group": {"expressions": [{"filter": {"field_name": "sourceMedium", "string_filter": {"match_type": 1, "value": "google / cpc", "case_sensitive": false}}}, {"filter": {"field_name": "eventName", "in_list_filter": {"values": ["first_visit", "purchase", "add_to_cart"], "case_sensitive": true}}}]}}

  5. An OR group filter:
    {"or_group": {"expressions": [{"filter": {"field_name": "sourceMedium", "string_filter": {"match_type": 1, "value": "google / cpc", "case_sensitive": false}}}, {"filter": {"field_name": "eventName", "in_list_filter": {"values": ["first_visit", "purchase", "add_to_cart"], "case_sensitive": true}}}]}}

Notes: The API applies the dimension_filter and metric_filter independently. As a result, some complex combinations of dimension and metric filters are not possible in a single report request.

For example, you can't create a `dimension_filter` and `metric_filter`
combination for the following condition:

(
  (eventName = "page_view" AND eventCount > 100)
  OR
  (eventName = "join_group" AND eventCount < 50)
)

This isn't possible because there's no way to apply the condition
"eventCount > 100" only to the data with eventName of "page_view", and
the condition "eventCount < 50" only to the data with eventName of
"join_group".

More generally, you can't define a `dimension_filter` and `metric_filter`
for:

(
  ((dimension condition D1) AND (metric condition M1))
  OR
  ((dimension condition D2) AND (metric condition M2))
)

If you have complex conditions like this, either:

a)  Run a single report that applies a subset of the conditions that
    the API supports as well as the data needed to perform filtering of the
    API response on the client side. For example, for the condition:
    (
      (eventName = "page_view" AND eventCount > 100)
      OR
      (eventName = "join_group" AND eventCount < 50)
    )
    You could run a report that filters only on:
    eventName one of "page_view" or "join_group"
    and include the eventCount metric, then filter the API response on the
    client side to apply the different metric filters for the different
    events.

or

b)  Run a separate report for each combination of dimension condition and
    metric condition. For the example above, you'd run one report for the
    combination of (D1 AND M1), and another report for the combination of
    (D2 AND M2).

Try to run fewer reports (option a) if possible. However, if running
fewer reports results in excessive quota usage for the API, use option
b. More information on quota usage is at
https://developers.google.com/analytics/blog/2023/data-api-quota-management.


      ### Hints for `metric_filter`:
      Example metric_filter arguments:
  1. A simple filter:
    {"filter": {"field_name": "eventCount", "numeric_filter": {"operation": 4, "value": {"int64_value": "10"}}}}

  2. A NOT filter:
    {"not_expression": {"filter": {"field_name": "eventCount", "numeric_filter": {"operation": 4, "value": {"int64_value": "10"}}}}}

  3. An empty value filter:
    {"filter": {"field_name": "purchaseRevenue", "empty_filter": {}}}

  4. An AND group filter:
    {"and_group": {"expressions": [{"filter": {"field_name": "eventCount", "numeric_filter": {"operation": 4, "value": {"int64_value": "10"}}}}, {"filter": {"field_name": "purchaseRevenue", "between_filter": {"from_value": {"double_value": 10.0}, "to_value": {"double_value": 25.0}}}}]}}

  5. An OR group filter:
    {"or_group": {"expressions": [{"filter": {"field_name": "eventCount", "numeric_filter": {"operation": 4, "value": {"int64_value": "10"}}}}, {"filter": {"field_name": "purchaseRevenue", "between_filter": {"from_value": {"double_value": 10.0}, "to_value": {"double_value": 25.0}}}}]}}

Notes: The API applies the dimension_filter and metric_filter independently. As a result, some complex combinations of dimension and metric filters are not possible in a single report request.

For example, you can't create a `dimension_filter` and `metric_filter`
combination for the following condition:

(
  (eventName = "page_view" AND eventCount > 100)
  OR
  (eventName = "join_group" AND eventCount < 50)
)

This isn't possible because there's no way to apply the condition
"eventCount > 100" only to the data with eventName of "page_view", and
the condition "eventCount < 50" only to the data with eventName of
"join_group".

More generally, you can't define a `dimension_filter` and `metric_filter`
for:

(
  ((dimension condition D1) AND (metric condition M1))
  OR
  ((dimension condition D2) AND (metric condition M2))
)

If you have complex conditions like this, either:

a)  Run a single report that applies a subset of the conditions that
    the API supports as well as the data needed to perform filtering of the
    API response on the client side. For example, for the condition:
    (
      (eventName = "page_view" AND eventCount > 100)
      OR
      (eventName = "join_group" AND eventCount < 50)
    )
    You could run a report that filters only on:
    eventName one of "page_view" or "join_group"
    and include the eventCount metric, then filter the API response on the
    client side to apply the different metric filters for the different
    events.

or

b)  Run a separate report for each combination of dimension condition and
    metric condition. For the example above, you'd run one report for the
    combination of (D1 AND M1), and another report for the combination of
    (D2 AND M2).

Try to run fewer reports (option a) if possible. However, if running
fewer reports results in excessive quota usage for the API, use option
b. More information on quota usage is at
https://developers.google.com/analytics/blog/2023/data-api-quota-management.


      ### Hints for `order_bys`:
      Example order_bys arguments:

1.  Order by ascending 'eventName':
    [ {"dimension": {"dimension_name": "eventName", "order_type": 1}, "desc": false} ]

2.  Order by descending 'eventName', ignoring case:
    [ {"dimension": {"dimension_name": "campaignName", "order_type": 2}, "desc": true} ]

3.  Order by ascending 'audienceId':
    [ {"dimension": {"dimension_name": "audienceId", "order_type": 3}, "desc": false} ]

4.  Order by descending 'eventCount':
    [ {"metric": {"metric_name": "eventValue"}, "desc": true} ]

5.  Order by ascending 'eventCount':
    [ {"metric": {"metric_name": "eventCount"}, "desc": false} ]

6.  Combination of dimension and metric order bys:
    [
      {"dimension": {"dimension_name": "eventName", "order_type": 1}, "desc": false},
      {"metric": {"metric_name": "eventValue"}, "desc": true},
    ]

7.  Order by multiple dimensions and metrics:
    [
      {"dimension": {"dimension_name": "eventName", "order_type": 1}, "desc": false},
      {"dimension": {"dimension_name": "audienceId", "order_type": 3}, "desc": false},
      {"metric": {"metric_name": "eventValue"}, "desc": true},
    ]

The dimensions and metrics in order_bys must also be present in the report
request's "dimensions" and "metrics" arguments, respectively.


      

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
property_idYes
date_rangesYes
dimensionsYes
metricsYes
dimension_filterNo
metric_filterNo
order_bysNo
limitNo
offsetNo
currency_codeNo
return_property_quotaNo

Implementation Reference

  • The main asynchronous handler function that implements the core logic of the 'run_report' tool. It constructs a RunReportRequest protobuf from input parameters, optionally applies filters and order_bys, executes the request via the Data API client, and converts the response to a dictionary.
    async def run_report(
        property_id: int | str,
        date_ranges: List[Dict[str, str]],
        dimensions: List[str],
        metrics: List[str],
        dimension_filter: Dict[str, Any] = None,
        metric_filter: Dict[str, Any] = None,
        order_bys: List[Dict[str, Any]] = None,
        limit: int = None,
        offset: int = None,
        currency_code: str = None,
        return_property_quota: bool = False,
    ) -> Dict[str, Any]:
        """Runs a Google Analytics Data API report.
    
        Note that the reference docs at
        https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta
        all use camelCase field names, but field names passed to this method should
        be in snake_case since the tool is using the protocol buffers (protobuf)
        format. The protocol buffers for the Data API are available at
        https://github.com/googleapis/googleapis/tree/master/google/analytics/data/v1beta.
    
        Args:
            property_id: The Google Analytics property ID. Accepted formats are:
              - A number
              - A string consisting of 'properties/' followed by a number
            date_ranges: A list of date ranges
              (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange)
              to include in the report.
            dimensions: A list of dimensions to include in the report.
            metrics: A list of metrics to include in the report.
            dimension_filter: A Data API FilterExpression
              (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression)
              to apply to the dimensions.  Don't use this for filtering metrics. Use
              metric_filter instead. The `field_name` in a `dimension_filter` must
              be a dimension, as defined in the `get_standard_dimensions` and
              `get_dimensions` tools.
            metric_filter: A Data API FilterExpression
              (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/FilterExpression)
              to apply to the metrics.  Don't use this for filtering dimensions. Use
              dimension_filter instead. The `field_name` in a `metric_filter` must
              be a metric, as defined in the `get_standard_metrics` and
              `get_metrics` tools.
            order_bys: A list of Data API OrderBy
              (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/OrderBy)
              objects to apply to the dimensions and metrics.
            limit: The maximum number of rows to return in each response. Value must
              be a positive integer <= 250,000. Used to paginate through large
              reports, following the guide at
              https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination.
            offset: The row count of the start row. The first row is counted as row
              0. Used to paginate through large
              reports, following the guide at
              https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination.
            currency_code: The currency code to use for currency values. Must be in
              ISO4217 format, such as "AED", "USD", "JPY". If the field is empty, the
              report uses the property's default currency.
            return_property_quota: Whether to return property quota in the response.
        """
        request = data_v1beta.RunReportRequest(
            property=construct_property_rn(property_id),
            dimensions=[
                data_v1beta.Dimension(name=dimension) for dimension in dimensions
            ],
            metrics=[data_v1beta.Metric(name=metric) for metric in metrics],
            date_ranges=[data_v1beta.DateRange(dr) for dr in date_ranges],
            return_property_quota=return_property_quota,
        )
    
        if dimension_filter:
            request.dimension_filter = data_v1beta.FilterExpression(
                dimension_filter
            )
    
        if metric_filter:
            request.metric_filter = data_v1beta.FilterExpression(metric_filter)
    
        if order_bys:
            request.order_bys = [
                data_v1beta.OrderBy(order_by) for order_by in order_bys
            ]
    
        if limit:
            request.limit = limit
        if offset:
            request.offset = offset
        if currency_code:
            request.currency_code = currency_code
    
        response = await create_data_api_client().run_report(request)
    
        return proto_to_dict(response)
  • Registers the 'run_report' function as an MCP tool using mcp.add_tool, providing a title and a dynamically generated description that includes argument hints.
    mcp.add_tool(
        run_report,
        title="Run a Google Analytics Data API report using the Data API",
        description=_run_report_description(),
    )
  • Generates a comprehensive tool description incorporating the function docstring and hints for all parameters (dimensions, metrics, date_ranges, filters, order_bys) sourced from metadata helpers, serving as the schema documentation.
    def _run_report_description() -> str:
        """Returns the description for the `run_report` tool."""
        return f"""
              {run_report.__doc__}
    
              ## Hints for arguments
    
              Here are some hints that outline the expected format and requirements
              for arguments.
    
              ### Hints for `dimensions`
    
              The `dimensions` list must consist solely of either of the following:
    
              1.  Standard dimensions defined in the HTML table at
                  https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#dimensions.
                  These dimensions are available to *every* property.
              2.  Custom dimensions for the `property_id`. Use the
                  `get_custom_dimensions_and_metrics` tool to retrieve the list of
                  custom dimensions for a property.
    
              ### Hints for `metrics`
    
              The `metrics` list must consist solely of either of the following:
    
              1.  Standard metrics defined in the HTML table at
                  https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema#metrics.
                  These metrics are available to *every* property.
              2.  Custom metrics for the `property_id`. Use the
                  `get_custom_dimensions_and_metrics` tool to retrieve the list of
                  custom metrics for a property.
    
    
              ### Hints for `date_ranges`:
              {get_date_ranges_hints()}
    
              ### Hints for `dimension_filter`:
              {get_dimension_filter_hints()}
    
              ### Hints for `metric_filter`:
              {get_metric_filter_hints()}
    
              ### Hints for `order_bys`:
              {get_order_bys_hints()}
    
              """
  • Helper function providing example date_ranges for use in the run_report tool description.
    def get_date_ranges_hints():
        range_jan = data_v1beta.DateRange(
            start_date="2025-01-01", end_date="2025-01-31", name="Jan2025"
        )
        range_feb = data_v1beta.DateRange(
            start_date="2025-02-01", end_date="2025-02-28", name="Feb2025"
        )
        range_last_2_days = data_v1beta.DateRange(
            start_date="yesterday", end_date="today", name="YesterdayAndToday"
        )
        range_prev_30_days = data_v1beta.DateRange(
            start_date="30daysAgo", end_date="yesterday", name="Previous30Days"
        )
    
        return f"""Example date_range arguments:
          1. A single date range:
    
            [ {proto_to_json(range_jan)} ]
    
          2. A relative date range using 'yesterday' and 'today':
            [ {proto_to_json(range_last_2_days)} ]
    
          3. A relative date range using 'NdaysAgo' and 'today':
            [ {proto_to_json(range_prev_30_days)}]
    
          4. Multiple date ranges:
            [ {proto_to_json(range_jan)}, {proto_to_json(range_feb)} ]
        """
  • Helper function providing examples and notes for dimension_filter expressions used in run_report hints.
    def get_dimension_filter_hints():
        """Returns hints and samples for dimension_filter arguments."""
        begins_with = data_v1beta.FilterExpression(
            filter=data_v1beta.Filter(
                field_name="eventName",
                string_filter=data_v1beta.Filter.StringFilter(
                    match_type=data_v1beta.Filter.StringFilter.MatchType.BEGINS_WITH,
                    value="add",
                ),
            )
        )
        not_filter = data_v1beta.FilterExpression(not_expression=begins_with)
        empty_filter = data_v1beta.FilterExpression(
            filter=data_v1beta.Filter(
                field_name="source", empty_filter=data_v1beta.Filter.EmptyFilter()
            )
        )
        source_medium_filter = data_v1beta.FilterExpression(
            filter=data_v1beta.Filter(
                field_name="sourceMedium",
                string_filter=data_v1beta.Filter.StringFilter(
                    match_type=data_v1beta.Filter.StringFilter.MatchType.EXACT,
                    value="google / cpc",
                ),
            )
        )
        event_list_filter = data_v1beta.FilterExpression(
            filter=data_v1beta.Filter(
                field_name="eventName",
                in_list_filter=data_v1beta.Filter.InListFilter(
                    case_sensitive=True,
                    values=["first_visit", "purchase", "add_to_cart"],
                ),
            )
        )
        and_filter = data_v1beta.FilterExpression(
            and_group=data_v1beta.FilterExpressionList(
                expressions=[source_medium_filter, event_list_filter]
            )
        )
        or_filter = data_v1beta.FilterExpression(
            or_group=data_v1beta.FilterExpressionList(
                expressions=[source_medium_filter, event_list_filter]
            )
        )
        return (
            f"""Example dimension_filter arguments:
          1. A simple filter:
            {proto_to_json(begins_with)}
    
          2. A NOT filter:
            {proto_to_json(not_filter)}
    
          3. An empty value filter:
            {proto_to_json(empty_filter)}
    
          4. An AND group filter:
            {proto_to_json(and_filter)}
    
          5. An OR group filter:
            {proto_to_json(or_filter)}
    
        """
            + _FILTER_NOTES
        )

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

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