← Plugin catalog
Developer Tools

Better Stack

Better Stack, Inc. v1.3.14

Incidents, logs and metrics

Create a free account to save this plugin.

From the developer

Declared capabilities

  • Read
  • Write

Declared limitations

  • Unrelated request. The plugin should not be used: ChatGPT answers without calling Better Stack tools.
  • Bulk destructive request. The plugin has no bulk delete, so it should not delete anything. It explains that and points to the Better Stack dashboard, or asks which single monitor is meant.
  • Another organization's data. The plugin only sees the Better Stack teams the signed-in user belongs to, so it says it can't access other companies' accounts.

Not specified in the available declarations: pricing & account requirements.

Onboarding example

Show me all monitors that are currently down.

View onboarding source →

Sources & dates

Developer declarations; not independently tested. Listing last checked Nov 17, 2026. Package observed Nov 17, 2026.

View package source →

Description

From the marketplace listing

Investigate incidents, check who is on call, manage uptime monitors, query logs, metrics, traces, errors and real user monitoring (RUM), and build dashboards with your Better Stack Incidents and Telemetry data.

Language: English · Automatically detected from descriptions.

Matches for “errors”

Exact text from the indicated source. A mention alone does not establish support for your task.

Publisher full description

Investigate incidents, check who is on call, manage uptime monitors, query logs, metrics, traces, errors and real user monitoring (RUM), and build dashboards with your Better Stack Incidents and Telemetry data.

What changed

· 8 observations

Capabilities & instructions

Supporting files updated; open the comparison for details. Skill instructions changed from “CloudWatch Translation below) 4. **Derive tag names from the query:** - PromQL `by (label)` → `label('label')` (Prometheus labels keep their names) -...” to “`references/cloudwatch-translation.md`) 4. **Derive tag names from...

View comparison →
Capabilities & instructions

Supporting files updated; open the comparison for details. Skill instructions changed from “Charts filter through **template variables**, referenced in chart SQL two ways: - `{{var}}` — **required**: interpolated inline; the variable MUST resolve to...” to “Read `references/template-variables.md` (in this skill's...

View comparison →
Capabilities & instructions

Full description changed from “Claude Code, Claude chat and Cowork, Claude Tag in Slack).” to “Antigravity, Claude Code, Claude chat and Cowork, Claude Tag in Slack). Once connected, suggests what to set up next from what the account has, such as...”. Skill instructions changed from “Claude Code, Claude chat and...

View comparison →
Capabilities & instructions

Supporting files updated; open the comparison for details. Skill instructions changed from “-------------------------- | -------------- | | `percent` | Percentage (0-1 to 0-100%) | 75% | | `auto` | Auto-detect | varies | | `none` | Raw number |...” to “------------------------------------------ |...

View comparison →
Capabilities & instructions

Skill instructions changed from “(CPU > 90%, errors > 100) | `value`, `operator` | | `relative` | Value changes by percentage vs. the past (traffic drops 50%) | `value`, `operator`,...” to “(disk > 90%, error rate > 5%) | `value`, `operator` | | `relative` | Change in % vs. the past, when the user asks for one |...

View comparison →
Capabilities & instructions

Logo url dark changed from “https://files.openai.com/content?id=file_00000000636c8211a30ea66c1e4e7505” to “https://files.openai.com/content?id=file_0000000025e081f5aa0177e7fca2d656”. Skill “connect-betterstack” description changed from “Claude Code, Claude chat and Cowork, Claude Tag in Slack).” to “Antigravity,...

View comparison →

Technical updates · 1

Package or technical metadata updated

View technical comparison →

· 3 observations

Capabilities & instructions

App-6aa02bd506908191bbf12fc2ec2f3161 updated; open the comparison for details. Betterstack updated; open the comparison for details. Full description changed from “Observability for AI agents: query your logs, traces, metrics, and errors with SQL, build dashboards and chart alerts, manage uptime monitors, respond...

View comparison →
Capabilities & instructions

App-6aa02bd506908191bbf12fc2ec2f3161 updated; open the comparison for details. Betterstack updated; open the comparison for details. Full description changed from “Observability for AI agents: query your logs, traces, metrics, and errors with SQL, build dashboards and chart alerts, manage uptime monitors, respond...

View comparison →

Technical updates · 1

Package or technical metadata updated

View technical comparison →

Keywords

Files & skills

File archives

Plugin package31 files · 106 KBBrowse files →
Skill instructions
chart-alerts13 KB

View saved version →

---
name: chart-alerts
description: Guide for creating and managing Better Stack chart alerts. Load when asked to set up alerting, create alerts on charts, or configure monitoring thresholds.
---

# Chart Alerts Guide

Chart alerts monitor metrics and logs queries and trigger incidents when conditions are met. They are attached to charts on dashboards or explorations. `chart_alert_help` has the server's current reference.

> **Two-tier thresholds:** a chart alert holds a single `value`. To reproduce a Datadog warning + critical monitor, create **two** alerts on the same chart (one per threshold).

## Alert Types

| Type           | Use Case                                                     | Key Parameters                                             |
| -------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
| `threshold`    | Known fixed limit exceeded (disk > 90%, error rate > 5%)     | `value`, `operator`                                        |
| `relative`     | Change in % vs. the past, when the user asks for one         | `value`, `operator`, `query_period`                        |
| `anomaly_rrcf` | Unusual patterns (ML-based), with a floor by default (below) | `shown_interval`, `anomaly_sensitivity`, `anomaly_trigger` |

## What to Alert On

Unless the user asks otherwise, every alert fires only on something both bad and unusual:

- **Outcomes, not activity**: orders completed, jobs finished, age of the oldest queued job. A stuck
  worker that retries every 2 s keeps emitting spans and requests while nothing gets done.
- **Saturation** (memory, disk, connection pools): `threshold`, since it is bad at the same level every day.
- **Customer impact** (error rate, latency, failed checkouts, orders dropping): `threshold`; for a
  drop, `lower_than` a value under the quietest normal hour. An anomaly or relative alert learns a
  sustained change as the new normal and resolves within about an hour while the outage goes on.
- **Anything else unusual**: `anomaly_rrcf` with a floor.
- **Slices**: group error and latency charts by endpoint or error type. Each series is checked on its
  own, so a failure in one slice crosses the bar instead of hiding in the whole-traffic average.
- **Low-traffic services** (a few requests per second or fewer): a ratio jumps on a handful of
  requests; alert on error counts instead.

## Operators

| Operator               | Description                            | Alert Types         |
| ---------------------- | -------------------------------------- | ------------------- |
| `higher_than`          | Value exceeds threshold                | threshold, relative |
| `lower_than`           | Value below threshold                  | threshold, relative |
| `higher_than_or_equal` | Value >= threshold                     | threshold, relative |
| `lower_than_or_equal`  | Value <= threshold                     | threshold, relative |
| `equal`                | Value equals threshold                 | threshold, relative |
| `increases_by`         | Value increases by X%                  | relative only       |
| `decreases_by`         | Value decreases by X%                  | relative only       |
| `changes_by`           | Value changes by X% (either direction) | relative only       |

## Chart Requirements

Only certain chart types support alerts:

| Chart Type     | Requirements                                   |
| -------------- | ---------------------------------------------- |
| `line_chart`   | Must be timeseries, query must have `{{time}}` |
| `bar_chart`    | Must be timeseries, query must have `{{time}}` |
| `number_chart` | Query must have `{{time}}`                     |
| `tail_chart`   | No additional requirements                     |

**Prefer line charts on dashboards** for alerts - they provide the best visibility into metric trends and make it easy to correlate alerts with visual data.

## Key Param

Preview of the first 4,000 characters. Read full instructions →

