Skip to main content
Glama
googleanalytics

Google Analytics MCP Server

Official

run_funnel_report

Analyze user progression through custom funnel steps in Google Analytics to identify drop-off points and conversion rates.

Instructions

    Run a Google Analytics Data API funnel report.

See the funnel report guide at
https://developers.google.com/analytics/devguides/reporting/data/v1/funnels
for details and examples.

Args:
    property_id: The Google Analytics property ID. Accepted formats are:
      - A number
      - A string consisting of 'properties/' followed by a number
    funnel_steps: A list of funnel steps. Each step should be a dictionary
      containing:
      - 'name': (str) Display name for the step
      - 'filter_expression': (Dict) Complete filter expression for the step
      OR for simple event-based steps:
      - 'name': (str) Display name for the step
      - 'event': (str) Event name to filter on
    date_ranges: A list of date ranges
      (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange)
      to include in the report.
    funnel_breakdown: Optional breakdown dimension to segment the funnel.
      This creates separate funnel results for each value of the dimension.
      Example: {"breakdown_dimension": "deviceCategory"}
    funnel_next_action: Optional next action analysis configuration.
      This analyzes what users do after completing or dropping off from
      the funnel.
      Example: {"next_action_dimension": "eventName", "limit": 5}
    segments: Optional list of segments to apply to the funnel.
    return_property_quota: Whether to return current property quota
      information.

Returns:
    Dict containing the funnel report response with funnel results
    including:
    - funnel_table: Table showing progression through funnel steps
    - funnel_visualization: Data for visualizing the funnel
    - property_quota: (if requested) Current quota usage information

Raises:
    ValueError: If funnel_steps is empty or contains invalid configurations
    Exception: If the API request fails


    ## Hints for arguments

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

    ### Hints for `funnel_breakdown`

    The `funnel_breakdown` parameter allows you to segment funnel results by a dimension:
    ```json
    {
        "breakdown_dimension": "deviceCategory"
    }
    ```
    Common breakdown dimensions include:
    - `deviceCategory` - Desktop, Mobile, Tablet
    - `country` - User's country
    - `operatingSystem` - User's operating system
    - `browser` - User's browser

    ### Hints for `funnel_next_action`

    The `funnel_next_action` parameter analyzes what users do after completing or dropping off from the funnel:
    ```json
    {
        "next_action_dimension": "eventName",
        "limit": 5
    }
    ```
    Common next action dimensions include:
    - `eventName` - Next events users trigger
    - `pagePath` - Next pages users visit

    ### Hints for `segments`

    The `segments` parameter allows you to segment funnel results by user criteria.
    Each segment is a dictionary passed directly to `data_v1alpha.Segment()`.
    See https://developers.google.com/analytics/devguides/reporting/data/v1/funnels#segments
    for details and examples.

    ### 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 `funnel_steps`
    Example funnel_steps configurations:

1. Simple event-based step (first open/visit):
    {"name": "First open/visit", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "first_open"}}, {"funnel_event_filter": {"event_name": "first_visit"}}]}}, "is_directly_followed_by": false}

2. Field filter for organic traffic:
    {"name": "Organic visitors", "filter_expression": {"funnel_field_filter": {"field_name": "firstUserMedium", "string_filter": {"match_type": 4, "value": "organic", "case_sensitive": false}}}, "is_directly_followed_by": false}

3. Simple event filter:
    {"name": "Session start", "filter_expression": {"funnel_event_filter": {"event_name": "session_start"}}, "is_directly_followed_by": false}

4. Multiple events with OR condition:
    {"name": "Screen/Page view", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "screen_view"}}, {"funnel_event_filter": {"event_name": "page_view"}}]}}, "is_directly_followed_by": false}

5. Purchase events (multiple event types):
    {"name": "Purchase", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "purchase"}}, {"funnel_event_filter": {"event_name": "in_app_purchase"}}]}}, "is_directly_followed_by": false}

6. Event with parameter filter (value > 50):
    {"name": "Add to cart (value > 50)", "filter_expression": {"funnel_event_filter": {"event_name": "add_to_cart", "funnel_parameter_filter_expression": {"funnel_parameter_filter": {"event_parameter_name": "value", "numeric_filter": {"operation": 4, "value": {"double_value": 50.0}}}}}}, "is_directly_followed_by": false}

7. Complex AND condition (page view + specific path):
    {"name": "Home page view", "filter_expression": {"and_group": {"expressions": [{"funnel_event_filter": {"event_name": "page_view"}}, {"funnel_field_filter": {"field_name": "pageLocation", "string_filter": {"match_type": 4, "value": "/", "case_sensitive": false}}}]}}, "is_directly_followed_by": false}


## Complete Funnel Example

