Skip to main content
skill Claude Code Gemini CLI CX Codex official · Google

cloud-monitoring-promql-query — Claude Code skill

Generates PromQL queries for Cloud Monitoring metrics and resources. Use it when you need a query or aggregation for a known metric type.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add google/skills --skill cloud-monitoring-promql-query -a claude-code
Open on GitHub

What cloud-monitoring-promql-query does

This skill turns Cloud Monitoring metric descriptors and resource parameters into valid PromQL queries. It uses the metric type, metric kind, value type, compatible monitored resources, and resource filters to shape the result. It handles PromQL queries and aggregations, but it is not intended for discovering or selecting raw metrics.

When descriptor details are missing, the skill can use google-cloud-monitoring:list_metric_descriptors or the Cloud Monitoring API. It can fetch a monitored resource descriptor when resource labels are unclear. A Google Cloud Project ID and access to the relevant Cloud Monitoring tools are required for these lookups.

Install it when your agent needs to write PromQL for a specific Cloud Monitoring metric. Use cloud-monitoring-metric-selection first when the metric itself still needs to be identified.

What it helps with

  • write PromQL for a Cloud Monitoring metric
  • scope a query to a monitored resource
  • build an aggregation from metric descriptors
  • resolve resource labels for a PromQL filter

Example prompts for the agent

  • Generate PromQL for `compute.googleapis.com/instance/cpu/utilization` for this resource.
  • Write a Cloud Monitoring query with a `monitored_resource` filter and an aggregation.
  • Inspect the metric descriptor and return a valid PromQL string.

How to install cloud-monitoring-promql-query

1Skills CLI (Vercel)

npx skills add google/skills --skill cloud-monitoring-promql-query -a claude-code

2Manually: put the files in place

~/.claude/skills/cloud-monitoring-promql-query/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/cloud-monitoring-promql-query/

From the same set172

The whole set →
bigquery-basics official google Manages BigQuery resources and runs SQL queries. Use it to create datasets, tables and views, or handle basic data ingestion and analysis. Claude Code Gemini CLI CX Codex 17,678installs cloud-run-basics official google This skill helps an agent manage Cloud Run services, jobs, and worker pools when a project needs HTTP deployment, scheduled work, or pull-based background processing. Claude Code Gemini CLI CX Codex 17,532installs gemini-api official google Connects Gemini API from Google Cloud Agent Platform to the agent. Gives access to Gemini models, multimodal input, function calling, and context caching. Claude Code Gemini CLI CX Codex 17,116installs google-cloud-recipe-auth official Google LLC This skill explains Google Cloud authentication and permissions. Use it when setting up IAM, ADC, or service accounts for local code and production workloads. Claude Code Gemini CLI CX Codex 15,450installs google-cloud-recipe-onboarding official Google LLC Guides a developer through a first Google Cloud project: CLI checks, sign-in, project setup and billing. It fits a personal first project. Claude Code Gemini CLI CX Codex 15,390installs cloud-sql-basics official google This skill helps create and explain Cloud SQL resources for MySQL, PostgreSQL, and SQL Server. Use it when setting up a database in Google Cloud. Claude Code Gemini CLI CX Codex 14,679installs google-cloud-waf-security official google This skill reviews Google Cloud workloads against the security pillar of the Well-Architected Framework and suggests actions for IAM, networks, data, and operations. Claude Code Gemini CLI CX Codex 14,620installs google-cloud-waf-cost-optimization official google Reviews Google Cloud workloads through the Well-Architected Cost Optimization pillar. Use it to inspect spending, resize resources, assess discounts, or find idle capacity. Claude Code Gemini CLI CX Codex 14,266installs

Similar