chart-generation22 KB

View saved version →

---
name: chart-generation
description: Complete reference for chart types, units, and settings on Better Stack dashboards. Load right before creating charts - after the queries are built with the query skills.
---

# Chart Generation Guide

This guide covers everything needed to create properly configured charts using the `add_chart_to_dashboard` and `edit_chart` tools. `chart_building_help` has the server's current reference.

To make a chart **filterable**, define a template variable with `set_dashboard_variable`, then reference it in the query as `{{var}}` (required) or `[[ ... {{var}} ... ]]` (optional). See the `dashboard-builder` skill's "Dashboard template variables" section.

## Chart Types

| Type                | Use Case                                                   | Key Requirement                                                                              |
| ------------------- | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `line_chart`        | Time-series trends, metrics over time                      | Query must have `time` column                                                                |
| `bar_chart`         | Comparisons, distributions                                 | Works with time or categories                                                                |
| `number_chart`      | Single KPI, current value                                  | Shows latest/aggregated value                                                                |
| `table_chart`       | Detailed data, logs, breakdowns                            | Any columnar data                                                                            |
| `pie_chart`         | Distribution, proportions                                  | Needs series + value columns                                                                 |
| `heatmap_chart`     | Correlation, density over time                             | Needs time, series, value                                                                    |
| `scatter_chart`     | Correlation between variables                              | X/Y numeric columns                                                                          |
| `gauge_chart`       | Percentage metrics (0-1 range)                             | Single value, use `unit: "percent"`                                                          |
| `map_chart`         | Geographic distribution (by IP, airport, city, or country) | Value column + a `location()` column, grouped by location. Load `map-hierarchy-charts` skill |
| `hierarchy_chart`   | Fleet overview — one colored hexagon per entity (host map) | One row per entity: value column + label column. Load `map-hierarchy-charts` skill           |
| `static_text_chart` | Markdown text, notes, documentation                        | Pass Markdown in `query` param                                                               |

See `metrics-query` skill for query syntax.

Funnels (`funnel_chart`, `funnel_trend_chart`) are not dashboard charts: they live in Explore, built from steps in the Better Stack UI.

## Units Reference

### Data Size

| Unit                         | Description                |
| ---------------------------- | -------------------------- |
| `B_si`                       | Bytes (SI: KB, MB, GB)     |
| `B_iec`                      | Bytes (IEC: KiB, MiB, GiB) |
| `kB`, `MB`, `GB`, `TB`, `PB` | Fixed unit                 |

### Data Transfer Rate

