Generated banner for Cloud Monitoring Chart Generation
Generated logo for Cloud Monitoring Chart Generation

Cloud Monitoring Chart Generation

GoogleOfficialPublished by Google

  • Skill
  • Tool integration
  • Cloud and DevOps
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Generates Cloud Monitoring Server-Driven UI (SDUI) Widget and XyChart Protocol Buffer textprotos on Google Cloud from resolved PromQL or ListTimeSeries queries. Use when: - Generating valid google.monitoring.dashboard.v1.Widget textprotos, containing PrometheusQuery or TimeSeriesFilter datasets, for use with the Cloud Monitoring Dashboards API, gcloud CLI, or declarative dashboard definitions. - Synthesizing Server-Driven UI (SDUI) widget titles, axis labels, and plot types for Prometheus or ListTimeSeries queries. Don't use for: - Metric discovery or PromQL query generation. For those tasks, use the cloud-monitoring-metric-selection or cloud-monitoring-promql-query skills.
— the description by Google

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow to transform metric queries into valid google.monitoring.dashboard.v1.Widget Protocol Buffer textprotos. It uses a multi-stage pipeline to synthesize semantic plot specifications, generate the corresponding textproto files, and validate the output against the original query parameters. It is designed for integration with the Cloud Monitoring Dashboards API, gcloud CLI, and declarative dashboard provisioning workflows.

What it does

  • Synthesizes titles, axis labels, and plot types for monitoring widgets.
  • Generates valid google.monitoring.dashboard.v1.Widget textprotos.
  • Supports both PrometheusQuery and TimeSeriesFilter dataset configurations.
  • Validates generated textprotos against input query strings and unit overrides.
  • Provides attribution headers for Google Cloud CLI and API interactions.

When to use it

  • When you need to create declarative dashboard definitions for Google Cloud Monitoring.
  • When you have resolved PromQL or ListTimeSeries queries that require visualization as a widget.
  • When you need to ensure widget configurations comply with the Cloud Monitoring Dashboards API schema.

Advantages

  • Ensures structural validity of dashboard widget definitions.
  • Automates the mapping of metric units to UCUM standards.
  • Provides built-in validation to prevent configuration errors.
  • Maintains consistency across dashboard provisioning pipelines.

Usage examples

“Generate a widget textproto for my CPU utilization PromQL query.”
The agent will run the synthesis pipeline, output a valid textproto block, and verify it against the provided PromQL query.
“Create a dashboard widget for this ListTimeSeries filter.”
The agent will process the filter string, generate the corresponding widget textproto, and validate the output file.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/google/cloud-monitoring-chart-generation/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip cloud-monitoring-chart-generation.zip -d .agents/skills

Documentation by Google

Cloud Monitoring Chart Generation Skill (cloud-monitoring-chart-generation)

Transforms PromQL or ListTimeSeries JSON request payloads and metric metadata into valid Server-Driven UI (SDUI) google.monitoring.dashboard.v1.Widget Protocol Buffer textprotos. These generated textprotos are designed to be ingested by the Cloud Monitoring Dashboards API, gcloud CLI, or declarative dashboard provisioning pipelines.

[!IMPORTANT] Preferred API & Mutually Exclusive Queries:

  • API Preference: Always prefer generating ListTimeSeries (time_series_filter) configurations for widgets over PromQL, unless the user explicitly requested PromQL or the metric math strictly requires it.

  • Mutually Exclusive: A widget dataset time_series_query must contain EITHER a time_series_filter OR a prometheus_query. You must never populate both fields in the same dataset simultaneously.

  • Strict Passthrough: You MUST copy the provided PromQL query or ListTimeSeries JSON exact filter string character-for-character. DO NOT invent, rewrite, or modify the queries under any circumstances.

[!CAUTION] CRITICAL EXECUTION & WORKING DIRECTORY RULES:

  • DO NOT CHANGE WORKING DIRECTORY: Keep your working directory at your workspace root. Do NOT cd into skill subdirectories.

  • NO DISCOVERY OR SEARCH RULE: The metric descriptor, PromQL query, ListTimeSeries JSON payload, unit, and resource type are ALWAYS present in the conversation context. NEVER run file or codebase search tools, like grep, find, directory listings, or codebase queries, to discover metric metadata or inspect repository structures.

  • SCRIPT EXECUTION: Execute the bundled Python scripts directly using python3.

  • OUTPUT GENERATION: The assemble_widget_proto script automatically generates a unique UUID-based filename to prevent parallel execution collisions. It will print the generated filename to standard error strongly prefixed with "Wrote widget textproto to:". You MUST parse this exact prefix from the logs to extract the generated path and use it for validation in Stage 4.

