Skip to main content
Glama

create_alert_policy

Create alert policies in GCP projects to monitor specific metrics, set thresholds, and define notification channels for timely issue detection and resolution.

Instructions

    Create a new alert policy in a GCP project.
    
    Args:
        project_id: The ID of the GCP project
        display_name: The display name for the alert policy
        metric_type: The metric type to monitor (e.g., "compute.googleapis.com/instance/cpu/utilization")
        filter_str: The filter for the metric data
        duration_seconds: The duration in seconds over which to evaluate the condition (default: 60)
        threshold_value: The threshold value for the condition (default: 0.0)
        comparison: The comparison type (COMPARISON_GT, COMPARISON_LT, etc.) (default: COMPARISON_GT)
        notification_channels: Optional list of notification channel IDs
    
    Returns:
        Result of the alert policy creation
    

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
comparisonNoCOMPARISON_GT
display_nameYes
duration_secondsNo
filter_strYes
metric_typeYes
notification_channelsNo
project_idYes
threshold_valueNo

Implementation Reference

  • The core handler function for the 'create_alert_policy' MCP tool. It uses the Google Cloud Monitoring API to create an alert policy with specified metric, threshold, duration, and optional notification channels. The @mcp.tool() decorator registers it as an MCP tool.
        @mcp.tool()
        def create_alert_policy(project_id: str, display_name: str, metric_type: str, 
                              filter_str: str, duration_seconds: int = 60, 
                              threshold_value: float = 0.0, comparison: str = "COMPARISON_GT",
                              notification_channels: Optional[List[str]] = None) -> str:
            """
            Create a new alert policy in a GCP project.
            
            Args:
                project_id: The ID of the GCP project
                display_name: The display name for the alert policy
                metric_type: The metric type to monitor (e.g., "compute.googleapis.com/instance/cpu/utilization")
                filter_str: The filter for the metric data
                duration_seconds: The duration in seconds over which to evaluate the condition (default: 60)
                threshold_value: The threshold value for the condition (default: 0.0)
                comparison: The comparison type (COMPARISON_GT, COMPARISON_LT, etc.) (default: COMPARISON_GT)
                notification_channels: Optional list of notification channel IDs
            
            Returns:
                Result of the alert policy creation
            """
            try:
                from google.cloud import monitoring_v3
                from google.protobuf import duration_pb2
                
                # Initialize the Alert Policy Service client
                client = monitoring_v3.AlertPolicyServiceClient()
                
                # Format the project name
                project_name = f"projects/{project_id}"
                
                # Create a duration object
                duration = duration_pb2.Duration(seconds=duration_seconds)
                
                # Create the alert condition
                condition = monitoring_v3.AlertPolicy.Condition(
                    display_name=f"Condition for {display_name}",
                    condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
                        filter=filter_str,
                        comparison=getattr(monitoring_v3.ComparisonType, comparison),
                        threshold_value=threshold_value,
                        duration=duration,
                        trigger=monitoring_v3.AlertPolicy.Condition.Trigger(
                            count=1
                        ),
                        aggregations=[
                            monitoring_v3.Aggregation(
                                alignment_period=duration_pb2.Duration(seconds=60),
                                per_series_aligner=monitoring_v3.Aggregation.Aligner.ALIGN_MEAN,
                                cross_series_reducer=monitoring_v3.Aggregation.Reducer.REDUCE_MEAN
                            )
                        ]
                    )
                )
                
                # Create the alert policy
                alert_policy = monitoring_v3.AlertPolicy(
                    display_name=display_name,
                    conditions=[condition],
                    combiner=monitoring_v3.AlertPolicy.ConditionCombinerType.OR
                )
                
                # Add notification channels if provided
                if notification_channels:
                    alert_policy.notification_channels = [
                        f"projects/{project_id}/notificationChannels/{channel_id}" 
                        for channel_id in notification_channels
                    ]
                
                # Create the policy
                policy = client.create_alert_policy(name=project_name, alert_policy=alert_policy)
                
                # Format response
                conditions_str = "\n".join([
                    f"- {c.display_name}: {c.condition_threshold.filter}" 
                    for c in policy.conditions
                ])
                
                notifications_str = "None"
                if policy.notification_channels:
                    notifications_str = "\n".join([
                        f"- {channel.split('/')[-1]}" 
                        for channel in policy.notification_channels
                    ])
                
                return f"""
    Alert Policy created successfully:
    - Name: {policy.display_name}
    - Policy ID: {policy.name.split('/')[-1]}
    - Combiner: {policy.combiner.name}
    
    Conditions:
    {conditions_str}
    
    Notification Channels:
    {notifications_str}
    """
            except Exception as e:
                return f"Error creating alert policy: {str(e)}"
  • Invocation of register_tools from the monitoring module, which defines and registers the 'create_alert_policy' tool using the @mcp.tool() decorator.
    monitoring_tools.register_tools(mcp)
  • Import of the monitoring tools module containing the 'create_alert_policy' implementation and registration.
    from .gcp_modules.monitoring import tools as monitoring_tools

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

A3.6/5.0
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It only states that it creates a policy and returns a vague 'Result'. It does not disclose permissions required, idempotency, failure behavior, or any side effects beyond the creation itself.

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

Conciseness4/5

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

The description is structured with Args and Returns sections, making it easy to scan. It lists all 8 parameters without excessive prose. It earns a 4 because it is appropriately sized for the complexity, though it could be slightly tighter.

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?

The description covers all parameters and states the creation action, but it lacks details about the return value format, potential errors, prerequisites, or how the created policy manifests. Given there is no output schema, some of this information would be helpful for a complete picture.

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

Parameters4/5

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

Schema description coverage is 0%, so the description must compensate. It provides an Args section that defines every parameter, including defaults and example values for metric_type and comparison. This adds meaningful context beyond the parameter names, though some descriptions are terse (e.g., filter_str).

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 states 'Create a new alert policy in a GCP project' with a specific verb and resource. This is unambiguous and distinguishes the tool from sibling monitoring tools that list alerts or metrics, though no sibling creates alert policies.

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?

Usage is implied by the action 'Create a new alert policy' – the tool is for creating policies when needed. However, there is no explicit statement of when to use it versus alternatives, nor any exclusions or prerequisites.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.