| Unit                         | Description                                   |
| ---------------------------- | --------------------------------------------- |
| `B_si/s`                     | Bytes per second (auto-scale)                 |
| `kB/s`, `MB/s`, `GB/s`       | Fixed rate unit                               |
| `bit_si/s`                   | Bits per second (auto-scale: bps, kbps, 

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 1 — file references are metadata, not package contents.

chart-styling11.6 KB

View saved version →

---
name: chart-styling
description: Better Stack chart styling and advanced settings reference - series colors and order, number chart coloring thresholds, heatmap color categories, gauge bounds, y-axis tuning, custom units, and the per-key settings table with cross-setting gotchas. Load when configuring how a chart looks beyond defaults, or when unsure which settings key applies to a chart type.
---

# Chart Styling & Advanced Settings

Detailed reference for the `settings` keys the chart tools accept beyond the basics covered in the `chart-generation` skill. The tool schema deliberately keeps its descriptions terse — this file is the authority on semantics, defaults, and per-type applicability.

## Per-key reference

| Key                                  | Applies to                          | Values / default                                                                | Notes                                                                                                                                                      |
| ------------------------------------ | ----------------------------------- | ------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `unit` + `custom_unit`               | all except table                    | any supported unit / `auto`                                                     | `custom_unit: true` renders `unit` verbatim as a literal suffix, no auto-scaling                                                                           |
| `decimal_places`                     | all                                 | number, default `2`                                                             |                                                                                                                                                            |
| `time_column`                        | line, bar, number, scatter, heatmap | default `"time"`                                                                | The X-axis column despite the name; category bar charts point it at the grouping column                                                                    |
| `x_axis_type`                        | line, bar, scatter, heatmap         | `time` (default), `value`, `category`                                           | line: time/value; bar & heatmap: time/category; scatter: all three                                                                                         |
| `y_axis_type`                        | scatter only                        | `value` (default), `category`                                                   |                                                                                                                                                            |
| `point_size_column`                  | scatter only                        | default `"size"`                                                                | Column whose value sizes each point                                                                                                                        |
| `y_axis_min` / `y_axis_max`          | line, bar                           | numbers                                                                         | `y_axis_max: 1` for 0-1 ratios with percent unit                                                                                                           |
| `y_axis_auto_range`                  | line only                           | `include_zero` (default), `fit_data`                                            | `fit_data` for values far from zero; hidden when `y_axis_scale` is `log`                                                                                   |
| `y_axis_scale`                       | line, bar, scatter                  | `linear` (d

Preview of the first 4,000 characters. Read full instructions →

collector-queries9.39 KB

View saved version →

---
name: collector-queries
description: Proven metrics queries for Better Stack Collector sources (the source tool's Platform "Collector") - per-host node_* metrics, per-container and per-service container_resources_*, requests and errors by destination, TCP health, and the container-level saturation checks that host averages hide. Load after metrics-query when the source platform is Collector, for health checks, resource questions and service dashboards.
---

# Collector sources: proven queries

Taken from the Hosts and Services dashboard templates; every metric and label below was verified on a live Collector source. Queries use `{{source}}`, `{{time}}`, `{{start_time}}`, `{{end_time}}` exactly as `metrics-query` describes: as written in dashboard charts, substituted in ad-hoc `query` calls.

## What the collector emits

- Every infrastructure metric carries `_host`, `_service`, `_container`; `_container` is the readable container name (`namespace/pod/container` on Kubernetes). Prefer these `container_*` and `node_*` families over the OTel `container.*` (dotted, docker-stats) family, whose labels are resource attributes.
- Per host, node exporter: `node_cpu_seconds_total` (`mode`, `cpu`), `node_memory_*_bytes`, `node_load1/5/15`, `node_disk_*` (`device`), `node_filesystem_*` (`mountpoint`, `fstype`), `node_network_*` (`device`), `node_pressure_{cpu,io,memory}_{waiting,stalled}_seconds_total`, `node_vmstat_oom_kill`, `node_procs_{running,blocked}`, `node_netstat_Tcp*`.
- Per container: `container_resources_cpu_usage_seconds_total`, `_cpu_limit_cores`, `_cpu_throttled_seconds_total`, `_cpu_delay_seconds_total`, `_memory_rss_bytes`, `_memory_cache_bytes`, `_memory_limit_bytes`, `_{cpu,memory,io}_pressure_waiting_seconds_total` (`kind` is `some` or `full`; filter one), `_disk_{used,size}_bytes` (`mount_point`, `device`), `container_oom_kills_total`, `container_restarts_total`.
- Per container and peer (`actual_destination` is ip:port): `container_net_tcp_active_connections`, `_successful_connects_total`, `_failed_connects_total` (`destination`), `_retransmits_total`, `_bytes_{sent,received}_total`; requests `container_{http,postgres,redis,kafka,zookeeper,...}_{requests,queries}_total` (`status`) with `_duration_seconds_total` histograms; `container_dns_requests_total` (`domain`, `status`).
- Maps: `container_net_tcp_listen_info` (`listen_addr` to `_container` and `_service`), `ip_to_fqdn` (`ip` to `fqdn`). Join them to name the peers in dependency and RED questions (see Requests and errors by destination).
- Span-derived metric `duration` with `service`, `kind`, `root`, `error`, `http_status`, `span_name`: the metrics-plane error rate and latency of the instrumented applications.

## Host

CPU busy per host (rates by mode, then one minus the idle share):

```sql
WITH per_mode AS (
  SELECT {{time}} AS time, label('_host') AS host, label('mode') AS mode, avgMerge(rate_avg) AS v
  FROM {{source}}
  WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}} AND name = 'node_cpu_seconds_total'
  GROUP BY time, host, mode
)
SELECT time, host AS series, 1 - sumIf(v, mode = 'idle') / nullIf(sum(v), 0) AS "CPU busy"
FROM per_mode GROUP BY time, host ORDER BY time
```

Add `sumIf(v, mode = 'iowait') / sum(v)` and `mode = 'system'` for IO wait and the kernel share.

Memory (`unit: B_iec`, or the ratio with `percent`):

```sql
SELECT {{time}} AS time,
  avgMergeIf(value_avg, name = 'node_memory_MemTotal_bytes') - avgMergeIf(value_avg, name = 'node_memory_MemAvailable_bytes') AS "Used",
  avgMergeIf(value_avg, name = 'node_memory_MemAvailable_bytes') AS "Available"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
  AND name IN ('node_memory_MemTotal_bytes', 'node_memory_MemAvailable_bytes')
GROUP BY time ORDER BY time
```

Swap: `node_memory_SwapTotal_bytes`, `node_memory_SwapFree_bytes`; a zero total means nothing stands between memory pressure and the OOM killer.

Load per core: `avgMergeIf(value_avg, name = 'node_load1

Preview of the first 4,000 characters. Read full instructions →

connect-betterstack11.8 KB

View saved version →

---
name: connect-betterstack
description: Connect the Better Stack MCP server and check that it works. Use when the user installs the Better Stack plugin or asks to set it up, when a Better Stack request comes in but no Better Stack tools (such as `incidents`, `monitors`, `query`, `documentation`) are available, or when a Better Stack tool fails with "unauthorized", 401 or "needs authentication". Tells the user exactly how to connect in the app they are using (ChatGPT, Codex, Cursor, Antigravity, Claude Code, Claude chat and Cowork, Claude Tag in Slack). Once connected, suggests what to set up next from what the account has, such as Claude investigating every new incident or fixing errors on a schedule. Also use when the user asks what Better Stack can do for them.
---

# Connect Better Stack

The Better Stack plugin brings skills, and its tools come from the Better Stack MCP server at `https://mcp.betterstack.com`. The server lists no tools until the user signs in with their Better Stack account (OAuth in the browser, no token needed). Until then the skills can't read any data.

## 1. Check whether Better Stack is connected

Look at the tools you have right now.

- **Connected:** you have Better Stack tools, such as `incidents`, `monitors`, `on_calls`, `sources`, `query` or `documentation`. Their names may carry a prefix (`mcp__plugin_betterstack_betterstack__incidents`, `betterstack.incidents`, `betterstack_betterstack/incidents`). Confirm with one cheap read-only call: `incidents` with `status: ["ongoing"]`, or `monitors`. If it returns data (even an empty list), say Better Stack is connected and carry on with what the user asked.
- **Not connected:** no Better Stack tools at all, only an `authenticate` tool for Better Stack, or a call that fails with `unauthorized`, 401, 403 or "needs authentication".

Several Better Stack servers can show up at once, and each kind signs in differently:

- **The Better Stack connector** from the user's Claude account: tool names start with `mcp__claude_ai_`. It signs in at [claude.ai/customize/connectors/yours](https://claude.ai/customize/connectors/yours).
- **The plugin's own server**: tool names start with `mcp__plugin_betterstack_betterstack__`, and `/mcp` lists it as `plugin:betterstack:betterstack`.
- **A server the user added themselves** under a name of their own, such as `betterstack`. `/mcp` lists it under that name.

If any one of them answers, Better Stack is connected: use it, and don't mention the others. When more than one answers, use the connector, then the plugin's server.

Claude Code connects to each address once: a server the user added themselves comes first, then the plugin's server, then the connector. So a server the user added with the address `https://mcp.betterstack.com` hides the plugin's server and the connector, and `/mcp` shows the connector as hidden. If that server is the one that needs a sign-in, say so by its name. The user can sign in to it from `/mcp`, or remove it (`claude mcp remove <name>`) so Claude Code uses the connector.

If you have a Better Stack `authenticate` tool, call it and give the user the sign-in link it returns. After they sign in, call `complete_authentication` if that tool exists, then check again.

Never make up incidents, monitors, logs or metrics while Better Stack isn't connected. Say it isn't connected and give the steps below.

## 2. Work out where you are running

Use what you know about your environment: your system prompt, your tool names, whether you have a shell, and where the conversation is happening.

| Signs | You are in |
| --- | --- |
| You are ChatGPT, in chatgpt.com or the ChatGPT app, no shell | ChatGPT |
| You are Codex, or you have a shell and `codex` is installed | Codex |
| You are in Cursor, or tool names look like Cursor's | Cursor |
| You are Antigravity, Google's agent, in its app, IDE or `agy` CLI | Antigravity |
| You are Claude Code, you have a shell, tool names start with `mcp__` | Claude Code |
| Yo

Preview of the first 4,000 characters. Read full instructions →

dashboard-builder18.8 KB

View saved version →

---
name: dashboard-builder
description: Guide for building Better Stack dashboards. Load when asked to create a dashboard or add multiple charts in Better Stack.
---

# Dashboard Builder Guide

Dashboards only run metrics queries - never raw logs/traces queries. Log and span volumes are still available there: `sum(logs_count)` / `sum(spans_count)`, grouped by any label the source extracts (`level`, `service`, logs-to-metrics labels) - see `metrics-query`.
Only a log field that is not extracted needs a detour: suggest [Explore](https://telemetry.betterstack.com/team/t0/explore-logs/new) for one-off visualizations, or extracting it with logs-to-metrics - [Docs](https://betterstack.com/docs/logs/dashboards/logs-to-metrics) - to chart it on a dashboard

**Related skills:**

- `dashboard-layout` - Layout rules, row templates, coordinate math, planning process
- `metrics-query` - Query syntax, merge functions, time filters
- `chart-generation` - Chart types, units, axis settings

## Process

1. **Explore available prebuilt templates** - Find dashboard templates and offer building it based on given dashboard template, if available
2. **Plan the structure** - Decide what metrics/areas to cover before creating anything
3. **Plan or validate the layout** — load the `dashboard-layout` skill (it has the row templates and the six layout rules). Then:
   - **Building from scratch**: follow `dashboard-layout`'s planning process to draft the section/row structure.
   - **Building from a pre-existing plan** (e.g. a plan file the user gives you): treat the plan's layout as **untrusted input**. Walk every section's row spec against `dashboard-layout` Rules 3-6 BEFORE you add any chart. The most common plan-side violation: a `w:12` chart paired with a `w:6 + w:6` row above it (orphan-row + full-width, breaks Rules 3 and 4 at once). When you find a violation, propose the fix (e.g. three charts at `w:4+w:4+w:4`) and patch the plan (or flag it to the user) — never silently implement a layout that breaks the rules.
4. **Validate queries** - Run each query with `query` to verify data exists and values make sense (substitute the template variables as `metrics-query` describes)
5. **Build incrementally** - Add charts one by one in row order, verify each works
6. **Verify structure** - After finishing the generation - check if its structured logically, and if there aren't any useless or unrelated charts. Verify even after using prebuilt templates to make sure that source works with that, and it covers all requested features

## Query Validation

**Always execute queries before adding charts — this is mandatory, not optional.**

1. Run query with `query`
2. Check: Does the query SUCCEED (no `Unknown expression`, no `Code: 47`, no `function not found`)?
3. Check: Does data exist? Are values reasonable?
4. Only then add chart with `add_chart_to_dashboard`

**A chart with a broken query cannot be added.** If the query returns "no data found" or an error, fix the query (different aggregation, different metric, different filter) or drop the chart and tell the user about the gap. Do not add a chart whose query you have not successfully executed against real data.

Common issues:

- 100% CPU constantly -> wrong metric or calculation
- No data -> wrong time range or source doesn't have this data, or wrong aggregation state (e.g. `quantilesMerge` on a metric that doesn't populate `value_quantiles`)
- Single flat line -> missing GROUP BY time
- `Unknown expression identifier` -> the aggregation function doesn't exist for this source / metric — pick a different one or revisit the plan

## Default Behavior

If no specific instructions provided, create a **comprehensive health-check dashboard** that covers the main areas available for the source:

1. First, use `source` to understand what data is available
2. Use `metrics_schema` to discover available metrics for the platform
3. Cover key areas: resource usage, performance, errors/logs (whatever applies to the source

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 1 — file references are metadata, not package contents.

dashboard-layout10.4 KB

View saved version →

---
name: dashboard-layout
description: Definitive guide for Better Stack dashboard layout — grid system, layout rules, row templates, planning process, coordinate math, section manipulation. Load when creating or modifying dashboard layouts.
---

# Dashboard Layout Guide

This is the single source of truth for all layout decisions. Referenced by the `dashboard-builder` and `grafana-import` skills.

## Grid System

Better Stack dashboards use a **12-column grid**. Charts have `(x, y, w, h)` coordinates:

- `x`: column position (0-11)
- `y`: row position (0-based)
- `w`: width in columns (must sum to 12 per row)
- `h`: height in rows (always 6 — see Height section)

**Section headers** occupy exactly 1 row of height (h=1) in the y-coordinate space. Charts in a section start at `section_y + 1`.

## Height

**ALL charts use `height: 6`.** Always pass `height: 6` explicitly — the default is 8, which is too tall.

### Minimum chart heights

| Min Height | Chart Types                                                                             |
| ---------- | --------------------------------------------------------------------------------------- |
| 6 units    | `line_chart`, `bar_chart`, `scatter_chart`, `heatmap_chart`, `gauge_chart`, `map_chart` |
| 4 units    | `pie_chart`, `number_chart`, `table_chart`, `tail_chart`                                |
| 2 units    | `static_text_chart`, `text_chart`                                                       |
| 1 unit     | sections                                                                                |

## Layout Rules (priority order)

These rules are ranked. When two rules conflict, the higher-priority rule wins.

**Rule 1 (highest): No vertical gaps.** Every row must be filled. No empty rows between charts within a section.

**Rule 2: No horizontal empty space.** Every row must sum to exactly 12 width units. No gaps on the right side.

**Rule 3: No full-width charts.** A single chart spanning w:12 is almost always wrong. If you have a lone chart, pull it up to share a row with another chart, or push it down to join the next row. Exception: tables or heatmaps that genuinely need the full width.

**Rule 4: No orphan rows.** If the last row has fewer charts than the rows above, merge it into the previous row. Up to 4 charts per row is fine.

**Rule 5: Even widths within a row.** Charts sharing a row should be equal width when possible:

- 2 charts -> w:6 + w:6
- 3 charts -> w:4 + w:4 + w:4
- 4 charts -> w:3 + w:3 + w:3 + w:3

Relax this only if needed to satisfy Rules 1-4.

**Rule 6: Prefer 3 charts per row.** This is the ideal density. 2 per row is acceptable for line charts. 4 per row is acceptable for number/gauge charts. 1 per row is a last resort.

## Number Chart (KPI) Rules

Number charts are compact — they should NEVER be as wide as line/bar charts:

- **Maximum width: w:4.** Number charts should be w:3 (default) or w:4. Never wider.
- **Mixed rows:** When a number chart shares a row with a line/bar chart, make the number chart narrow and give the remaining space to the line/bar chart.

Examples:

- 1 number + 1 line -> Number(w:3) + Line(w:9) = 12
- 1 number + 2 lines -> Number(w:3) + Line(w:5) + Line(w:4) = 12
- 2 numbers + 1 line -> Number(w:3) + Number(w:3) + Line(w:6) = 12

## Row Templates

Use these pre-approved row configurations:

```
3 line/bar charts:        w:4 + w:4 + w:4 = 12   (best overall)
2 line/bar charts:        w:6 + w:6 = 12          (acceptable)
4 number charts:          w:3 + w:3 + w:3 + w:3 = 12
3 number charts:          w:4 + w:4 + w:4 = 12
1 number + 1 line:        w:3 + w:9 = 12          (number stays narrow)
2 numbers + 1 line:       w:3 + w:3 + w:6 = 12
3 numbers + 1 line:       w:2 + w:2 + w:2 + w:6 = 12  (line takes half)
1 number + 2 lines:       w:3 + w:5 + w:4 = 12    (or w:4 + w:4 + w:4)
4 mixed (overflow merge):  w:3 + w:3 + w:3 + w:3 = 12
```

## Layout Planning Process (MANDATORY)

Charts auto-position left-to-right, top-to-botto

Preview of the first 4,000 characters. Read full instructions →

errors-query5.82 KB

View saved version →

---
name: errors-query
description: Load BEFORE querying Better Stack exception or error-pattern data with SQL - exception counts, trends, first/last occurrence, affected users, raw stack traces. Contains instructions for querying errors/exceptions.
---

# Querying exceptions (Errors sources)

## Where the query runs

Better Stack runs SQL in two places, and the query text differs:

- **Dashboard charts and chart alerts** (`add_chart_to_dashboard`, `edit_chart`, `create_chart_alert`): write the query as this skill shows it, with the template variables `{{source}}`, `{{time}}`, `{{start_time}}` and `{{end_time}}`. The dashboard resolves them. Chart queries always read the source's metrics collection.
- **Ad-hoc queries** (`query`, `render_chart`): there are no template variables. First call the help tool for the data type with the source ID (`query_help` for logs and spans, `metrics_query_help` for metrics, `errors_query_help` for errors): it names the source's collections and the table to pass. Put the collection where `{{source}}` stands (e.g. `remote(t123_my_app_logs)` for the last ~30 minutes, `s3Cluster(primary, t123_my_app_s3)` with its row-type filter for older rows), a bucket such as `toStartOfInterval(dt, INTERVAL 5 MINUTE)` where `{{time}}` stands, and concrete bounds such as `dt > now() - INTERVAL 3 HOUR` for `{{start_time}}` and `{{end_time}}`. Add a `LIMIT`, and call `query_windows` before an `s3Cluster(...)` query over more than a few hours.

Error tracking has two data planes:

- **Occurrences** (this skill): ClickHouse - pre-aggregated exception metrics and raw exception events
- **State**: triage status (resolved/unresolved, who changed it, when) is returned ONLY by `errors` / `error` and changed with `update_error_state`. Never infer state from SQL.
- **Issues**: Linear/Jira issues linked to an error are listed by `error`; attach or file one with `link_error_issue` / `create_error_issue` (through the team's Better Stack integration, so state changes post comments on the issue), detach with `unlink_error_issue`.

## Exception metrics (counts, trends, first/last seen)

Query the application's metrics collection (`errors_query_help` names it). The schema is **fixed for all Errors sources** - query it directly, no field discovery needed:

- **Count exceptions with `sum(exceptions_count)`.** `exceptions_count` is a plain `UInt64` per-row column: the number of exceptions in that row. Aggregate it with `sum(...)`, **never** `countMerge(...)` (it is not an aggregate-state column). It self-scopes - it is `0` on non-exception rows - so you do **not** need a `_row_type` filter to isolate exceptions.
- **Never count exceptions with `countMerge(events_count)`.** `events_count` totals _every_ row type (spans, logs, web events, exceptions) and double-counts span event vs. duration rows, so it over-counts exceptions. Reach for it only when you deliberately want all row types at once.
- `pattern` - plain column holding the error-group hash: the same hash `errors` returns and `error` takes. Filter on it to scope any query to one error group
- `environment` - plain column (`production`, `staging`, ...)
- Aggregate-state columns (use their Merge function): `uniqMerge(user_uniq)` affected users, `minMerge(seen_at_min)` / `maxMerge(seen_at_max)` exact first/last occurrence, `anyLastMerge(type_last)` / `anyLastMerge(message_last)` / `anyLastMerge(call_site_file_last)` / `anyLastMerge(call_site_function_last)` group metadata

Exceptions over time:

```sql
SELECT {{time}} AS time,
  sum(exceptions_count) AS "Exceptions"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY time
ORDER BY time
```

Per-pattern trend with readable labels ("errors by pattern"): there is no plain `message` column - group by `pattern` (the stable identity) and label the series with the message merge column. No hash-to-message mapping needed:

```sql
SELECT {{time}} AS time,
  anyLastMerge(message_last) AS series,
  sum(exceptions_c

Preview of the first 4,000 characters. Read full instructions →

grafana-import20.4 KB

View saved version →

---
name: grafana-import
description: Import Grafana dashboards from grafana.com templates. Translates PromQL to ClickHouse. Load when user asks to import, convert, or recreate a Grafana dashboard in Better Stack.
---

# Grafana Dashboard Import

## Quick Start

```bash
# 1. Get summary first (always start here)
node <this skill's directory>/scripts/extract-layout.js --dashboard <ID> --summary
node <this skill's directory>/scripts/extract-layout.js --file <path> --summary

# 2. Extract and build section-by-section
node <this skill's directory>/scripts/extract-layout.js --dashboard <ID> --section 1
# ... build section 1 charts ...
node <this skill's directory>/scripts/extract-layout.js --dashboard <ID> --section 2
# ... build section 2 charts ... and so on
```

## Tool Setup

You need the Better Stack dashboard tools (`create_dashboard`, `add_chart_to_dashboard`, `set_dashboard_variable`) and the query tools (`sources`, `source`, `metrics_schema`, `query`). If your client loads tools on demand, load them before starting.

The extract script is `scripts/extract-layout.js` in this skill's directory, run with Node.js 18 or newer. If you can't run scripts, read the export yourself and pull out the same fields: sections, panels, their queries, units and template variables.

## Workflow

1. **Extract summary:** `node scripts/extract-layout.js --dashboard <ID> --summary` — see all sections and panel counts
2. **Check metrics:** `metrics_schema(id)` — identify available metrics AND their tags
3. **Discover tag names:** `SELECT DISTINCT tags FROM {{source}} WHERE name = 'your.first.metric' LIMIT 5` — use exact tag names from real data, never guess
4. **Create dashboard:** `create_dashboard(source_id, name)`
5. **Translate template variables** — For each `templating.list` entry, create a Better Stack variable with `set_dashboard_variable` AND reference it in the queries that used `$name` via an optional `[[ ]]` clause. Never just omit them. See Template Variable Translation below.
6. **Process section-by-section** — For each section:
   - Extract: `node scripts/extract-layout.js --dashboard <ID> --section <n>`
   - Build queries using translation rules below (load `metrics-query` skill)
   - Validate each query via `query` before creating charts
   - Add charts (load `chart-generation` + `dashboard-builder` skills), always pass `height: 6` and `section: "Name"`
   - Move to next section only after completing current one

**Query translation checklist:**

- Identify datasource type (Prometheus or CloudWatch) from extract output
- For PromQL: match `rate()`/`irate()` to correct merge function, handle `sum by`/`avg by` aggregations
- For CloudWatch: match `statistics` field (Average/Sum/Maximum/Minimum) to correct merge function
- Check for multi-metric arithmetic (`a / b`) requiring CTEs

### No-data mode (blind import)

**Use ONLY when explicitly requested** (e.g., "import without data", "no metrics available", "blind import"). Never default to this mode — always try the normal workflow first.

When the service has no metric data in Better Stack, you cannot validate queries. Instead:

1. **Extract layout** as normal with the extract script
2. **Skip `metrics_schema`** — you can't discover metrics or tags from live data
3. **Derive metric names from the Grafana query:**
   - PromQL metrics: use as-is (Prometheus metrics keep their exact names in Better Stack)
   - CloudWatch metrics: translate `namespace/metricName` → underscore format with suffix (see `references/cloudwatch-translation.md`)
4. **Derive tag names from the query:**
   - PromQL `by (label)` → `label('label')` (Prometheus labels keep their names)
   - CloudWatch `dimensions` → `label('snake_case')` (CloudWatch tags are snake_case)
5. **Build queries using known patterns** — follow ALL translation rules from this skill
6. **Self-review every query before creating the chart:**
   - Re-read the SQL character by character
   - Check: Does `{{time}}` only appear where `dt` is in s

Preview of the first 4,000 characters. Read full instructions →

Referenced files: 3 — file references are metadata, not package contents.

health-check3.02 KB

View saved version →

---
name: health-check
description: Quick health assessment of servers or services (databases, webservers) from their Better Stack telemetry. Checks metrics, logs, dependencies for anomalies. Use for "how is Nginx and Redis doing?" questions, not incident diagnosis.
---

# Health check of service

Applies to full servers or specific services (e.g., database, Redis, webserver). Prefer charts (`render_chart`) when presenting results - show a chart and a short comment, e.g. how CPU or memory is doing.

## Step 1: Find the source

Call `sources` to find the server's or service's sources, then `source` for each: its platform, its services and which data (logs, spans, metrics) it has. Keep progress notes short while you collect data.

## Default Parameters

- **Time window:** Last 3 hours (unless user specifies otherwise)

## What to Check

### 1. Metrics Anomalies

- Resource saturation spikes (CPU, memory, disk, network)
- Latency increases for certain services (p50/p95/p99)
- Error rate changes
- Throughput drops

Compare current values against the 3-hour baseline. Flag deviations.

### 2. Log Distribution

Query log counts by level over time:

- Sudden increase in error/warn logs?
- Drop in info logs (service stopped logging)?
- New log patterns appearing?
- Is there a spike in logs count by any level?

Group by `_pattern` (the message with IDs and numbers stripped) to see which kinds of lines are new or spiking; `query_help` has the syntax.

### 3. Dependencies

From spans (`spans-query`) or, on a Collector source, the requests-by-destination queries in `collector-queries`, check:

- Request rate, error rate and latency between services
- Dependencies showing elevated error rates
- Latency spikes between services

## Output

Provide a simple overview of system's health, show visualizations about key metrics and point out potential issues and your finding.

For each key metric (load, memory, disk, network, ...), repeat this rhythm:

1. Write the `### <Metric name>` heading
2. Call `render_chart` with that metric's query (a real tool call; writing the tool's name in text renders nothing)
3. Write 1-2 sentences interpreting what the chart shows

Chart each metric once, in the summary, not while collecting data. One chart at a time: chart, then its comment, then the next heading. Never a wall of text describing charts that were never rendered.

## Collector sources

When `source` reports platform Collector, load `collector-queries`: it carries the proven host queries (CPU, memory, load, disk, network, pressure) and the per-container pass (usage against limits, throttling, pressure, OOM kills, restarts) that host averages hide, plus the "keeping up" rubric for the verdict. Compare the 3-hour window against the same window a day earlier before calling a level normal. Ratios stay 0-1 with `unit: "percent"`; bytes stay raw with `B_iec`. Syntax: `metrics-query`.

## If Anomalies Found

1. Report findings with specifics (timestamps, values)
2. Ask user: "Want me to investigate deeper?"
3. If yes → load the `investigate-incident` skill and continue
investigate-incident7.99 KB

View saved version →

---
name: investigate-incident
description: Investigate a Better Stack incident, alert or outage report end to end. Find the incident, check who is on call, drill into the metrics, logs, traces and errors around it, correlate with recent releases, and post a short situation report. Use when someone asks why something is down, slow or erroring, mentions a Better Stack incident, monitor or alert, or when Claude is working as an on-call first responder in an incident channel (for example in Claude Tag).
---

# Investigate an incident with Better Stack

You are the first responder. Tell the humans what is broken, since when, how bad it is and the most likely root cause, backed by data from Better Stack. Stay read-only unless someone in the thread explicitly asks you to act.

## Core principle: drill down

Start broad, find the anomaly, then narrow the focus. Aggregated data hides details.

```
BROAD SCAN (hours/days) → FIND ANOMALY → NARROW WINDOW (minutes) → COMPARE WINDOWS
```

- Time-series queries aggregate into buckets, so a 2-minute spike disappears in 1-hour buckets. When something looks interesting, query it again with a narrower window and smaller buckets.
- Check metrics before logs. Metrics quickly show what is anomalous and when ("memory spiked at 14:32"). Use that timing to target the log search.

## Phase 1: Orient

- **Clarify the symptom:** slow, erroring, down, or intermittent?
- **Establish the timeline:** when did it start, and was it sudden or gradual?
- **Check the existing context:**
  - Given an incident link or ID, call `incident`, `incident_timeline` and `incident_comments`. Otherwise call `incidents` with `status: ["ongoing", "acknowledged"]`, narrowed with `cause`, `monitor_id` or `from`/`to`.
  - Call `chart_alerts` to see which telemetry alerts are firing.
  - For a monitor incident, call `monitor`, then `monitor_response_times` and `monitor_availability`, to tell a total outage from a regional one or a latency-only one.
  - Call `on_calls` and `on_call` to see who is on call. If the incident is escalating, call `escalation_policy` to see who gets paged next.
- Don't repeat what the incident comments already say.

## Phase 2: Scope

- Call `sources` to find the affected service's sources, then `source` for its details, and `source_fields` to see which fields exist.
- For errors, call `applications` and then `errors` for the affected application.

Form a hypothesis based on the symptom:

| Symptom | Primary suspects | Start with |
| --- | --- | --- |
| Slow responses | CPU, memory, DB queries, network | Metrics: latency, resource saturation |
| Errors / 5xx | App bugs, dependency failures, OOM | Errors → metrics → logs |
| Intermittent issues | Resource contention, connection limits, GC | Metric spikes + log correlation |
| Complete outage | Crash, network partition, config change | Monitor checks, recent log events |
| After a deploy | Recent code, config or dependency changes | `releases`, then the diff if GitHub is connected |

## Phase 3: Investigate

**Before writing any SQL, call the help tool for that data type.** The query syntax is specific and will fail without it:

- logs and spans: `query_help` (with `source_type: "logs"` or `"spans"`)
- metrics: `metrics_schema` (filter by name, e.g. `*latency*`, `*memory*`) and `metrics_query_help`
- errors: `errors_query_help` (for custom error analytics beyond `errors` and `error`)

Then run the SQL with `query`. Bound every query in time, and call `query_windows` before querying more than a few hours.

**Metrics:**
- Resource saturation: CPU, memory, disk, network
- Application: request rate, error rate, latency (p50/p95/p99)
- Dependencies: DB connection pool, queue depth

**Logs and spans:**
- Error clustering: which messages are new or spiking? Group by message or error type over time rather than reading raw lines first.
- Log level distribution: count by level per minute to find the error spike.
- Timeline reconstruction: what happened right before 

Preview of the first 4,000 characters. Read full instructions →

logs-query7.76 KB

View saved version →

---
name: logs-query
description: MUST load BEFORE writing any Better Stack logs or web-events SQL query. Contains required syntax for raw-event queries - without this, queries will fail. Compatible with Explore. Also load when the user asks how raw-event queries look.
---

# Logs Query Building Guide

## Where the query runs

These queries read raw events, so they run ad hoc through `query` and `render_chart`; dashboard charts only read the metrics collection (see `dashboard-builder` for log and span volumes there). `query` and `render_chart` take no template variables. First call `query_help` with the source ID: it names the source's collections and the table to pass. Put the collection where `{{source}}` stands (e.g. `remote(t123_my_app_logs)` for the last ~30 minutes, `s3Cluster(primary, t123_my_app_s3)` with its row-type filter for older rows), a bucket such as `toStartOfInterval(dt, INTERVAL 5 MINUTE)` where `{{time}}` stands, and concrete bounds such as `dt > now() - INTERVAL 3 HOUR` for `{{start_time}}` and `{{end_time}}`. Add a `LIMIT`, and call `query_windows` before an `s3Cluster(...)` query over more than a few hours.

## Quick Reference

| Need             | Pattern                                                                  |
| ---------------- | ------------------------------------------------------------------------ |
| Source           | `FROM {{source}}`                                                        |
| Time filter      | `WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}`                 |
| Time bucket      | `{{time}} AS time`                                                       |
| Service filter   | `<service expression> = 'service-name'`                                  |
| Group by service | `<service expression> AS series`                                         |
| Extract field    | `JSONExtractCaseInsensitive(raw, 'field', 'Nullable(String)')`           |
| Nested field     | `JSONExtractCaseInsensitive(raw, 'parent', 'child', 'Nullable(String)')` |
| Keyword search   | `positionCaseInsensitive(field, 'keyword') > 0`                          |

## Critical Rules

### 1. Log Data is in `raw` Column (JSON)

```sql
-- Always use JSONExtractCaseInsensitive with Nullable types
JSONExtractCaseInsensitive(raw, 'level', 'Nullable(String)') AS log_level
JSONExtractCaseInsensitive(raw, 'metadata', 'user_id', 'Nullable(Int32)') AS user_id

-- Fields with dots in name: use single string (NOT separate args)
JSONExtractCaseInsensitive(raw, 'field.with.dots', 'Nullable(String)')
```

List of fields coming from `source_fields` lists fields as which are nested in `raw` - always access using `JSONExtractCaseInsensitive(raw, 'nginx', 'agent', 'Nullable(String)')`, not `SELECT nginx.agent FROM {{source}}`

### 2. Use Template Variables

- `{{source}}` - table name (never hardcode)
- `{{time}}` - time bucket column (NOT `dt`)
- `{{start_time}}`, `{{end_time}}` - time range bounds

### Service filtering and grouping

`source` returns the source's **service name expression** (a `JSONExtractCaseInsensitive(...)` or `COALESCE(...)` snippet) - copy it verbatim into SELECT / WHERE / GROUP BY. A service listed there with its own `field:` is extracted from that path instead; never guess service field paths.

### 3. Standard Aggregations Only

Use `COUNT`, `AVG`, `SUM` - NOT `avgMerge`, `countMerge` (those are for pre-aggregated metrics).

### 4. Use Descriptive Column Aliases

Column aliases become chart legend labels. Use descriptive names instead of generic `value`.

```sql
-- BAD: Legend shows "value"
SELECT {{time}} AS time, COUNT(*) AS value FROM ...

-- GOOD: Legend shows "Error count"
SELECT {{time}} AS time, COUNT(*) AS "Error count" FROM ...
```

### 5. Point Lookups: Add a `raw LIKE` Prefilter

When filtering on one specific ID (session ID, trace_id, request ID, user ID), add a substring prefilter before the extraction:

```sql
AND raw LIKE '%YOUR_SESSION_ID%'
AND JSONExtractCaseInsensitive(raw, '

Preview of the first 4,000 characters. Read full instructions →

map-hierarchy-charts5.48 KB

View saved version →

---
name: map-hierarchy-charts
description: Query shapes and settings for Better Stack map_chart (geographic map) and hierarchy_chart (host map hexagons). MUST load before creating either chart type — on dashboards or in Explore.
---

# Map & Hierarchy Charts

Both are **not** time-series: the query returns one row per location/entity — **no `time` column, no `GROUP BY time`, no series**. `AS value` is fine for both — neither renders a legend, so the value alias is never displayed. Load the query skill for the data type first (`metrics-query` / `logs-query`).

## Map Charts (`map_chart`)

Plot a numeric value at geographic points on a world map. Select exactly two things — a numeric value and a location — and group by the location.

**Metrics:**

```sql
SELECT
  avgMerge(rate_avg) AS value,
  location(label('colo')) AS location
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
  AND name = 'cloudflare_zone_colocation_requests_total'
GROUP BY location
```

**Raw events (logs / web events, e.g. in Explore):**

```sql
SELECT
  COUNT(*) AS value,
  location(JSONExtractCaseInsensitive(raw, 'remote_ip', 'Nullable(String)')) AS location
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
GROUP BY location
```

- **`location(...)`** resolves a string to coordinates: an **IP** (`'1.1.1.1'`), **airport code** (`'JFK'`), **city** (`'San Francisco, CA'`), or **country** (`'US'`, `'UK'`) — typically a metric label (`location(label('colo'))`) or a raw event field. Explicit coordinates work too: `tuple(lat, lng, 'custom_label')`.
- The location expression must be aliased `AS location` and the value `AS value` (or set `location_column` / `value_columns` to match your aliases).

### Settings

| Setting           | Purpose                                                                                                                       | Default       |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `location_column` | Result column holding the `location()` tuple                                                                                  | `"location"`  |
| `value_columns`   | Single-entry array with the numeric value column                                                                              | `["value"]`   |
| `location_label`  | `"automatic"` shows the closest city/country in tooltips; `"original_value"` shows the raw input (the IP, airport code, etc.) | `"automatic"` |
| `unit`            | Value formatting                                                                                                              | `"auto"`      |

Use `location_label: "original_value"` when the raw values matter to the reader (e.g. to see the actual IP addresses rather than the nearest city).

## Hierarchy Charts (`hierarchy_chart`)

Host maps: one colored hexagon per entity — host, service, pod — colored by a single numeric value on a min→max scale. Select a numeric value and an identifying label, one row per entity:

```sql
SELECT
  label('_host') AS host,
  avgMerge(value_avg) AS value
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
  AND name = 'system_cpu_utilization_ratio'
GROUP BY host
-- Settings: value_columns: ["value"], label_column: "host"
```

- The label column identifies each hexagon (shown inside it / in the tooltip); the single `value_columns` entry colors it.
- To nest hexagons into groups (e.g. by environment or region), select up to two extra label columns, add them to `GROUP BY`, and list them in `group_by_columns` (first = outer group, second = sub-cluster).

### Settings

| Setting                   | Purpose                                                                                                                             | Default                                  |
| ------------------------- | --------------------------------

Preview of the first 4,000 characters. Read full instructions →

metrics-query15.1 KB

View saved version →

---
name: metrics-query
description: MUST load BEFORE writing any Better Stack metrics SQL query. Better Stack's pre-aggregated metrics dialect (Merge functions, template variables, storage layouts, the ways a query silently blends series) - without it queries fail or return wrong numbers. Also load when the user asks how metrics queries look.
---

# Metrics Query Guide

Metrics tables hold pre-aggregated ClickHouse state columns. Below are the facts ClickHouse knowledge does not give you; everything else is standard SQL.

## Where the query runs

Better Stack runs SQL in two places, and the query text differs:

- **Dashboard charts and chart alerts** (`add_chart_to_dashboard`, `edit_chart`, `create_chart_alert`): write the query as this skill shows it, with the template variables `{{source}}`, `{{time}}`, `{{start_time}}` and `{{end_time}}`. The dashboard resolves them. Chart queries always read the source's metrics collection.
- **Ad-hoc queries** (`query`, `render_chart`): there are no template variables. First call the help tool for the data type with the source ID (`query_help` for logs and spans, `metrics_query_help` for metrics, `errors_query_help` for errors): it names the source's collections and the table to pass. Put the collection where `{{source}}` stands (e.g. `remote(t123_my_app_logs)` for the last ~30 minutes, `s3Cluster(primary, t123_my_app_s3)` with its row-type filter for older rows), a bucket such as `toStartOfInterval(dt, INTERVAL 5 MINUTE)` where `{{time}}` stands, and concrete bounds such as `dt > now() - INTERVAL 3 HOUR` for `{{start_time}}` and `{{end_time}}`. Add a `LIMIT`, and call `query_windows` before an `s3Cluster(...)` query over more than a few hours.

## Shape of a query

```sql
SELECT {{time}} AS time, avgMerge(value_avg) AS "Connected clients"
FROM {{source}}
WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}
  AND name = 'redis_connected_clients'
GROUP BY time
ORDER BY time
```

- `{{source}}` is the table, never a hardcoded name (dashboards may substitute a source variable such as `{{redis_source}}`). `{{time}}` is the time bucket, sized from the range: never `dt` as the series column, never a function around it (`toStartOfHour({{time}})` fails). In ad-hoc queries, see above.
- The metric column is `name`, not `metric` or `metric_name`.
- Aliases become chart legends: descriptive (`AS "Memory used"`), never `AS value`. Several values in one chart are named columns plus chart settings `value_columns: [...]`, `series_column: ""`.
- Tables and number charts drop `{{time}}` and `GROUP BY time`.

## Two storage layouts (`metrics_query_help` says which; copy its expressions)

- **Row-based** (ingested Prometheus/OTel metrics, most extracted metrics): every metric shares the state columns `value_avg`, `value_min`, `value_max`, `rate_avg`, `bucket_*`, `events_count` (no `value_sum`, no `value_last`), selected by `WHERE name = '...'`. There are no per-metric columns: `memory_total_bytes_max` does not exist, `maxMergeIf(value_max, name = 'memory_total_bytes')` does. Labels live in the `tags` map and are read with `label('key')`.
- **Column-based** (errors, RUM, warehouse, legacy migrated metrics): each metric has its own `<name>_<agg>` columns (`anyLast` maps to `<name>_last`: `anyLastMerge(replay_city_last)`), never appears in `name` (a `name` filter returns 0 rows), and labels are bare columns (`city`, not `label('city')`, which returns NULL there).

## Merge functions

- A state column is read only by its matching combinator: `avgMerge(value_avg)`, `minMerge(value_min)`, `maxMerge(value_max)`, `avgMerge(rate_avg)`, `sumMerge(bucket_sum)`, `countMerge(events_count)`; `anyLastMerge` exists only on column-based sources (`<name>_last`). `AVG(value_avg)`, `avgMerge(value)`, `sumMerge(rate_avg)` and `sumMerge(value_max)` fail with ILLEGAL_TYPE_OF_ARGUMENT. A total across series is `sum` of per-series merges in a two-level query (below), never `sumMerge`.
- **Count events with the per-row-type colum

Preview of the first 4,000 characters. Read full instructions →

spans-query11 KB

View saved version →

---
name: spans-query
description: MUST load BEFORE writing any Better Stack spans/traces SQL query. Contains required syntax for span queries - without this, queries will fail.
---

# Spans Query Building Guide

## Where the query runs

These queries read raw events, so they run ad hoc through `query` and `render_chart`; dashboard charts only read the metrics collection (see `dashboard-builder` for log and span volumes there). `query` and `render_chart` take no template variables. First call `query_help` with the source ID: it names the source's collections and the table to pass. Put the collection where `{{source}}` stands (e.g. `remote(t123_my_app_logs)` for the last ~30 minutes, `s3Cluster(primary, t123_my_app_s3)` with its row-type filter for older rows), a bucket such as `toStartOfInterval(dt, INTERVAL 5 MINUTE)` where `{{time}}` stands, and concrete bounds such as `dt > now() - INTERVAL 3 HOUR` for `{{start_time}}` and `{{end_time}}`. Add a `LIMIT`, and call `query_windows` before an `s3Cluster(...)` query over more than a few hours.

## Quick Reference

| Need             | Pattern                                                                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------- |
| Source           | `FROM {{source}}`                                                                                                       |
| Time filter      | `WHERE {{time}} BETWEEN {{start_time}} AND {{end_time}}`                                                                |
| Time bucket      | `{{time}} AS time`                                                                                                      |
| Service filter   | `<service expression> = 'service-name'`                                                                                 |
| Group by service | `<service expression> AS series`                                                                                        |
| Extract field    | `JSONExtract(raw, 'span', 'field', 'Nullable(String)')`                                                                 |
| Trace ID         | `JSONExtractString(raw, 'span', 'trace_id')`                                                                            |
| Span ID          | `JSONExtractString(raw, 'span', 'span_id')`                                                                             |
| Duration (ns)    | `JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64') - JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')` |

## Critical Rules

### 1. Span Data is in `raw` Column (JSON)

Spans follow OpenTelemetry format. All span fields are nested under `raw.span`, resource fields under `raw.resource`.

Enum values are stored as lowercase short names, not the proto constants: `kind` is `server` / `client` / `internal` / `producer` / `consumer` (never `SPAN_KIND_SERVER`), `status.code` is `ok` / `error` / `unset`.

```sql
-- Span fields (under "span" key)
JSONExtract(raw, 'span', 'trace_id', 'Nullable(String)') AS trace_id
JSONExtract(raw, 'span', 'span_id', 'Nullable(String)') AS span_id
JSONExtract(raw, 'span', 'parent_span_id', 'Nullable(String)') AS parent_span_id
JSONExtract(raw, 'span', 'name', 'Nullable(String)') AS span_name
JSONExtract(raw, 'span', 'kind', 'Nullable(String)') AS span_kind
JSONExtract(raw, 'span', 'root', 'Nullable(Boolean)') AS is_root

-- Duration (nanoseconds) - calculate from start/end
JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
  - JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64') AS duration_ns

-- Duration in milliseconds
(JSONExtract(raw, 'span', 'end_time_unix_nano', 'UInt64')
  - JSONExtract(raw, 'span', 'start_time_unix_nano', 'UInt64')) / 1000000 AS duration_ms

-- Status
JSONExtract(raw, 'span', 'status', 'code', 'Nullable(String)') AS status_code
```

### 2. Span Attributes (under `span.a

Preview of the first 4,000 characters. Read full instructions →

uptime-monitors9.26 KB

View saved version →

---
name: uptime-monitors
description: Reference for Better Stack Uptime monitors and escalation policies — monitor types, valid configuration values, how escalation policies work, and the limits of what the monitor tools can do. Load before using create_monitor, create_heartbeat, monitors, monitor, escalation_policies or escalation_policy.
---

# Uptime monitors & escalation policies

What the Uptime tools can do, the non-obvious rules, and where the limits are. A **monitor** is one Uptime check against a URL or host; when a check fails it opens an **incident** and alerts whoever the monitor's **escalation policy** routes it to.

## Tools at a glance

- `monitors`, `monitor` — read monitors.
- `monitor_availability`, `monitor_response_times` — a monitor's availability and response times, per region.
- `create_monitor` — create a monitor. `create_heartbeat` — create a heartbeat (below).
- `escalation_policies`, `escalation_policy` — read escalation policies (who gets paged).

Show the user what you are about to create and get a yes before calling a create tool: a new monitor starts checking, and alerting, right away.

There is **no update, pause/resume or delete tool**. You can create and read monitors, but not edit one in place (change its URL, frequency, alerting, etc.), pause, resume or remove it. You can read escalation policies but not create/edit them. To change a monitor, give the user its link from the tool result so they can adjust it in the Better Stack UI.

## Monitor types

`monitor_type` defaults to `status`. What the `url` field means depends on the type:

| Type                                    | Checks                                 | `url` is               | Extra field                      |
| --------------------------------------- | -------------------------------------- | ---------------------- | -------------------------------- |
| `status`                                | HTTP returns 2xx                       | full URL (`https://…`) | —                                |
| `expected_status_code`                  | HTTP returns one of the listed codes   | full URL               | `expected_status_codes`          |
| `keyword`                               | response body **contains** a word      | full URL               | `required_keyword`               |
| `keyword_absence`                       | response body is **missing** a word    | full URL               | `required_keyword`               |
| `ping`                                  | host answers ICMP ping                 | host (`example.com`)   | —                                |
| `tcp` / `udp` / `smtp` / `pop` / `imap` | a port answers                         | host                   | `port`                           |
| `dns`                                   | a DNS server answers                   | host (DNS server)      | `request_body` (domain to query) |
| `playwright`                            | a scripted browser/API scenario passes | scenario name          | the script (UI only)             |

**You can create every type except `playwright`**: `create_monitor` takes no script, so a Playwright monitor is set up in the Better Stack UI (see below). The port-based types (`tcp`, `udp`, `smtp`, `pop`, `imap`) need `port`.

**Heartbeats** (passive "ping us every N minutes" checks for cron jobs and workers) are created with `create_heartbeat`; the job then calls the heartbeat URL from the result on every successful run. **SSL-certificate** / **domain-expiration** monitors (they alert N days before expiry; valid windows are 1, 2, 3, 7, 14, 30, 60 days) **can't be created via these tools**: direct the user to the UI.

## Configuration you can set (and valid values)

`create_monitor` exposes a curated subset of monitor settings. Passing an invalid value is rejected, so stick to these:

- `check_frequency` (seconds): HTTP monitors **30, 45, 60, 120, 180, 300, 600, 900, 1800**; Playwright **60, 180, 300, 600, 900, 1800, 3600, …**. Sub-3-min

Preview of the first 4,000 characters. Read full instructions →

Package details

Publisher declarations from the archived package. These are separate from our research and the live service's terms.

Package license
MIT
Package author
Better Stack, Inc.
Keywords
See keywords
Getting started skill
./skills/connect-betterstack/SKILL.md
Review scenarios
5 positive · 3 negativeScenario counts, not test results.

Declared capabilities

  • Read
  • Write

Package observed Nov 17, 2026.

Technical details
First seen
Sep 30, 2026 · 22:02 UTC
Last seen
Nov 17, 2026 · 06:00 UTC
Latest observed change
Nov 13, 2026 · 12:08 UTC
Collection status
Collected

plugin_asdk_app_6aa02bd506908191bbf12fc2ec2f3161

Download plugin data (JSON)

Plugin details: freshly prepared. Prepared . Refreshed when plugin data changes or after 6 hours. Your account and Follow status are live.