helm-chart-scaffolding Seth Hobson This skill helps create and maintain Helm charts for Kubernetes, build reusable templates, and prepare deployments for multiple environments. Claude Code CX Codex Cursor 11,964installs python-resilience Seth Hobson A Python skill for retries, timeouts, backoff, and transient failure handling. Use it when external services or network calls need bounded recovery. Claude Code CX Codex Cursor 11,755installs gitops-workflow Seth Hobson This skill guides Kubernetes GitOps setup with ArgoCD or Flux. Use it to deploy from Git and keep cluster state aligned with declarative configuration. Claude Code CX Codex Cursor 11,650installs dependabot official github A GitHub Copilot skill that helps write and tune .github/dependabot.yml: grouped updates, monorepo patterns, security updates. GitHub Copilot 4,400installs python-observability Seth Hobson A skill that gives your agent Python observability patterns: structured logging, Prometheus metrics, distributed tracing. Useful when production breaks and the logs don't tell you where. Claude Code CX Codex Cursor 11,547installs wizard Matt Pocock This skill creates an interactive bash wizard for manual setup steps, CI secrets, third-party dashboards, and one-off migrations. Claude Code 553,369installs hyperframes-cli heygen-com Controls HyperFrames video workflows from the CLI: audits layouts and contrast, edits timeline clips, captures snapshots, and renders locally or in cloud runtimes. Claude Code CX Codex Cursor +1 1,200,000installs setup-pre-commit Matt Pocock This skill configures pre-commit checks for a JavaScript repository, running Prettier, type checking, and tests before each commit. Claude Code 489,289installs

Questions about cloud-monitoring-promql-query

How do I install cloud-monitoring-promql-query in Claude Code?

Run npx skills add google/skills --skill cloud-monitoring-promql-query -a claude-code. The skill file is placed at ~/.claude/skills/cloud-monitoring-promql-query/SKILL.md.

What does cloud-monitoring-promql-query do?

It generates PromQL queries and aggregations from Cloud Monitoring metric descriptors and resource parameters. The result uses the metric type, value type, metric kind, and compatible monitored resource.

Does cloud-monitoring-promql-query need a Google Cloud Project ID?

Yes. The skill checks for a Project ID before using Google Cloud lookups. It cannot continue when the ID is unavailable from the request or environment.

Source text

SKILL.md · Apache-2.0
---
name: cloud-monitoring-promql-query
metadata:
  version: "1.0.1"
  category: CloudObservabilityAndMonitoring
description: >-
  Generates valid PromQL queries from Cloud Monitoring metric descriptors and
  resource parameters. Use when asked to create, generate, write, or format
  PromQL queries, PromQL strings, or PromQL aggregations for Cloud Monitoring
  metrics and resources. Don't use for raw metric discovery or metric selection.
---

# Cloud Monitoring PromQL Generator

Use this skill to generate a valid PromQL query from any Cloud Monitoring metric
type. This guide applies to all Cloud Monitoring metric types by mapping Cloud
Monitoring metric and resource descriptors to PromQL structures.

## Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:cloud-monitoring-promql-query)"`
and append `agent-skills/1.0 (skill:cloud-monitoring-promql-query)` to `User-Agent` headers.

## Workflow

### Resolve Project ID (CRITICAL & BLOCKING)

Before performing any other actions (such as searching code, reading references,
or running validation), you MUST verify whether the Google Cloud Project ID is
available:

1.  **Check Prompt/Payload**: Look for the Project ID in the user's prompt or
    input.
2.  **Check Environment**: If the Project ID is not present in the prompt, you
    MUST run `gcloud config get-value project` to attempt to resolve it from the
    environment.
3.  **Ask for Clarification (BLOCKING)**: If the Project ID is not in the prompt
    AND the `gcloud` command fails, returns an empty string, or is unavailable,
    you MUST immediately stop. Do NOT generate a PromQL query, do not run the
    validation script, and do not use placeholders (like `YOUR_PROJECT_ID`). You
    must refuse to proceed and ask the user to provide the Project ID.

### Inspect Metric and Resource Descriptors

1.  **Use Provided Descriptors First**: If the user's prompt already includes
    metric descriptor details (such as `metric.type`, `metricKind`, `valueType`,
    or `monitoredResourceTypes`) or specific resource filter values, use those
    values directly instead of calling the Cloud Monitoring API.
