AWS Observability
AWSOfficialPublished by AWS
- Skill
- Tool integration
- Cloud and DevOps
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides comprehensive domain expertise for AWS observability, covering both classic CloudWatch and CloudWatch Omni. It assists users in investigating service health, querying logs and traces, configuring alerts, and managing dashboards. The skill is designed to help operators distinguish between the two services, navigate their respective APIs, and perform advanced tasks like agent quality evaluation and context graph analysis. It does not handle initial service setup or onboarding, which are managed by a separate dedicated skill.
What it does
- Investigates root causes using Omni context graphs and intelligence insights.
- Queries logs, traces, and metrics using SQL, PromQL, and Log Insights.
- Configures and tunes alerts, dashboards, and alarms for both CloudWatch and Omni.
- Evaluates AI agent quality through trace scoring and online evaluation.
- Provides methodology for service-health investigations and dependency analysis.
- Supports programmatic access via AWS CLI, SDKs, and CloudFormation.
When to use it
- When you need to investigate a service performance issue or root cause.
- When you need to write or debug queries for logs, traces, or metrics.
- When you need to create or update alerts and dashboards in CloudWatch or Omni.
- When you need to evaluate the quality of an AI agent using trace telemetry.
- When you need to understand service dependencies and blast radius.
Advantages
- Provides clear routing between CloudWatch and Omni based on service signals.
- Offers structured methodologies for complex observability tasks.
- Includes specific checklists to ensure all required configuration facts are surfaced.
- Maintains a strict scope to ensure accurate and relevant technical guidance.
- Supports advanced observability features like dynamic instrumentation and agent evaluation.
Usage examples
- “Why is my service experiencing high latency?”
- The agent will guide you through a service-health investigation, starting with relevant telemetry signals and checking for configuration issues like timeouts.
- “Create an Omni alert for high error rates.”
- The agent will provide the necessary authoring guidance, ask for your specific threshold and evaluation period, and confirm the configuration before proceeding.
- “How do I query my traces in Omni?”
- The agent will explain the SQL syntax for traces.default and provide the necessary fields to identify slow or failed spans.
- “Evaluate the quality of my AI agent's recent sessions.”
- The agent will help you select an appropriate evaluator and guide you through the process of scoring traces to assess agent performance.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/aws/aws-observability/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip aws-observability.zip -d .agents/skills
Documentation by AWS
AWS Observability
Overview
Domain expertise for AWS observability across metrics, logs, and traces, for two products that share the CloudWatch name but are separate services with separate control planes, data models, and APIs:
| CloudWatch | CloudWatch Omni | |
|---|---|---|
| What it is | Log groups, metric namespaces, alarms, Log Insights, X-Ray, Application Signals | Application Observability / Agent Observability. A Space per account per Region is the access boundary over the account's CloudWatch Dataset (OpenTelemetry logs, traces, and metrics); the Dataset is a CloudWatch resource the Space reads, not something the Space contains |
| Control plane | aws cloudwatch, aws logs, aws xray, aws application-signals | aws cloudwatchomni (endpoint prefix cloudwatch-omni, signing name cloudwatch) |
| Query | Log Insights query language; GetMetricData | SQL over logs.default / traces.default; PromQL over metrics; named views |
| Notify | Alarms (metric, composite, anomaly) | Alerts (SQL/PromQL rule, contributors, OK/WARNING/CRITICAL/NODATA) |
| Topology | Application Signals service map | Context graph (GetContextGraph) |
| Access | IAM only | Domain → Space → access grants and access profiles (set up in setting-up-cloudwatch-observability) |
| Only here | Dynamic Instrumentation, Synthetics canaries, CloudTrail auditing, EMF | Agent-quality evaluation, views, context graph |
| First-time setup | Application Signals onboarding — ADOT auto-instrumentation, the amazon-cloudwatch-observability add-on, ServiceEvents, CI/CD metadata | Domain → Space → grants → telemetry in → plain-ADOT instrumentation |
| References | references/cloudwatch/ | references/cloudwatch-omni/ |
This skill covers using both products, never setting either one up. Both first-time
setup paths above live in setting-up-cloudwatch-observability (same two-folder split);
route there rather than describing an onboarding procedure from memory.
Enabling Omni does not replace CloudWatch; log groups, metrics, and alarms keep working, and most customers use both.
Works best with the AWS MCP server — enables running CLI commands, querying CloudWatch, and validating configurations directly. All guidance also works with standard AWS CLI access.
Note: Reference files contain specific runtime versions, quota values, and feature matrices that may change. When precision matters (e.g. deploying to production, choosing a runtime, or checking a quota), confirm values against current AWS documentation rather than relying solely on the values in these files.
Scope guard — is this an observability request?
This skill owns the scope decision for every request routed to it, and this section is its sole home.
If a request is NOT about AWS observability with CloudWatch or CloudWatch Omni (weather, trivia, general chit-chat, non-observability coding), decline it in one sentence: state plainly that it is out of scope, never fabricate an answer, and never claim a false capability limitation (no "no internet access", no "no weather data") — the reason is simply that it is out of scope. Then redirect by naming what this skill does cover: querying CloudWatch and CloudWatch Omni logs, traces, and metrics, building dashboards, configuring alerts, investigating a service, or agent evaluation.
Do not attempt the off-topic task, and do not call a tool or run a query in pursuit of it. Keep it brief: no lecture, no long refusal.
Step 0 — CloudWatch or CloudWatch Omni?
Decide this before routing. The natural wording ("set up an alert for high latency", "build a dashboard", "query my logs") does not say which product the customer means.
The customer names the product — "Omni", "Application Observability", "Agent Observability", a Space, Domain, Dataset, access grant,
spaceId,cloudwatch-omni, Omni SQL, PromQL, views, context graph, evaluators, agent evaluation / scoring traces / online or continuous evaluation /gen_ai.evaluation, and OTel span vocabulary (traces.default,logs.default, spans,durationNano,status.code, resource attributes,service.name) → Omni. "Log Insights", "log group", "metric namespace", "CloudWatch alarm", "metric alarm", "composite alarm", "anomaly alarm", "X-Ray", "Application Signals", "canary", "CloudTrail", "Dynamic Instrumentation" → CloudWatch. A "log group" named inside an agent-evaluation request is the online-evaluation data source to verify, not a CloudWatch signal. A bare "alarm" (or "alert") with no other product signal is ambiguous — fall through to rule 3 and probe: a Space → Omni alert (alerts.md); no Space → CloudWatch alarm (cloudwatch/alarms.md). Exception: a "PromQL alarm" is a CloudWatch alarm on OTel metrics (cloudwatch/alarms.md) — "alarm" wins over "PromQL".Knowledge or how-to question ("what is an Omni alert", "does Omni have an API", "how do alerts differ from alarms") → answer from the reference files directly. Do not probe the account, and do not divert to the other product. Whether a capability exists is a fact about the product, not the account. concepts.md carries the full feature-equivalence matrix. 2a. Authoring / how-to alert request — "create / set up / write an Omni alert that fires when X", "how should I alert on Y" — with no Space or Region supplied and no go-ahead to actually create it, is a HOW-TO request. Deliver the authoring guidance (the alert row of "Must-state checklists" below, then alerts.md) FIRST, from the reference files. Do NOT stall on a Region/Space clarifying question and do NOT fall back to a CloudWatch alarm for a request that explicitly says "Omni alert". Probe the account only once the user supplies a Space/Region or asks you to create it. 2b. A telemetry object is already in the prompt — the user pastes, or the UI passes as context, a span, trace, log record, or query result and asks what it means, what errors it has, or how long it took. This is not a live-data request: do not probe the account, run a query, or ask the user to fetch it again. Read it in place per the "Reading a span or trace you already have" section of query/sql-logs-traces.md and state every item in its must-state list. 2c. A query request whose live result is empty or unreachable ("show me the slowest spans", "which traces failed") is still answered with the methodology — the exact query and the field rules that make it correct (see the must-state callouts in query/sql-logs-traces.md). Zero rows, a wrong-Region Space, or an unreachable endpoint is reported as a finding alongside the query, never as the whole answer.
Request that must act on live data, and the wording is ambiguous (not a Step 0.5 content question, which is answered from the catalog) → probe the target Region first:
aws cloudwatchomni list-domains aws cloudwatchomni list-spaces --region <target-region> --query "items[?region=='<target-region>']" # account-global; filter to the Regionlist-spacesis account-global (the--regionflag only selects the endpoint), so filter its result to the target Region as shown rather than reading a non-empty list as proof; a Space is one per account per Region. Seereferences/cloudwatch-omni/concepts.mdfor the full Region-probe rationale.A Domain and a Space in that Region (a non-empty filtered list) → Omni.
No Space in that Region (an empty filtered list) → CloudWatch: alarms → cloudwatch/alarms.md, dashboards → cloudwatch/dashboards.md, queries → cloudwatch/log-insights.md, metrics → cloudwatch/metrics.md. If the customer explicitly asked for Omni and has no Space, that is a first-time setup — see step 4.
The probe itself errors ("not yet supported", unknown service, endpoint does not resolve) → the CLI/SDK model in use lacks
cloudwatchomni. That is not evidence Omni is absent and must not be reported as "Omni is unavailable". The customer's installed AWS CLI/SDK most likely predates the service. If the request carried any Omni signal, give the customer the upgrade command to run (AWS CLI v2 reinstall orbrew upgrade awscli;pip install -U boto3 botocore) and have them re-runaws cloudwatchomni list-domains— exact steps in programmatic-access.md. Never run a package-manager upgrade or installer on the host yourself (brew,pip install -U,.pkg/MSI); it mutates the customer's machine beyond the request and can break unrelated tooling — hand over the command and continue with the guidance. Never substitute a CloudWatch or X-Ray command for an Omni request. If the request carried no Omni signal, do not block on the upgrade. When you are already going back to the customer for missing inputs (for example an alert's threshold and period), ask which product they want in that same question: say the Space probe could not run on this CLI, describe both options, and build neither until they answer. When the request is fully specified or says not to ask, proceed on the CloudWatch path (the pre-Omni default) and mention the upgrade only in passing.Still inconclusive → ask the customer.
First-time setup, on EITHER product → STOP and route to the
setting-up-cloudwatch-observabilityskill. This skill covers a service or Space that already reports and holds no onboarding procedure for either product, so there is nothing here to fall back on: not Omni setup (creating a Domain or Space, granting access, ingestion, forwarding, Slack, instrumenting an app or AI agent for a Space) and not CloudWatch setup (onboarding a service to Application Signals — ADOT auto-instrumentation, theamazon-cloudwatch-observabilityadd-on, monitored service, ServiceEvents, CI/CD metadata, the per-platform enablement guides). Any instrumentation / ADOT / collector request is a setup request either way; the setup skill owns the product decision too, so hand the whole request over rather than probinglist-spacesyourself. Application Signals once it is reporting — service map, alarms on its metrics, Dynamic Instrumentation debugging — belongs here.
Under-specified alert requests: When an alert or alarm request names what to watch (a symptom or a service) but not the inputs it needs — the threshold value and the evaluation period — ask for those rather than inventing them. Notifications are optional (per alerts.md), so ask for a notification destination only if the user wants to be notified. This holds on both paths (an Omni alert or a CloudWatch alarm).
Under-specified dashboard requests: When a dashboard request names what to show but not which metrics, panels, or layout, ground those against the data and confirm the panel set rather than inventing panels; a dashboard has no threshold, period, or notification. For ANY dashboard authoring/save request, also open dashboards.md and surface its "Facts you MUST surface when building or saving an Omni dashboard" checklist (see "Must-state checklists" below). Which signals or panels a named resource type needs is a Step 0.5 catalog question, not a dashboards-file question.
Step 0.5 — Service-health investigation (routing)
A large share of real questions are phrased as an operator symptom, not as a tool: "is my
<service> throttled / slow / erroring / unhealthy," "which of my <service>s are
<symptom>," "what's the health of my <service>," "what does <service> depend on and
which is broken," "what signals / what should be on a dashboard or view for <service>."
These are observability-data questions. Start from the telemetry, and answer with the
methodology (the correct signals, aggregation, scoping, and caveats) even when you also
pull live numbers and even when no matching resource exists in the account.
Telemetry shows the symptom. The cause is often a configured value, so when the question is
why something fails, also read the configuration of the resources involved, for example an
API Gateway integration timeout, an SQS visibility timeout, or a Lambda timeout or event
source mapping. A read-only or "logs only" role can usually still call these Get and
Describe APIs. Make the call and report AccessDenied if it happens.
Route by the symptom, then open the reference and surface every applicable item in its "facts you MUST surface" checklist — the checklist is the output contract, and it lives in the reference file, not here:
A metric symptom about one AWS service (throttling, latency, error rate, restarts, saturation, "what signals should it get", which signals or panels a named resource type needs on a dashboard or view) → query/promql-metrics.md. Open its "Service-health question — facts you MUST surface" section and surface every applicable item. Dashboard or view wording does not send this to either dashboards file (neither carries the signal facts) nor to rule 3's probe — it is a content question.
"What does
<service>depend on / what's broken downstream" / blast radius / who is affected / which direction do I walk the graph / what doCALLS,ACCESSES,RUNS_ONmean → context-graph.md. Open its "Dependency / blast-radius question — facts you MUST surface" section and surface every applicable item. A slowness or error symptom phrased in terms of the graph, dependencies, or edge types routes here, not to the metric bullet above.A health VERDICT for a service ("is
<service>healthy", "health summary of<service>") or a dependency map WITH ROLES ("what does<service>depend on and what role does each play", "which services call<service>") → service-health.md. Open its "Service health & dependency question — facts you MUST surface" section and surface every applicable item — it owns the combined verdict and the role-labelled dependency map, and defers the per-resource signal catalog and blast radius elsewhere. A bare single-service metric symptom, or a "what signals / panels does<resource type>need" or fleet-health-view ask, routes to the promql-metrics bullet above; a pure blast-radius / direction / edge-semantics question routes to the context-graph bullet.System status, a root-cause / triage symptom, or a past incident — "is anything wrong right now?", "what's wrong with
<service>", "why is<service>slow or erroring", "what changed since<time>", "users reported errors between X and Y — which service is the single most likely root cause", or any mention of insights, observations, or anomalies (a cause ask, not a single-signal health verdict or a dependency list) → intelligence.md: start from Omni Intelligence insights and observations, then use the context graph and queries to confirm. Its own "Scope and neighbours" section states which asks it hands back to the bullets above.Individual slow or failing spans / traces ("slowest spans for
<service>", "which traces failed") are trace SQL, not a metric aggregate → query/sql-logs-traces.md. Open its "Span Duration" and "Finding failed spans" sections and state every item in their must-state callouts — a request about a service's latency or error rate (an aggregate signal) is the PromQL bullet above instead.A failure being investigated from logs ("is this only failing for X?", "how many errors?", "what is the root cause?") → load the
aws-investigationskill and read itsreferences/completeness-and-root-cause.md. Read every page and every scope before counting, and check the root cause against every fact before reporting it.
Must-state checklists — the output contract
Four Omni tasks carry a checklist the answer text must carry, not just the plan. Open the reference and surface every item relevant to the request; the reference holds the per-item detail and is the source of truth, so do not restate it here.
| Task | Open | Section to surface |
|---|---|---|
| Authoring or advising on an Omni alert | alerts.md | "Facts you MUST surface when authoring an alert" |
| Scoring traces, choosing an evaluator, reading stored scores, online/continuous evaluation, evaluation datasets, turning scores into agent changes | agent-evaluation.md | every "tell the user ALL of this" callout |
| Exploring traces — one trace by id, comparing runs, finding traces by their spans, slowest traces, trace fields, agent sessions, token cost, what changed between two windows | query/trace-exploration.md | every "state … in the answer" callout |
| Authoring, saving, reading back, or debugging an Omni dashboard | dashboards.md | "Facts you MUST surface when building or saving an Omni dashboard" |
Routing — CloudWatch (references/cloudwatch/)
| User need | Action |
|---|---|
Enabling/onboarding a service to Application Signals (auto-instrumentation, the amazon-cloudwatch-observability add-on, monitored service), propagating ServiceEvents git/deployment metadata through CI/CD, or the per-platform × per-language enablement steps | STOP — this is first-time CloudWatch setup and no reference here covers it. Route to the setting-up-cloudwatch-observability skill |
| Writing Log Insights queries (pipe-delimited syntax: fields, filter, stats, sort, parse, display) | Read log-insights.md. If StartQuery rejects the window as before the log group's creation time, read the same window with FilterLogEvents. See Known issues 11 there |
| Configuring alarms (metric, composite, anomaly) | Read alarms.md. For an Omni alert, see the Omni table |
| Publishing custom metrics or using EMF | Read metrics.md |
| X-Ray / ADOT tracing behaviour — X-Ray-SDK-vs-ADOT choice, trace and segment structure, annotations vs metadata, sampling rules, collector pipeline config, X-Ray→OTel migration traps | Read tracing.md. Onboarding an un-instrumented service is the setup skill's job (see the first row) |
| Building CloudWatch dashboards (widget mechanics; which signals a given AWS service needs is Step 0.5) | Read dashboards.md |
| Debugging observability issues | Read troubleshooting.md — starts with the 5 most common fixes |
| Investigating a failure from logs: whether it affects one entity or the whole fleet, counts/totals/"no evidence of X", or deciding and reporting the root cause | Load the aws-investigation skill — completeness and scope first (references/completeness-and-root-cause.md), then root-cause analysis and the closing checklist |
| Debugging canary failures | Read synthetics.md — see Common failures table |
| CloudTrail operational auditing | Read cloudtrail.md |
| Setting up Lambda monitoring with CDK | Use alarm-template.ts as a starting point |
| Creating synthetic canaries | Read synthetics.md |
| Configuring ADOT collector | Use otel-config.yaml as a starting point |
| Debugging a running service with breakpoints/snapshots — Dynamic Instrumentation (modifies live services and captures live data) | Read dynamic-instrumentation.md in full before acting. Confirm with the user before any create/delete, and narrate before significant actions: observation → hypothesis → proposed action → expected result. Source inspection alone identifies hypotheses, not confirmed root causes; keep suspected causes tentative until runtime evidence confirms them. |
Routing — CloudWatch Omni (references/cloudwatch-omni/)
Rows that act on live Space data assume Step 0 found a Space. Knowledge questions are answered from the file directly.
| User need | Action |
|---|---|
| Concepts. What Omni is, what a Domain / Space / Dataset / grant / profile / view / alert / context graph is, whether a feature is Omni or CloudWatch, where setup starts | Read concepts.md |
Query logs or traces — SQL (SELECT … FROM logs.default / traces.default / default), field access, schema discovery, slowest / failed spans (durationNano, status.code), TABLESAMPLE | Read query/sql-logs-traces.md. For slowest or failed spans, state every item in its "Span Duration" / "Finding failed spans" must-state callouts, even when the live result is empty |
| Explore traces — open one trace by id (where the time went, why it failed, span tree, inputs/outputs, tokens), compare two runs, why a trace scored badly, find traces by their spans (tool calls per trace, a repeated tool, failed tool calls), the slowest traces today, what fields a trace carries, list or walk an agent's sessions (a looping session), token cost, guardrail or deploy questions, what changed (agent, model or downstream) | Read query/trace-exploration.md for the trace recipes and agent-span attributes, with query/sql-logs-traces.md for the SQL itself |
| A span, trace, or log record supplied in the prompt — "I have this span open, what errors are in it", a pasted telemetry object | Read the "Reading a span or trace you already have" section of query/sql-logs-traces.md. Answer from the object's own fields; do not probe, query, or ask the user to fetch it |
| Query metrics — PromQL, which metric answers which symptom per AWS service, why a metric is missing, gauge vs counter | Read query/promql-metrics.md. Metrics are PromQL, never SQL; run them directly through the CloudWatch Prometheus-compatible API (monitoring endpoint) or the CloudWatch MCP server's PromQL tools, not through StartTelemetryQuery |
Views — create, manage, or query named reusable SQL (FROM view.<name>) | Read query/views.md |
Dashboards in Omni — compose, ground panel queries, author panels[], lay out the grid, the API save semantics (an unknown root- or panel-level key, a missing type/layout, or a bad variant is REJECTED at save with a 400 ValidationException; a bad enum VALUE, x+w>60, or an unknown key inside config saves 200 and fails or is ignored at render; validate before save), fix an empty or blank panel, the *OmniDashboard APIs | Read dashboards.md |
Alerts in Omni — any mention of an Omni alert, CreateAlert / GetAlert / ListAlerts / UpdateAlert / DeleteAlert, a profileId, an alert ARN, or how alerts differ from alarms; create, tune, tag, list, delete; notifications | Read alerts.md. The alert API is real and first-class — do NOT redirect to CloudWatch alarms. For CloudWatch alarms when Omni is not enabled, read cloudwatch/alarms.md |
Omni Intelligence — is anything wrong right now, status of a service, why is a service slow or erroring, what caused an incident between two times, root cause, past incidents, insights, observations, anomalies, ListInsights, ListObservations | Read intelligence.md; it links to the context graph for cause-vs-impact questions. ListInsights, ListObservations, and GetContextGraph are the public CloudWatch Omni operations it teaches (aws cloudwatchomni list-insights / list-observations / get-context-graph), with the Intelligence console view as a human-readable cross-check. It consults the intelligence layer, localizes on the context graph, confirms with telemetry, and names one root-cause service. For a health verdict or dependency roles with no single-cause ask, use service-health.md; for pure dependency / blast-radius topology and graph traversal, use context-graph.md |
Context graph — why is service X slow or failing, what depends on it, upstream/downstream, which direction to walk, edge types CALLS / ACCESSES / RUNS_ON, blast radius, walking from an insight or anomaly to a root cause, GetContextGraph | Read context-graph.md and state every applicable item in its "facts you MUST surface" section |
Service health & dependency analysis — is <service> healthy, health summary, what does <service> depend on and what ROLE does each play (caller / callee / datastore / runs-on), which services call it | Read service-health.md and state every applicable item in its "facts you MUST surface" section. It grounds the verdict in the context graph + RED/USE metrics + alarm state; for the resource-specific signal catalog and query mechanics it defers to query/promql-metrics.md (§5 per-service catalog), query/sql-logs-traces.md, and alerts.md, for traversal and blast radius to context-graph.md. A "what signals / panels does <resource type> need" or fleet-health-view ask goes to promql-metrics.md, not here |
Agent evaluation — score traces on demand, choose an evaluator, read back stored gen_ai.evaluation.* scores ("which evaluators are doing worst", "which online evaluators are unhealthy / underperforming"), build datasets from traces, set up online evaluation, author a custom evaluator, audit whether an agent's traces are flowing, monitor quality, root-cause a quality regression, recommend prompt or tool-description changes from scores, verify a change against a baseline | Read agent-evaluation.md and state every applicable item in its "tell the user ALL of this" callouts |
| Programmatic access — "is there an API or SDK for Omni", calling Omni from code, CI, IaC, or an AI coding agent | Read programmatic-access.md. Omni has a real public SigV4 API; never answer that it has none, never substitute the CloudWatch or X-Ray CLI/SDK, and answer without probing for a Space. Endpoint cloudwatch-omni.<region>.api.aws, never .amazonaws.com; client cloudwatchomni, no hyphen. Give both authorization classes: a grant-mediated caller needs a matching grant or is denied; a direct IAM caller with none is not denied by the Space — its own IAM policy decides |
| AWS DevOps Agent — Investigations reports it is not connected, connecting it to a Space, or running, following, or chatting with an investigation | Connecting is first-time setup: route to the setting-up-cloudwatch-observability skill. In the Omni web app an investigation starts from a thread, /investigation new <description>, or a firing alert's Investigate action. Driving the DevOps Agent itself (starting, following, or chatting with investigations from a coding agent) belongs to its dedicated aws-agents-for-devsecops plugin; point there and do not reconstruct that workflow or invent aidevops calls |
| Who has access to a Space, granting or revoking access, access profiles, creating a Space or Domain, ingestion, forwarding, Slack, Azure, instrumenting an app or AI agent — and, on the CloudWatch side, onboarding a service to Application Signals | Route to the setting-up-cloudwatch-observability skill. If it is not installed locally, load it with the AWS MCP retrieve_skill tool (skill_name: setting-up-cloudwatch-observability; pass file for a reference it cites) |
| Spans multiple areas | Read the most specific reference first, then consult others as needed |
Files
references/cloudwatch/
| File | Content |
|---|---|
| alarms.md | Metric, composite, anomaly detection alarms — configuration, constraints, recommended defaults |
| log-insights.md | Complete query syntax, commands, functions, known issues, reusable query library |
| metrics.md | Custom metrics, EMF spec, metric filters, high-resolution, retention |
| tracing.md | X-Ray → ADOT migration, sampling rules, annotations vs metadata, collector config |
| dashboards.md | Widget types, cross-account/region, dynamic labels, sharing |
| troubleshooting.md | Error → cause → fix for all observability services |
| cloudtrail.md | Operational auditing, event types, S3+Athena queries |
| synthetics.md | Canary runtime/blueprint constraints, VPC networking, common failures |
| dynamic-instrumentation.md | Dynamic Instrumentation debugging loop — breakpoints/probes on live code, snapshot capture + correlation analysis, create/delete gating, snapshot PII handling. Runs via scripts/cloudwatch/di_instrumentation.py + scripts/cloudwatch/di_snapshots.py; details in dynamic-instrumentation/ |
| alarm-template.ts | Best-practice CDK Lambda monitoring (alarms + dashboard) |
| otel-config.yaml | ADOT collector config for X-Ray traces + CloudWatch EMF metrics |
Not here, by design: Application Signals onboarding (the enablement procedure, the
ServiceEvents CI/CD chain, the 16 per-platform guides) is first-time setup and lives in
setting-up-cloudwatch-observability. Do not reconstruct it here from memory; route.
references/cloudwatch-omni/
| File | Content |
|---|---|
| concepts.md | What Omni is and is not; glossary (Domain, Space, Dataset, grant, profile, view, alert, dashboard, context graph, evaluator); Omni-vs-CloudWatch feature-equivalence matrix; how to tell which product the customer means; the setup sequence and where it lives |
| context-graph.md | The service/resource topology Omni builds from traces and metrics; GetContextGraph request/response and CLI; reading upstream vs downstream and blast radius; walking from an insight or anomaly hop-by-hop to a root cause, then pivoting to queries |
| intelligence.md | Omni Intelligence — the insight and observation operations and data model, ListInsights / ListObservations inputs and filters, GetContextGraph with insights, answering status, troubleshooting, root-cause and past-incident questions, the 404-vs-403-vs-local error rule (owned by context-graph.md), cost and performance guardrails, and the empty-result/stale-insight gotchas |
| service-health.md | Service health verdict and dependency analysis — dependency map with roles (caller/callee/datastore/runs-on), the multi-signal HEALTHY/DEGRADED/DOWN verdict (RED for services, USE for resources, alarm state), and how to build the checks from a node's includeMetadata selectors. Ties together context-graph, promql-metrics, sql-logs-traces, and alerts rather than duplicating them — defers traversal and blast radius to context-graph and the resource-specific signal catalog to promql-metrics §5 |
| programmatic-access.md | The public SigV4 API (cloudwatch-omni endpoint prefix, cloudwatch signing name), how access grants authorize a programmatic caller, CLI/SDK access (and why an unsupported-service error is a client-version issue), CloudFormation/CDK, AI coding agents, and the wrong answers to avoid |
| query/sql-logs-traces.md | SQL over logs and traces — table addressing, required time range, system fields, field access and quoting, schema discovery, supported operations, functions, common patterns (including durationNano span duration), constraints, TABLESAMPLE |
| query/promql-metrics.md | Metrics in Omni are PromQL — what is queryable (OTLP, span RED, OTel-enriched vended metrics) and what is not, label conventions, __name__ matcher, rate() on counters, per-AWS-service metric catalog with derived formulas and dimension traps, and running queries and discovering names through the Prometheus-compatible HTTP API and MCP tools |
| query/trace-exploration.md | Working with whole traces on traces.default — span fields and AI-agent span attributes (span role, tool name, input/output, token usage), fetching one trace in the right window, time breakdown and self-time, failure analysis with exception events, comparing runs, tying a bad evaluation score to spans, tool-call and repeated-tool patterns, trace-level latency and "today", field discovery for traces, reporting, agent sessions, walking a session, token cost, signals the spans may not record, before/after comparison by layer |
| query/views.md | Named SQL views: CreateView / UpdateView / DeleteView / ListViews, FROM view.<name>, naming and definition rules, composition patterns |
| dashboards.md | Omni dashboards — composition recipes, grounding panel queries, the panels[] body and panel types, visualizations, the 60-column grid, the API save semantics (unknown root/panel keys are rejected 400; unknown keys inside config save 200 and are ignored at render; validate before save), troubleshooting empty/blank panels, the Create/Get/List/Update/DeleteOmniDashboard APIs, archetype templates |
| alerts.md | Omni alerts — alert vs alarm, evaluation (FIELD_VALUE / COUNT_OF_RESULTS, contributors), states and no-data treatment, notification rules, step-by-step create / update / delete / tag / fetch, and the alert APIs |
| agent-evaluation.md | Agent-quality evaluation on OTel traces — instrumentation health audit, evaluator selection, on-demand scoring, online evaluation, custom evaluators, datasets from traces, reading back stored gen_ai.evaluation.* scores (retrieval plan + SQL mechanics), and turning scores into changes (monitoring, regressions, evaluator drills, golden datasets, change and re-run). Uses scripts/cloudwatch-omni/evaluate_traces.py and scripts/cloudwatch-omni/capture_dataset_from_traces.py |
Files
- ATTRIBUTION.mdAdded by AutoGineer899 B
- LICENSELicence file added by AutoGineer9.9 KiB
- NOTICELicence file added by AutoGineer67 B
- SKILL.md37.0 KiB
- assets/cloudwatch/alarm-template.tsScript3.9 KiB
- assets/cloudwatch/otel-config.yaml1.9 KiB
- references/cloudwatch-omni/agent-evaluation.md114.9 KiB
- references/cloudwatch-omni/alerts.md108.5 KiB
- references/cloudwatch-omni/concepts.md29.3 KiB
- references/cloudwatch-omni/context-graph.md32.6 KiB
- references/cloudwatch-omni/dashboards.md79.4 KiB
- references/cloudwatch-omni/intelligence.md16.9 KiB
- references/cloudwatch-omni/programmatic-access.md15.5 KiB
- references/cloudwatch-omni/query/promql-metrics.md66.8 KiB
- references/cloudwatch-omni/query/sql-logs-traces.md45.1 KiB
- references/cloudwatch-omni/query/trace-exploration.md26.1 KiB
- references/cloudwatch-omni/query/views.md12.8 KiB
- references/cloudwatch-omni/service-health.md17.5 KiB
- references/cloudwatch/alarms.md11.6 KiB
- references/cloudwatch/cloudtrail.md5.4 KiB
- references/cloudwatch/dashboards.md5.8 KiB
- references/cloudwatch/dynamic-instrumentation.md39.3 KiB
- references/cloudwatch/dynamic-instrumentation/breakpoint-creation.md16.3 KiB
- references/cloudwatch/dynamic-instrumentation/call-tree-and-directions.md5.7 KiB
- references/cloudwatch/dynamic-instrumentation/snapshot-parsing.md4.2 KiB
- references/cloudwatch/log-insights.md8.3 KiB
- references/cloudwatch/metrics.md7.5 KiB
- references/cloudwatch/synthetics.md6.5 KiB
- references/cloudwatch/tracing.md9.4 KiB
- references/cloudwatch/troubleshooting.md7.5 KiB
- scripts/cloudwatch-omni/capture_dataset_from_traces.pyScript25.2 KiB
- scripts/cloudwatch-omni/evaluate_traces.pyScript42.7 KiB
- scripts/cloudwatch-omni/test_evaluate_traces.pyScript12.6 KiB
- scripts/cloudwatch/di_app_signals_client.pyScript3.3 KiB
- scripts/cloudwatch/di_capture.pyScript8.5 KiB
- scripts/cloudwatch/di_constants.pyScript560 B
- scripts/cloudwatch/di_crud_rendering.pyScript13.1 KiB
- scripts/cloudwatch/di_crud_tools.pyScript28.8 KiB
- scripts/cloudwatch/di_error_translation.pyScript5.6 KiB
- scripts/cloudwatch/di_formatting.pyScript992 B
- scripts/cloudwatch/di_gateway.pyScript7.0 KiB
- scripts/cloudwatch/di_instrumentation.pyScript13.0 KiB
- scripts/cloudwatch/di_location.pyScript15.3 KiB
- scripts/cloudwatch/di_logs_client.pyScript4.2 KiB
- scripts/cloudwatch/di_region.pyScript2.0 KiB
- scripts/cloudwatch/di_result.pyScript2.0 KiB
- scripts/cloudwatch/di_session.pyScript2.0 KiB
- scripts/cloudwatch/di_snapshot_parsing.pyScript11.4 KiB
- scripts/cloudwatch/di_snapshot_queries.pyScript2.4 KiB
- scripts/cloudwatch/di_snapshot_rendering.pyScript12.5 KiB
- scripts/cloudwatch/di_snapshot_tools.pyScript12.0 KiB
- scripts/cloudwatch/di_snapshots.pyScript12.8 KiB
- scripts/cloudwatch/di_status_assessment.pyScript4.7 KiB
- scripts/cloudwatch/di_status_rendering.pyScript11.8 KiB
- scripts/cloudwatch/di_status_tools.pyScript13.0 KiB
- scripts/cloudwatch/di_validation.pyScript11.2 KiB
scripts/cloudwatch-omni/capture_dataset_from_traces.py
#!/usr/bin/env python3
"""Turn CloudWatch Omni traces into an AgentCore evaluation dataset.
Bundled skill helper (retrieved via the skill's supplementary-file mechanism and run
with the agent's shell) for Section 5, Step B "build a dataset from traces". For each
trace it queries spans from CloudWatch Omni (traces.default) via Omni SQL, reshapes
them into one example (root-span COALESCE for the input, last-finishing AGENT span for the
expected response, ordered TOOL-name trajectory with adjacent dupes collapsed,
scenario_id/metadata provenance), validates it, and writes the batch into a NEW dataset
(--mode create) or an EXISTING one (--mode add). Prints a compact JSON receipt only —
raw spans never leave this process (kept out of the model's context).
--mode create always creates an AGENTCORE_EVALUATION_PREDEFINED_V1 dataset. --mode add
first reads the target dataset's immutable schemaType with get-dataset and renders the
examples in the shape that schema declares — PREDEFINED (nested `turns`) or
THIRD_PARTY_EVALUATION_V1 (flat `input`/`expected_output`, what the console writes for a
dataset created from traces). The two shapes are not interchangeable and validation is
all-or-nothing, so a dataset declaring any other schema is refused by name instead.
Requires boto3 + caller AWS credentials with cloudwatch-omni (Omni SQL query) +
bedrock-agentcore-control (dataset write). The caller must have an access grant on the
Space and cloudwatch:StartQuery / cloudwatch:GetQueryResults permissions.
Creating/extending a dataset is a real resource write. This helper refuses to write unless
the caller passes --i-have-confirmed, asserting the user confirmed this write. The flag is a
caller-side assertion, not a verification: it stops an accidental or unconfirmed run, but the
caller is responsible for adding it only AFTER the user has actually confirmed.
Examples:
python capture_dataset_from_traces.py --mode create --dataset-name checkout_regressions \
--trace-ids 6a7f...,6a80... --region us-east-1 --i-have-confirmed
python capture_dataset_from_traces.py --mode add --dataset-id my_ds-AbC123 \
--trace-ids 6a81... --i-have-confirmed
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import time
from typing import NoReturn
from uuid import uuid4
import boto3
from botocore.exceptions import BotoCoreError, ClientError
# String-valued attribute keys only (COALESCE order). The OTel GenAI-semconv
# `gen_ai.input.messages`/`gen_ai.output.messages` are structured ARRAYS, not strings,
# so they're intentionally excluded — treating them as a plain string would either be
# dead (non-str skipped) or inject a raw serialized-array blob as the turn text.
INPUT_KEYS = ("input.value", "gen_ai.input_value")
OUTPUT_KEYS = ("output.value", "gen_ai.output_value")
PREDEFINED_SCHEMA = "AGENTCORE_EVALUATION_PREDEFINED_V1"
THIRD_PARTY_SCHEMA = "THIRD_PARTY_EVALUATION_V1"
# --mode create always creates a PREDEFINED dataset; --mode add renders into whichever of
# these two the target dataset declares. Any other schemaType (e.g. the SIMULATED one, which
# needs an author-written actor_profile.goal) cannot be derived from a trace at all.
CREATE_SCHEMA_TYPE = PREDEFINED_SCHEMA
ADD_SCHEMAS = (PREDEFINED_SCHEMA, THIRD_PARTY_SCHEMA)
MAX_TRACES = 25 # single write batch; excess is reported, never silently dropped
SPAN_ROW_LIMIT = 1000 # fetch LIMIT+1 (1001) so an exactly-full result is detectable as truncated
# Service limits (bedrock-agentcore-control datasets): each example must serialize to <= 1 MB
# (a 400 on the whole batch otherwise), and a dataset holds at most 1000 examples in total
# (a write past that is a 402 ServiceQuotaExceededException).
MAX_EXAMPLE_BYTES = 1_000_000
MAX_DATASET_EXAMPLES = 1000
QUERY_POLL_ATTEMPTS = (
150 # × 2s = up to 5 min for the (heavy: 25 traces / 30-day) query to complete
)
# Trace ids are hex; validate before interpolating into the Omni SQL query string.
_TRACE_ID_RE = re.compile(r"^[0-9a-fA-F]{1,64}$")
def _die(payload) -> NoReturn:
"""Print an error receipt to stdout (so the agent sees it) and exit non-zero."""
print(json.dumps(payload))
sys.exit(1)
# ---- pure conversion (same mapping as references/dataset-from-traces.md) ----
def _attr_text(span, keys):
attrs = (span or {}).get("attributes") or {}
for k in keys:
v = attrs.get(k)
if isinstance(v, str) and v.strip():
return v.strip()
return None
def _scan(spans, keys):
for s in spans:
t = _attr_text(s, keys)
if t:
return t
return None
def _root(spans):
return next((s for s in spans if not s.get("parentSpanId")), spans[0] if spans else None)
def _nano_key(v):
"""Sort key for a nanosecond timestamp string: compare by magnitude, not lexically."""
return (len(v), v) if isinstance(v, str) else (0, "")
def _final_output(spans):
"""The trace's final answer: output of the last-FINISHING AGENT span.
Ranking on *end* time, not start time, is the point: the span that produced the answer is
the outermost one, which starts early and finishes last. Ordering by start time instead
picks the innermost leaf the framework happened to invoke last — on a LangGraph trace that
is the conditional-edge node (`should_continue`), whose output is the routing token
`__end__`, and the helper would store that 7-character token as ground truth for every
example.
AGENT kind is preferred over the root span because the root is so often neither: on an
HTTP-served agent it is the `POST` span, which carries no output at all, and on a trace
whose spans are all parented the root fallback is the earliest graph span, whose output is
the whole accumulated graph state rather than the answer. When the root *is* the agent span
it also ends last among AGENT spans, so it is still selected. Falls back to the root, then
to the last-finishing span of any kind, for frameworks that emit no span kind.
"""
by_end = sorted(spans, key=lambda s: _nano_key(s.get("end")))
agents = [s for s in by_end if _span_kind(s) == "AGENT"]
for s in reversed(agents):
t = _attr_text(s, OUTPUT_KEYS)
if t:
return t
return _attr_text(_root(spans), OUTPUT_KEYS) or _scan(list(reversed(by_end)), OUTPUT_KEYS)
def _collapse_adjacent(items):
out: list = []
for x in items:
if not out or out[-1] != x:
out.append(x)
return out
def _span_kind(s):
a = s.get("attributes") or {}
return a.get("openinference.span.kind") or a.get("aws.genai.span_kind")
def to_example(trace_id, spans, partial=False):
spans = sorted(spans, key=lambda s: _nano_key(s.get("ts"))) # start-time order
root = _root(spans)
turn = {"input": _attr_text(root, INPUT_KEYS) or _scan(spans, INPUT_KEYS) or ""}
out = _final_output(spans)
if out:
turn["expected_response"] = out
session_id = next(
(
s["attributes"].get("session.id")
for s in spans
if (s.get("attributes") or {}).get("session.id")
),
None,
)
metadata = {"sourceTraceId": trace_id}
if session_id:
metadata["sessionId"] = session_id
if partial:
metadata["partial"] = True
example = {"scenario_id": trace_id, "turns": [turn], "metadata": metadata}
tools = [
(s.get("attributes") or {}).get("tool.name")
for s in spans
if _span_kind(s) == "TOOL" and (s.get("attributes") or {}).get("tool.name")
]
trajectory = _collapse_adjacent(tools)
if trajectory:
example["expected_trajectory"] = trajectory
return example
def to_third_party(example):
"""Re-render a PREDEFINED example in the THIRD_PARTY_EVALUATION_V1 shape.
That schema is flat: the turn's `input` sits at the top level (the service rejects the
whole batch with "Required field 'input' is missing from example content" when it is
nested in `turns`) and the ground-truth response is `expected_output`. `scenario_id`,
`metadata` and `expected_trajectory` carry over unchanged — the same shape the console
writes when it builds a dataset from traces. Trace-derived examples are always
single-turn, so the flattening is lossless.
"""
turn = (example.get("turns") or [{}])[0]
flat = {"input": turn.get("input"), "scenario_id": example.get("scenario_id")}
if turn.get("expected_response"):
flat["expected_output"] = turn["expected_response"]
if example.get("metadata"):
flat["metadata"] = example["metadata"]
if example.get("expected_trajectory"):
flat["expected_trajectory"] = example["expected_trajectory"]
return flat
def invalid(example, schema_type=PREDEFINED_SCHEMA):
"""Return an error string if the example fails this schema's gate, else None.
Each schema keeps the input in a different place, so the gate has to know which one the
example was rendered for: PREDEFINED nests it under `turns[0].input`, THIRD_PARTY keeps it
top-level. The service only checks that the field is *present* on a third-party dataset —
an empty input is a useless example either way, so reject it here.
"""
if schema_type == THIRD_PARTY_SCHEMA:
val = example.get("input")
missing_input = "missing a non-empty input"
else:
turns = example.get("turns")
if not turns:
return "no turns"
val = turns[0].get("input")
missing_input = "turn 1 missing a non-empty input"
if not ((isinstance(val, str) and val.strip()) or (isinstance(val, dict) and val)):
return missing_input
# The service rejects the WHOLE batch if any single example exceeds 1 MB serialized.
size = len(json.dumps(example, default=str).encode("utf-8"))
if size > MAX_EXAMPLE_BYTES:
return "example serializes to %d bytes; the service caps one example at %d bytes" % (size, MAX_EXAMPLE_BYTES)
return None
# ---- span fetch via CloudWatch Omni SQL (traces.default) ----
def fetch_spans_by_trace(omni, trace_ids, window_days):
"""Fetch spans for the trace ids via Omni SQL, sorted by (traceId, startTimeUnixNano).
Returns (by_trace, truncated, boundary). Because the query sorts by traceId asc, a
row-cap hit only ever cuts the *last* returned trace mid-way — every lower-sorted trace
is complete, and every higher-sorted (requested) trace was never reached. So on
truncation only `boundary` (the last returned trace id) is partial; the caller flags the
unreached traces distinctly from genuine misses.
"""
quoted = ", ".join("'%s'" % t for t in trace_ids) # ids are validated hex — safe to interpolate
sql = (
"SELECT traceId, spanId, parentSpanId, startTimeUnixNano, endTimeUnixNano, "
"attributes['openinference.span.kind'] AS oi_span_kind, "
"attributes['aws.genai.span_kind'] AS aws_genai_span_kind, "
"attributes['tool.name'] AS tool_name, "
"attributes['input.value'] AS input_value, "
"attributes['output.value'] AS output_value, "
# String-valued gen_ai.* fallbacks — the *.messages array keys are omitted
# (they are not plain strings; the COALESCE in _attr_text skips non-str values).
"attributes['gen_ai.input_value'] AS gen_ai_input_value, "
"attributes['gen_ai.output_value'] AS gen_ai_output_value, "
"attributes['session.id'] AS session_id_attr "
"FROM \"traces.default\" "
"WHERE traceId IN (%s) "
"AND \"@timestamp\" BETWEEN NOW() - INTERVAL '%d days' AND NOW() "
"ORDER BY traceId ASC, startTimeUnixNano ASC "
# fetch one past the cap so an exactly-full result isn't mistaken for truncation
"LIMIT %d"
) % (quoted, window_days, SPAN_ROW_LIMIT + 1)
rows: list = []
truncated = False
session_id = None
try:
try:
session_id = omni.start_telemetry_query_session(
sessionName="capture-dataset"
)["sessionId"]
except (BotoCoreError, ClientError) as e:
_die({"error": "Omni start_telemetry_query_session failed: %s" % e})
try:
qid = omni.start_telemetry_query(
sessionId=session_id, queryString=sql
)["queryId"]
except (BotoCoreError, ClientError) as e:
_die({"error": "Omni start_telemetry_query failed: %s" % e})
# Phase 1: poll for completion (status only; rows are not stable until Complete)
status = None
for _ in range(QUERY_POLL_ATTEMPTS):
time.sleep(2)
try:
poll = omni.get_telemetry_query_results(queryId=qid, maxResults=1)
except (BotoCoreError, ClientError) as e:
_die({"error": "Omni get_telemetry_query_results failed: %s" % e})
status = poll.get("status")
if status in ("Complete", "Failed", "Cancelled"):
break
if status != "Complete":
_die(
{
"error": "Omni SQL query did not complete (status=%s); "
"reduce --trace-ids or narrow --window-days" % status
}
)
# Phase 2: paginate while session is still open, accumulating up to SPAN_ROW_LIMIT+1
# rows. The SQL uses LIMIT SPAN_ROW_LIMIT+1 (1001) so if the LIMIT was hit the 1001st
# row exists; once accumulated rows exceed SPAN_ROW_LIMIT we know it was hit. Paginating
# rather than trusting a single page handles short pages (fewer than maxResults rows
# returned with a nextToken) which are valid for any AWS paginated API.
next_token = None
while len(rows) <= SPAN_ROW_LIMIT:
try:
kwargs: dict = {"queryId": qid, "maxResults": 1000}
if next_token:
kwargs["nextToken"] = next_token
page = omni.get_telemetry_query_results(**kwargs)
except (BotoCoreError, ClientError) as e:
_die({"error": "Omni get_telemetry_query_results (fetch) failed: %s" % e})
rows.extend(page.get("rows", []))
next_token = page.get("nextToken")
if not next_token:
break
finally:
if session_id:
try:
omni.stop_telemetry_query_session(sessionId=session_id)
except Exception:
pass
truncated = len(rows) > SPAN_ROW_LIMIT
if truncated:
rows = rows[:SPAN_ROW_LIMIT] # drop the probe row before building spans
by_trace: dict = {}
order: list = []
# rows is a list of dicts: column alias → string value
_ATTR_COLS = [
("openinference.span.kind", "oi_span_kind"),
("aws.genai.span_kind", "aws_genai_span_kind"),
("tool.name", "tool_name"),
("input.value", "input_value"),
("output.value", "output_value"),
("gen_ai.input_value", "gen_ai_input_value"),
("gen_ai.output_value", "gen_ai_output_value"),
("session.id", "session_id_attr"),
]
for row in rows:
tid = row.get("traceId")
if not tid:
continue
if tid not in by_trace:
order.append(tid)
attrs = {attr_key: row[col] for attr_key, col in _ATTR_COLS if row.get(col)}
by_trace.setdefault(tid, []).append(
{
"spanId": row.get("spanId"),
"parentSpanId": row.get("parentSpanId") or None,
"ts": row.get("startTimeUnixNano"),
# end time ranks the final-answer span (_final_output); start time cannot
"end": row.get("endTimeUnixNano"),
"attributes": attrs,
}
)
boundary = order[-1] if (truncated and order) else None # the only possibly-cut trace
return by_trace, truncated, boundary
def _resolve_dataset_id(ctl, id_or_name):
token = None
while True:
try:
resp = ctl.list_datasets(**({"nextToken": token} if token else {}))
except (BotoCoreError, ClientError) as e:
_die({"error": "list_datasets failed: %s" % e})
for d in resp.get("datasets", []):
if d.get("datasetId") == id_or_name or d.get("datasetName") == id_or_name:
return d.get("datasetId")
token = resp.get("nextToken")
if not token:
_die({"error": "dataset %r not found" % id_or_name})
def _dataset_schema_and_count(ctl, dataset_id):
"""Read the target dataset's declared schemaType and its DRAFT example count.
The schemaType read is NOT best-effort: it is fixed at creation, immutable, and decides
where the example's input goes, so building examples without it is a guess that rejects the
whole batch whenever it is wrong (validation is all-or-nothing). Refuse the write, naming
the schema, rather than guess. The count stays tolerant of a missing or odd value -- the
service enforces the 1000-example cap anyway.
"""
try:
resp = ctl.get_dataset(datasetId=dataset_id)
except (BotoCoreError, ClientError) as e:
_die({
"error": "get_dataset failed for %s: %s. --mode add must read the dataset's "
"schemaType before building examples (it decides the example shape, and the wrong "
"shape rejects the whole batch), so this lookup cannot be skipped -- grant "
"bedrock-agentcore-control GetDataset on this dataset and re-run." % (dataset_id, e)
})
schema = resp.get("schemaType")
if schema not in ADD_SCHEMAS:
_die({
"error": "dataset %s declares schemaType %r; this helper can only build %s examples "
"from traces. Add to a dataset declaring one of those, or create a new one with "
"--mode create (which creates %s)."
% (dataset_id, schema, " or ".join(ADD_SCHEMAS), CREATE_SCHEMA_TYPE),
"schemaType": schema,
})
count = resp.get("exampleCount")
return schema, (count if isinstance(count, int) else None)
def main():
ap = argparse.ArgumentParser(
description="Build an AgentCore eval dataset from CloudWatch Omni traces."
)
ap.add_argument("--trace-ids", required=True, help="comma-separated trace ids")
ap.add_argument("--mode", choices=["create", "add"], default="create")
ap.add_argument("--dataset-name", help="name for the new dataset (mode create)")
ap.add_argument("--dataset-id", help="existing dataset id or name (mode add)")
ap.add_argument("--description")
ap.add_argument("--region", default="us-east-1")
ap.add_argument("--window-days", type=int, default=30, help="trace lookback window")
ap.add_argument(
"--i-have-confirmed",
action="store_true",
help="REQUIRED to write. Assert that the user confirmed this create/add. Without it the "
"helper refuses (exit 1) before any AWS call.",
)
args = ap.parse_args()
# A create/add is a real resource write. Refuse outright unless the caller passes
# --i-have-confirmed, which an agent may add only AFTER the user has confirmed. The
# helper cannot verify that confirmation happened; it only guarantees that an unflagged
# run exits non-zero having touched no AWS API.
if not args.i_have_confirmed:
_die({
"error": "refusing to write: creating/extending a dataset is a real resource write. "
"Confirm with the user first, then re-run with --i-have-confirmed. Do not pass the "
"flag on a request that has not been confirmed.",
"confirmationRequired": True,
})
if args.mode == "create" and not args.dataset_name:
_die({"error": "--dataset-name is required for --mode create"})
if args.mode == "add" and not (args.dataset_id or args.dataset_name):
_die({"error": "--dataset-id or --dataset-name is required for --mode add"})
seen, uniq, bad = set(), [], []
# Normalize to lowercase once: span trace ids are stored lowercase, the filter is an exact
# string match, and the boundary comparison relies on the query's case-sensitive `sort`.
for t in (x.strip().lower() for x in args.trace_ids.split(",")):
if not t or t in seen:
continue
if not _TRACE_ID_RE.match(t):
bad.append(t)
continue
seen.add(t)
uniq.append(t)
if bad:
_die({"error": "invalid trace id(s) (expected hex): %s" % ", ".join(bad[:5])})
if not uniq:
_die({"error": "no valid trace ids provided"})
notes = []
if len(uniq) > MAX_TRACES:
notes.append(
"captured the first %d of %d traces; run again for the rest" % (MAX_TRACES, len(uniq))
)
uniq = uniq[:MAX_TRACES]
session = boto3.Session(region_name=args.region)
omni = session.client("cloudwatchomni")
ctl = session.client("bedrock-agentcore-control")
# Resolve the target dataset's immutable schemaType BEFORE the (minutes-long) span query:
# it decides the shape every example is built in, and a dataset declaring a schema this
# helper cannot render should fail before any Omni work is paid for.
schema_type, existing, dsid = CREATE_SCHEMA_TYPE, None, None
if args.mode == "add":
dsid = _resolve_dataset_id(ctl, args.dataset_id or args.dataset_name)
schema_type, existing = _dataset_schema_and_count(ctl, dsid)
by_trace, truncated, boundary = fetch_spans_by_trace(omni, uniq, args.window_days)
if truncated:
notes.append(
"Omni SQL query hit the %d-row cap; only fully-fetched traces were captured. The boundary "
"trace is flagged metadata.partial=true; any trace reported 'row cap reached before this "
"trace' was not fetched — reduce --trace-ids or narrow --window-days and re-run for those."
% SPAN_ROW_LIMIT
)
examples, conversion_errors = [], []
for tid in uniq:
spans = by_trace.get(tid) or []
if not spans:
# On truncation the query stops at `boundary` (traceId asc), so a requested id that
# sorts after it was never reached — report that distinctly from a genuine miss.
if (
truncated and boundary is not None and tid > boundary
): # both lowercase; matches `sort traceId asc`
conversion_errors.append(
{
"traceId": tid,
"error": "row cap (%d) reached before this trace; not fetched"
% SPAN_ROW_LIMIT,
}
)
else:
conversion_errors.append({"traceId": tid, "error": "no spans found in window"})
continue
# Only the boundary trace can be mid-cut; every lower-sorted trace is complete.
partial = truncated and boundary is not None and tid == boundary
example = to_example(tid, spans, partial=partial)
if schema_type == THIRD_PARTY_SCHEMA:
example = to_third_party(example)
err = invalid(example, schema_type)
if err:
conversion_errors.append({"traceId": tid, "error": err})
continue
examples.append(example)
if not examples:
_die({"error": "no examples could be built", "conversionErrors": conversion_errors})
source = {"inlineExamples": {"examples": examples}}
if args.mode == "create":
kwargs = {
"datasetName": args.dataset_name,
"schemaType": CREATE_SCHEMA_TYPE,
"source": source,
"clientToken": str(uuid4()),
}
if args.description:
kwargs["description"] = args.description
try:
resp = ctl.create_dataset(**kwargs)
except (BotoCoreError, ClientError) as e:
_die({"error": "create_dataset failed: %s" % e, "conversionErrors": conversion_errors})
receipt = {
"mode": "create",
"datasetId": resp.get("datasetId"),
"status": resp.get("status"),
"schemaType": schema_type,
"examplesWritten": len(examples),
}
else:
if existing is not None and existing + len(examples) > MAX_DATASET_EXAMPLES:
_die({
"error": "dataset %s already holds %d examples; adding %d would exceed the service cap of %d "
"examples per dataset (the write would fail with 402 ServiceQuotaExceededException). "
"Create a new dataset (--mode create) for the remainder." % (dsid, existing, len(examples), MAX_DATASET_EXAMPLES),
"conversionErrors": conversion_errors,
})
try:
resp = ctl.add_dataset_examples(datasetId=dsid, source=source, clientToken=str(uuid4()))
except (BotoCoreError, ClientError) as e:
_die(
{
"error": "add_dataset_examples failed: %s" % e,
"schemaType": schema_type, # the shape the examples were built in
"conversionErrors": conversion_errors,
}
)
example_ids = resp.get("exampleIds") or []
receipt = {
"mode": "add",
"datasetId": dsid,
"schemaType": schema_type,
"examplesWritten": len(example_ids) or len(examples),
"exampleIds": example_ids,
}
if conversion_errors:
receipt["conversionErrors"] = conversion_errors
if notes:
receipt["notes"] = notes
print(json.dumps(receipt, default=str, indent=2))
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 an MCP server, Needs a command-line tool, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Phrasing that asks for actions without confirmation
- 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
- AWS
- Publisher
- AWS (Official)
- Source
- aws/agent-toolkit-for-aws · skills/core-skills/aws-observability · commit 0a218f8
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- NOTICE (added by AutoGineer from NOTICE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- aws/agent-toolkit-for-aws
AutoGineer is not affiliated with or endorsed by AWS.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download aws-observability.zip