Attribution

MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read Usage Attribution. 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-chart-generation)" and append agent-skills/1.0 (skill:cloud-monitoring-chart-generation) to User-Agent headers.

Prerequisites: Environment Setup

Install the required dependencies in your environment or sandbox:

pip install -r scripts/requirements.txt

Follow the workflow pipeline

[ Stage 1: compute_labels ]  --->  [ Stage 2: LLM Synthesis ]  --->  [ Stage 3: assemble_widget_proto ]
  Generates candidate labels         Formulates SemanticPlotSpec       Emits validated widget textproto
Stage 1: Baseline Candidate Synthesis

Run Stage 1 using python3:

# For PromQL:
python3 scripts/compute_labels.py \
  --metric_display_name "METRIC_DISPLAY_NAME" \
  --resource_type "RESOURCE_TYPE" \
  --metric_unit "UNIT" \
  --promql_query 'PROMQL_QUERY'

# For ListTimeSeries:
python3 scripts/compute_labels.py \
  --metric_display_name "METRIC_DISPLAY_NAME" \
  --resource_type "RESOURCE_TYPE" \
  --metric_unit "UNIT" \
  --filter_string 'metric.type="m"...' \
  --per_series_aligner "ALIGN_RATE" \
  --cross_series_reducer "REDUCE_SUM"
Stage 2: SemanticPlotSpec Prediction (LLM)

Review the user prompt, PromQL or LTS query structure, and Stage 1 baseline candidates to formulate a 4-key SemanticPlotSpec JSON object:

  1. title: Polish titleCandidate to ensure it is concise, human-readable, and under 80 characters.

  2. yAxisLabel: Set this to a concise, human-readable quantitative descriptor or metric concept, like "Utilization", "Bytes", or "Bytes Rate". Do NOT append unit symbols or suffixes like "(%)", "(/s)", or "(By)" to the label, because units are rendered automatically via unitOverride.

  3. plotType: Default to LINE. Use STACKED_AREA if requested by the user or for distribution queries.

  4. unitOverride: Set this to the Unified Code for Units of Measure (UCUM) unit string, derived by applying the corresponding rules below:

List Time Series (LTS) Unit Strategy:
  • Trust the Candidate: For List Time Series flows, set this directly to the unitOverrideCandidate produced by Stage 1. Stage 1 mathematically processes ALIGN_RATE, for example producing By/s, forces % for ALIGN_PERCENT_CHANGE, and correctly outputs native normalizations unconditionally.

PromQL Unit Strategy (LLM Manual Override):

Because PromQL expressions can geometrically compose, for example histogram_quantile(..., rate(...)), rely on your own semantic reasoning to govern the final unit:

  • Rate Functions (rate(...), irate(...)): Convert cumulative counters into per-second rates. Append /s to the raw metric unit. For example, a raw metric unit of By with rate(...) results in unitOverride: "By/s".

    • Exception: If rate() is evaluated inside a histogram_quantile(), the output is the raw bucket unit like "s", not a rate.

  • Ratios & Percentages (100 * (A / B)): Ratios of identical metric units typically represent percentages, resulting in unitOverride: "%".

  • Normalizations: Normalize 10^2.% to "%".

  • Preserved Units: For simple aggregation functions like avg_over_time(...) or sum by (...), retain and output the underlying metric unit without modification.

  • Legend Template: Do NOT configure the legend_template field. It is intentionally omitted so that the Cloud Monitoring frontend dynamically renders its multi-column table legend at runtime.

Example SemanticPlotSpec:

{
  "title": "VM CPU Utilization us-central1-a",
  "yAxisLabel": "Utilization",
  "plotType": "LINE",
  "unitOverride": "%"
}
Stage 3: Protobuf Assembly & Output

Run Stage 3 using python3 to generate and save the widget textproto. Use --promql_query for PromQL, or --lts_request_json for ListTimeSeries:

# For PromQL:
python3 scripts/assemble_widget_proto.py \
  --promql_query 'PROMQL_QUERY' \
  --spec_json 'SEMANTIC_PLOT_SPEC_JSON'