2.  **Discover Missing Descriptors**: If exact metric descriptors
    (`metric.type`, `metricKind`, `valueType`) are missing or underspecified,
    resolve the target metric type's descriptor using one of these paths:
    *   **Vague Query**: If the prompt is vague (for example, `"VM CPU usage"`),
        use the `cloud-monitoring-metric-selection` skill first to identify the
        specific metric type.
    *   **Known Metric Type**: If you already have the specific metric type name
        (for example, `compute.googleapis.com/instance/cpu/utilization`) but
        need its descriptor, call the
        `google-cloud-monitoring:list_metric_descriptors` MCP tool. If the tool
        is missing, refer to the `cloud-monitoring-metric-selection` skill to
        configure the Cloud Monitoring MCP server.
    *   **Fallback**: If the MCP tool cannot be configured, fall back to making
        a direct Cloud Monitoring API call.
3.  **Identify Key Fields**: From the retrieved descriptor, identify four key
    schema attributes:
    *   **`type`**: The Cloud Monitoring metric type string.
    *   **`metricKind`**: `GAUGE`, `DELTA`, or `CUMULATIVE`.
    *   **`valueType`**: `INT64`, `DOUBLE`, `DISTRIBUTION`, or `BOOL`.
    *   **`monitoredResourceTypes`**: Compatible `resource.type` strings
        required for resource scoping and grouping.

### Resolve Resource Filters & Discovery Protocol

To filter data by a specific resource instance, apply these resource rules and
discovery protocols:

1.  **Monitored Resource Filter**: Always include the
    `monitored_resource="<type>"` filter in your query to prevent collisions
    across services that share metric names.
    *   **Example**: `monitored_resource="gae_app"`
2.  **Preserve User Literals (CRITICAL)**: ALWAYS use the literal resource
    names, namespaces, and IDs provided in the user's prompt. Do **NOT**
    override or replace these values with active resource names found during
    Cloud Monitoring discovery unless the user explicitly asked you to find
    active resources. Telemetry discovery must only be used to identify metric
    type names and label keys, not to override user input.
3.  **Resource Identifier Mapping**:
    *   **Direct & Specific Keys**: Use the most specific resource identifier
        available. **Example**: `version_id`, `cluster_name`.
    *   **Name-to-ID Resolution**: If the user filters by a resource *name*
        (such as `"instance-1"`), but the resource schema uses numeric IDs (like
        `instance_id`), use PromQL string name labels instead of numeric ID
        labels. **Example**: `instance_name`, `metadata_system_name`.
    *   **Composite Identifiers**: For resources with hierarchical identifiers
        (such as Cloud SQL databases), format the filter as a single composite
        key. Do NOT split them into separate `project_id` and sub-resource
        labels. **Example**: `database_id="{project_id}:{instance_name}"`.
4.  **Resource Label Discovery**: The
    `google-cloud-monitoring:list_metric_descriptors` tool only returns
    metric-specific labels. If the label schema for a monitored resource is
    unknown, fetch the resource descriptor directly from the Cloud Monitoring v3
    REST API (`projects.monitoredResourceDescriptors.get`):

    ```bash
    TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || gcloud auth print-access-token)
    curl -s -H "Authorization: Bearer ${TOKEN}" \
    "https://monitoring.googleapis.com/v3/projects/{project_id}/monitoredResourceDescriptors/{monitored_resource_type}"
    ```

    An HTTP 200 OK response returns the `MonitoredResourceDescriptor` object
    containing the `labels` array with the exact resource label keys for that
    resource.

### Choose Aggregation Structure & Defaults

The query structure and aggregation functions (such as `rate`,
`histogram_quantile`, `sum`, or `avg`) depend on the metric type and how it is
visualized.

1.  **Consult the Reference**: Consult the
    [Cloud Monitoring to PromQL Basic Aggregations Reference](references/basic_aggregations.md)
    as the single source of truth to map Cloud Monitoring properties (Metric
    Kind, Value Type, Aligner, Reducer) to their PromQL structures.