A typical e-commerce funnel with 5 steps:
[
    {"name": "First open/visit", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "first_open"}}, {"funnel_event_filter": {"event_name": "first_visit"}}]}}, "is_directly_followed_by": false},
    {"name": "Organic visitors", "filter_expression": {"funnel_field_filter": {"field_name": "firstUserMedium", "string_filter": {"match_type": 4, "value": "organic", "case_sensitive": false}}}, "is_directly_followed_by": false},
    {"name": "Session start", "filter_expression": {"funnel_event_filter": {"event_name": "session_start"}}, "is_directly_followed_by": false},
    {"name": "Screen/Page view", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "screen_view"}}, {"funnel_event_filter": {"event_name": "page_view"}}]}}, "is_directly_followed_by": false},
    {"name": "Purchase", "filter_expression": {"or_group": {"expressions": [{"funnel_event_filter": {"event_name": "purchase"}}, {"funnel_event_filter": {"event_name": "in_app_purchase"}}]}}, "is_directly_followed_by": false}
]



    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
property_idYes
funnel_stepsYes
date_rangesNo
funnel_breakdownNo
funnel_next_actionNo
segmentsNo
return_property_quotaNo

Implementation Reference

  • Main handler function that executes the funnel report tool logic. Builds FunnelStep objects from input, constructs a RunFunnelReportRequest, calls the Google Analytics Data API (Alpha), and returns the response as a dict.
    async def run_funnel_report(
        property_id: int | str,
        funnel_steps: List[Dict[str, Any]],
        date_ranges: List[Dict[str, str]] = None,
        funnel_breakdown: Dict[str, str] = None,
        funnel_next_action: Dict[str, str] = None,
        segments: List[Dict[str, Any]] = None,
        return_property_quota: bool = False,
    ) -> Dict[str, Any]:
        """Run a Google Analytics Data API funnel report.
    
        See the funnel report guide at
        https://developers.google.com/analytics/devguides/reporting/data/v1/funnels
        for details and examples.
    
        Args:
            property_id: The Google Analytics property ID. Accepted formats are:
              - A number
              - A string consisting of 'properties/' followed by a number
            funnel_steps: A list of funnel steps. Each step should be a dictionary
              containing:
              - 'name': (str) Display name for the step
              - 'filter_expression': (Dict) Complete filter expression for the step
              OR for simple event-based steps:
              - 'name': (str) Display name for the step
              - 'event': (str) Event name to filter on
            date_ranges: A list of date ranges
              (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/DateRange)
              to include in the report.
            funnel_breakdown: Optional breakdown dimension to segment the funnel.
              This creates separate funnel results for each value of the dimension.
              Example: {"breakdown_dimension": "deviceCategory"}
            funnel_next_action: Optional next action analysis configuration.
              This analyzes what users do after completing or dropping off from
              the funnel.
              Example: {"next_action_dimension": "eventName", "limit": 5}
            segments: Optional list of segments to apply to the funnel.
            return_property_quota: Whether to return current property quota
              information.
    
        Returns:
            Dict containing the funnel report response with funnel results
            including:
            - funnel_table: Table showing progression through funnel steps
            - funnel_visualization: Data for visualizing the funnel
            - property_quota: (if requested) Current quota usage information
    
        Raises:
            ValueError: If funnel_steps is empty or contains invalid configurations
            Exception: If the API request fails
        """
        if not funnel_steps:
            raise ValueError("funnel_steps must contain at least one step")
    
        steps = []
        for i, step in enumerate(funnel_steps):
            if not isinstance(step, dict):
                raise ValueError(f"Step {i+1} must be a dictionary")
    
            step_name = step.get("name", f"Step {i+1}")
    
            if "filter_expression" in step:
                filter_expr = data_v1alpha.FunnelFilterExpression(
                    step["filter_expression"]
                )
            elif "event" in step:
                filter_expr = data_v1alpha.FunnelFilterExpression(
                    funnel_event_filter=data_v1alpha.FunnelEventFilter(
                        event_name=step["event"]
                    )
                )
            else:
                raise ValueError(
                    f"Step {i+1} must contain either 'filter_expression' or 'event' key"
                )
    
            funnel_step = data_v1alpha.FunnelStep(
                name=step_name, filter_expression=filter_expr
            )
            steps.append(funnel_step)
    
        request = data_v1alpha.RunFunnelReportRequest(
            property=construct_property_rn(property_id),
            funnel=data_v1alpha.Funnel(steps=steps),
            date_ranges=[data_v1alpha.DateRange(dr) for dr in (date_ranges or [])],
            return_property_quota=return_property_quota,
        )
    
        if funnel_breakdown and "breakdown_dimension" in funnel_breakdown:
            request.funnel_breakdown = data_v1alpha.FunnelBreakdown(
                breakdown_dimension=data_v1alpha.Dimension(
                    name=funnel_breakdown["breakdown_dimension"]
                )
            )
    
        if funnel_next_action and "next_action_dimension" in funnel_next_action:
            next_action_config = data_v1alpha.FunnelNextAction(
                next_action_dimension=data_v1alpha.Dimension(
                    name=funnel_next_action["next_action_dimension"]
                )
            )
            if "limit" in funnel_next_action:
                next_action_config.limit = funnel_next_action["limit"]
            request.funnel_next_action = next_action_config
    
        if segments:
            request.segments = [
                data_v1alpha.Segment(segment) for segment in segments
            ]
    
        def _sync_call():
            return create_data_api_alpha_client().run_funnel_report(request)
    
        response = await asyncio.to_thread(_sync_call)
        return proto_to_dict(response)
  • Input schema/type definitions for the tool's parameters. Defines types for property_id, funnel_steps, date_ranges, funnel_breakdown, funnel_next_action, segments, and return_property_quota.
    async def run_funnel_report(
        property_id: int | str,
        funnel_steps: List[Dict[str, Any]],
        date_ranges: List[Dict[str, str]] = None,
        funnel_breakdown: Dict[str, str] = None,
        funnel_next_action: Dict[str, str] = None,
        segments: List[Dict[str, Any]] = None,
        return_property_quota: bool = False,
    ) -> Dict[str, Any]:
  • Registration of run_funnel_report as a FunctionTool with a custom description, added to the tools list that gets exposed via MCP.
    from analytics_mcp.tools.reporting.funnel import (
        run_funnel_report,
        _run_funnel_report_description,
    )
    
    run_report_with_description = FunctionTool(run_report)
    run_report_with_description.description = _run_report_description()
    run_realtime_report_with_description = FunctionTool(run_realtime_report)
    run_realtime_report_with_description.description = (
        _run_realtime_report_description()
    )
    run_funnel_report_with_description = FunctionTool(run_funnel_report)
    run_funnel_report_with_description.description = (
        _run_funnel_report_description()
    )
  • Helper function that generates the tool description including the docstring and hints for funnel_breakdown, funnel_next_action, segments, date_ranges, and funnel_steps.
    def _run_funnel_report_description() -> str:
        """Returns the description for the `run_funnel_report` tool."""
        return f"""
            {run_funnel_report.__doc__}
    
            ## Hints for arguments
    
            Here are some hints that outline the expected format and requirements
            for arguments.
    
            ### Hints for `funnel_breakdown`
    
            The `funnel_breakdown` parameter allows you to segment funnel results by a dimension:
            ```json
            {{
                "breakdown_dimension": "deviceCategory"
            }}
            ```
            Common breakdown dimensions include:
            - `deviceCategory` - Desktop, Mobile, Tablet
            - `country` - User's country
            - `operatingSystem` - User's operating system
            - `browser` - User's browser
    
            ### Hints for `funnel_next_action`
    
            The `funnel_next_action` parameter analyzes what users do after completing or dropping off from the funnel:
            ```json
            {{
                "next_action_dimension": "eventName",
                "limit": 5
            }}
            ```
            Common next action dimensions include:
            - `eventName` - Next events users trigger
            - `pagePath` - Next pages users visit
    
            ### Hints for `segments`
    
            The `segments` parameter allows you to segment funnel results by user criteria.
            Each segment is a dictionary passed directly to `data_v1alpha.Segment()`.
            See https://developers.google.com/analytics/devguides/reporting/data/v1/funnels#segments
            for details and examples.
    
            ### Hints for `date_ranges`:
            {get_date_ranges_hints()}
    
            ### Hints for `funnel_steps`
            {get_funnel_steps_hints()}
    
            """
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the transparency burden. It details parameters, return structure, and potential exceptions, but does not disclose behavior like idempotency, authorization needs, or rate limits. Adequate but not fully transparent.

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

Conciseness3/5

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

The description is lengthy with many repeated examples and sections. While front-loaded with purpose, the hints section could be streamlined. Some redundancy exists, but overall structure is logical.

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

Completeness4/5

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

Given the tool's complexity (7 parameters, nested objects, no output schema), the description covers all parameters with examples, return format, and error handling. It is complete for a complex tool, though somewhat verbose.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema coverage, the description fully compensates by providing extensive hints and examples for each parameter, including nested objects for funnel_steps, date_ranges, and optional breakdown/next_action. This adds substantial meaning beyond the bare schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states 'Run a Google Analytics Data API funnel report', specifying a concrete action and resource. It distinguishes itself from sibling tools like run_report and run_realtime_report by focusing on funnel-specific report type.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies when to use this tool (for funnel analysis) but does not explicitly contrast with alternatives such as run_report or provide when-not-to-use guidance. It references an external guide but lacks direct sibling differentiation.

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

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