# For ListTimeSeries:
python3 scripts/assemble_widget_proto.py \
  --lts_request_json '{"filter": "...", "aggregation": {...}}' \
  --spec_json 'SEMANTIC_PLOT_SPEC_JSON'

[!IMPORTANT] MANDATORY FILE OUTPUT CONTRACT: Do not attempt to guess or enforce the output filename. The script will automatically generate a guaranteed-unique filename and print it to standard error. Search stderr for the explicit prefix "Wrote widget textproto to:" to deterministically capture this filename, and then target it in Stage 4 validation.

  • Assigned Filename Feedback: Whenever an output file is saved, the script logs the file path to stderr. Read your command execution logs for the exact filename created so you can target it in Stage 4 validation.

  • Text Chat Output: Enclose the generated SDUI widget textproto inside a ```textproto code block in your response:

title: "..."
xy_chart {
  ...
}
Verify and auto-retry

[!CAUTION] DO NOT FINISH YOUR TURN UNTIL FILE VERIFICATION PASSES: 1. Validate Artifact: Execute the validator script against the generated file output from Stage 3:

   # For PromQL charts:
   python3 scripts/validate_chart.py --input_file "GENERATED_FILE.textproto" \
      --expected_promql_substring "SOME_IDENTIFYING_SUBSTRING_FROM_QUERY" \
      --expected_unit_override "UNIT_OVERRIDE_CANDIDATE"

   # For ListTimeSeries (LTS) charts:
   python3 scripts/validate_chart.py --input_file "GENERATED_FILE.textproto" \
      --expected_lts_filter_substring "SOME_IDENTIFYING_SUBSTRING_FROM_FILTER" \
      --expected_unit_override "UNIT_OVERRIDE_CANDIDATE"

   # ALWAYS provide an identifying substring and the Stage 1 unit override candidate to verify you didn't mutate the data.

CRITICAL: If you generated multiple charts for multiple metrics, you MUST run this validation script independently for EACH file generated to ensure every chart is correct!


2.  **Auto-Retry if Missing or Failed**: If `validate_chart` reports that the
    file is missing or invalid, verify your script parameters and immediately
    re-run Stage 3:

    ```bash
    python3 scripts/assemble_widget_proto.py \
      --promql_query 'PROMQL_QUERY' \
      --spec_json 'SEMANTIC_PLOT_SPEC_JSON'
    # Or use --lts_request_json if applicable
    ```
3. **Validation & Retries**: Run `validate_chart` to verify the generated
   textproto. If validation fails due to a schema or syntax error, correct
   the parameters and retry up to 2 times. If validation still fails after 2
   retries, stop retrying, notify the user of the validation error, and
   present the best-effort textproto.
4.  **Execution vs. Validation Errors**: Note that schema/syntax validation
    errors from `validate_chart.py` are distinct from OS or environment
    execution restrictions, which are handled below in **Graceful Sandbox
    Fallback**.
Perform graceful sandbox fallback

If compute_labels.py, assemble_widget_proto.py, or validate_chart.py cannot be executed due to environment or sandbox restrictions, do the following:

  1. Notify the user which script cannot be executed and why.

  2. Synthesize and output the complete widget textproto directly in your response, following all formatting and unit rules.

  3. Provide a "Local Verification" section containing the standalone python3 commands so the user can run and validate the schema locally if desired.

Files

scripts/assemble_widget_proto.py

"""Stage 3: Assembles and validates google.monitoring.dashboard.v1.Widget textproto."""

import argparse
import json
import os
import sys
import uuid

VALID_ALIGNERS = {
    "ALIGN_NONE",
    "ALIGN_DELTA",
    "ALIGN_RATE",
    "ALIGN_INTERPOLATE",
    "ALIGN_NEXT_OLDER",
    "ALIGN_MIN",
    "ALIGN_MAX",
    "ALIGN_MEAN",
    "ALIGN_COUNT",
    "ALIGN_SUM",
    "ALIGN_STDDEV",
    "ALIGN_COUNT_TRUE",
    "ALIGN_COUNT_FALSE",
    "ALIGN_FRACTION_TRUE",
    "ALIGN_PERCENTILE_99",
    "ALIGN_PERCENTILE_95",
    "ALIGN_PERCENTILE_50",
    "ALIGN_PERCENTILE_05",
    "ALIGN_PERCENT_CHANGE",
}

VALID_REDUCERS = {
    "REDUCE_NONE",
    "REDUCE_MEAN",
    "REDUCE_MIN",
    "REDUCE_MAX",
    "REDUCE_SUM",
    "REDUCE_STDDEV",
    "REDUCE_COUNT",
    "REDUCE_COUNT_TRUE",
    "REDUCE_COUNT_FALSE",
    "REDUCE_FRACTION_TRUE",
    "REDUCE_PERCENTILE_99",
    "REDUCE_PERCENTILE_95",
    "REDUCE_PERCENTILE_50",
    "REDUCE_PERCENTILE_05",
}

def format_proto_string(val: str) -> str:
  """Escapes and quotes a string for protobuf text format."""
  escaped = val.replace("\\", "\\\\").replace('"', '\\"')
  return f'"{escaped}"'


def parse_duration_seconds(duration_str: str) -> int:
  """Robustly parses a time duration string into seconds."""
  if not duration_str:
    raise ValueError("Empty duration_str provided to parse_duration_seconds")
  duration_str = str(duration_str).strip()
  try:
    if duration_str.endswith("s"):
      return int(float(duration_str.rstrip("s")))
    if duration_str.endswith("m"):
      return int(float(duration_str.rstrip("m")) * 60)
    if duration_str.endswith("h"):
      return int(float(duration_str.rstrip("h")) * 3600)
    if duration_str.endswith("d"):
      return int(float(duration_str.rstrip("d")) * 86400)
    return int(float(duration_str))
  except ValueError:
    raise ValueError(f"Unsupported duration format: {duration_str}")


def assemble_widget_textproto(
    title: str,
    promql_query: str,
    lts_filter: dict | None = None,
    plot_type: str = "LINE",
    y_axis_label: str = "",
    unit_override: str = "",
    scale: str = "LINEAR",
) -> str:
  """Assembles a valid Widget protobuf textproto string with omitted legend_template."""
  clean_title = title.strip()
  clean_promql = promql_query.strip()
  clean_plot_type = plot_type.strip().upper() if plot_type else "LINE"
  clean_scale = scale.strip().upper() if scale else "LINEAR"

  if clean_plot_type not in ("LINE", "STACKED_AREA", "STACKED_BAR", "HEATMAP"):
    clean_plot_type = "LINE"

  lines = [
      "widget {",
      f"  title: {format_proto_string(clean_title)}",
      "  xy_chart {",
      "    chart_options {",
      "      mode: COLOR",
      "    }",
      "    data_sets {",
      "      time_series_query {",
  ]
  if lts_filter:
    lines.extend([
        "        time_series_filter {",
        (
            "          filter:"
            f" {format_proto_string(lts_filter.get('filter', ''))}"
        ),
    ])
    agg = lts_filter.get("aggregation", {})
    if agg:
      lines.append("          aggregation {")
      if "alignmentPeriod" in agg:
        secs = parse_duration_seconds(agg["alignmentPeriod"])
        lines.extend([
            "            alignment_period {",
            f"              seconds: {secs}",
            "            }",
        ])
      if "perSeriesAligner" in agg:
        aligner = agg["perSeriesAligner"]
        if aligner not in VALID_ALIGNERS:
          raise ValueError(f"Invalid perSeriesAligner: {aligner}")
        lines.append(f"            per_series_aligner: {aligner}")
      if "crossSeriesReducer" in agg:
        reducer = agg["crossSeriesReducer"]
        if reducer not in VALID_REDUCERS:
          raise ValueError(f"Invalid crossSeriesReducer: {reducer}")
        lines.append(f"            cross_series_reducer: {reducer}")
      for gb in agg.get("groupByFields", []):
        lines.append(f"            group_by_fields: {format_proto_string(gb)}")
      lines.append("          }")
    lines.append("        }")
  else:
    lines.append(
        f"        prometheus_query: {format_proto_string(clean_promql)}"
    )

  if unit_override and unit_override.strip():
    lines.append(
        f"        unit_override: {format_proto_string(unit_override.strip())}"
    )

  lines.extend([
      "      }",
      f"      plot_type: {clean_plot_type}",
      "      target_axis: Y1",
      "    }",
      "    y_axis {",
  ])

  if y_axis_label and y_axis_label.strip():
    lines.append(f"      label: {format_proto_string(y_axis_label.strip())}")

  lines.extend([
      f"      scale: {clean_scale}",
      "    }",
      "  }",
      "}",
  ])

  return "\n".join(lines)


def get_auto_output_path(work_dir: str) -> str:
  """Safely generates a random, parallel-robust filename to avoid race conditions."""
  # Adjust for Google3 environments where the agent may run from the CitC client root
  # rather than the google3/ directory. This check is safely bypassed in public (GitHub)
  # environments because the google3/ directory will not exist. Internally, the workspace
  # contains a parent CitC directory (causing flakiness if the agent runs from there). Externally,
  # the Git checkout is the true root, so agents won't accidentally run from a parent wrapper.
  if not work_dir.endswith("google3") and os.path.basename(work_dir) != "google3":
    if os.path.exists(os.path.join(work_dir, "google3")):
      work_dir = os.path.join(work_dir, "google3")

  while True:
    random_id = uuid.uuid4().hex[:8]
    candidate = os.path.join(work_dir, f"chart_{random_id}.textproto")
    if not os.path.exists(candidate):
      return candidate

def main() -> None:
  parser = argparse.ArgumentParser(
      description="Stage 3 Server-Driven UI (SDUI) widget textproto assembler."
  )
  parser.add_argument(
      "--promql_query", "-q", default="", help="PromQL query expression."
  )
  parser.add_argument(
      "--lts_request_json",
      "-l",
      default="",
      help="ListTimeSeries request JSON.",
  )
  parser.add_argument("--title", "-t", default="", help="Widget chart title.")
  parser.add_argument(
      "--plot_type",
      "-p",
      default="LINE",
      help="Plot type (for example: LINE, STACKED_AREA).",
  )
  parser.add_argument(
      "--y_axis_label", "-y", default="", help="Y-axis label string."
  )
  parser.add_argument(
      "--unit_override",
      "-u",
      default="",
      help="Unit override string (for example: '%%', 'By/s').",
  )
  parser.add_argument(
      "--scale", "-s", default="LINEAR", help="Y-axis scale (LINEAR or LOG10)."
  )
  parser.add_argument(
      "--spec_json",
      "-j",
      default="",
      help="JSON string of SemanticPlotSpec from Stage 2.",
  )

  args = parser.parse_args()

  title = args.title
  plot_type = args.plot_type
  y_axis_label = args.y_axis_label
  unit_override = args.unit_override

  if args.spec_json:
    try:
      spec = json.loads(args.spec_json)
      if isinstance(spec, dict):
        title = spec.get("title", title)
        plot_type = spec.get("plotType", plot_type)
        y_axis_label = spec.get("yAxisLabel", y_axis_label)
        unit_override = spec.get("unitOverride", unit_override)
    except Exception:
      pass

  if not title:
    title = "Monitoring Chart"

  lts_filter = None
  if args.lts_request_json:
    try:
      lts_filter = json.loads(args.lts_request_json)
    except Exception as e:
      print(f"ERROR: Failed to parse LTS JSON payload: {e}", file=sys.stderr)
      sys.exit(1)

    if not lts_filter.get("filter"):
      print(
          "ERROR: Provided LTS JSON payload is missing the mandatory 'filter'"
          " key.",
          file=sys.stderr,
      )
      sys.exit(1)

  try:
    proto_text = assemble_widget_textproto(
        title=title,
        promql_query=args.promql_query,
        lts_filter=lts_filter,
        plot_type=plot_type,
        y_axis_label=y_axis_label,
        unit_override=unit_override,
        scale=args.scale,
    )
  except ValueError as e:
    print(f"ERROR: {e}", file=sys.stderr)
    sys.exit(1)

  print(proto_text)
  work_dir = os.environ.get("BUILD_WORKING_DIRECTORY", os.getcwd())
  output_path = get_auto_output_path(work_dir)

  with open(output_path, "w", encoding="utf-8") as f:
    f.write(proto_text)
  print(f"Wrote widget textproto to: {output_path}", file=sys.stderr)

if __name__ == "__main__":
  main()

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Google
Publisher
Google (Official)
Source
google/skills · skills/cloud/cloud-monitoring-chart-generation · commit 2194d3b
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download cloud-monitoring-chart-generation.zip