2.  **SRE Aggregation & Visualization Rules**:
    *   **Do NOT sum or average ratio/percentage utilization metrics** (like CPU
        % or Memory limit utilization) across resource instances. Instead, keep
        them unaggregated (raw metric), group by instance, or wrap in `topk(30,
        avg_over_time(...))`.
    *   **State Label Filtering (CRITICAL)**: Only the metrics
        `agent.googleapis.com/memory/percent_used` and
        `agent.googleapis.com/disk/percent_used` require `{state!="free"}`. Do
        **NOT** filter by `{state="used"}`.

### Format & Validate Query

Before presenting any PromQL queries, validate them using the linter:

#### Python Dependencies

Before executing the validation script (`scripts/validate_promql.py`), install
the required Python dependencies:

```bash
python3 -c "import promql_parser" || pip install promql-parser
```

#### Validation Procedure

1.  **Format Constraints**:
    *   **Metric Name Normalization**: Convert Cloud Monitoring metric types to
        PromQL metric names using this recipe:
        1.  **Split Domain and Path**: Split the Cloud Monitoring metric type by
            the first slash (`/`) to separate the domain from the path.
            *   **Example**:
                `storage.googleapis.com/network/received_bytes_count` -> domain
                `storage.googleapis.com`, path `network/received_bytes_count`
        2.  **Normalize Domain**: Replace all periods (`.`) in the domain with
            underscores (`_`).
            *   **Example**: `storage.googleapis.com` ->
                `storage_googleapis_com`
        3.  **Normalize Path**: Replace all periods (`.`) and slashes (`/`) in
            the path with underscores (`_`).
            *   **Example**: `network/received_bytes_count` ->
                `network_received_bytes_count`
        4.  **Join with Colon**: Join the normalized domain and normalized path
            with a colon (`:`).
            *   **Example**:
                `storage_googleapis_com:network_received_bytes_count`
        5.  **Native Prometheus Metrics**: If the metric type has no slash, keep
            it as-is.
            *   **Example**: `up` -> `up`, `http_requests_total` ->
                `http_requests_total`
        6.  **Distribution Suffix**: If the metric's `valueType` is
            `DISTRIBUTION`, append `_bucket` to the end of the normalized name.
            *   **Example**:
                `cloudfunctions.googleapis.com/function/execution_times` ->
                `cloudfunctions_googleapis_com:function_execution_times_bucket`
    *   Ensure the final query is a **single line with no comments** (no `#` or
        `//`). Cloud Monitoring query translation collapses whitespace and can
        cause code trailing a comment to be ignored or throw parsing errors.
    *   **Grouping Clause Syntax**: Ensure grouping clauses (such as `by
        (label)`) only follow aggregation operators (such as `sum`, `avg`,
        `min`, `max`, or `count`). Never place a grouping clause directly after
        a metric selector.
        *   **Incorrect**: `metric{...} by (label)`
        *   **Correct**: `sum(rate(metric{...}[5m])) by (label)`
    *   **Fenced Output Code Block**: ALWAYS wrap the final verified PromQL
        query in a fenced `promql` code block in your final response.
2.  **Linter Verification**:
    *   Validate all generated queries in a single batch: `python3
        <path_to_skill>/scripts/validate_promql.py --query '<q1>' '<q2>'`
    *   If validation fails, read
        [PromQL Error Recovery Guide](references/promql_error_recovery.md) to
        diagnose and fix common type mismatches and syntax errors before
        repeating the loop.

## References

*   [Cloud Monitoring PromQL Basic Aggregations Reference](references/basic_aggregations.md)
*   [Cloud Monitoring PromQL Error Recovery Guide](references/promql_error_recovery.md)
*   [Cloud Monitoring PromQL Documentation](https://docs.cloud.google.com/monitoring/promql.md.txt)
*   [Cloud Monitoring Monitored Resource Types Reference](https://docs.cloud.google.com/monitoring/api/resources.md.txt)

© google · Apache-2.0 · google/skills

See also

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor