Monitors as Code

What is Monitors as Code?

Monitors as Code (MaC) lets you define Monte Carlo monitors in YAML files and manage them with the Monte Carlo CLI. Optionally deploy through your CI/CD pipeline for automated, version-controlled monitor management. The CLI reads your YAML and syncs the declared state to Monte Carlo β€” creating, updating, or deleting monitors as needed.

New to MaC? Start with the Setting Up guide β€” it walks you from CLI install to your first running monitor. This page is the reference for project configuration, monitor types, and deployment.

πŸ“˜

Already using dbt? Apply monitors straight from your dbt project.

Two options, no separate tooling required:

  • Embed monitors in schema.yml β€” nest them under a model's meta block to keep monitor config next to the model it watches. See Embedded in dbt schema.yml.
  • Generate monitors from existing dbt tests β€” turn your unique, not_null, relationships, and singular tests into monitors automatically. See Generating monitors from dbt tests.

Project Configuration

Every MaC project needs a montecarlo.yml file in the project root:

FieldTypeRequiredDescription
versionintegeryesAlways 1. Currently the only supported version.
default_resourcestringconditionalWarehouse name or UUID. Required if multiple warehouses are configured. Find yours in Settings > Integrations > Warehouses and Lakes.
default_domainstringrecommendedDefault domain for monitors that don't specify domains. Effectively required β€” all new accounts need one domain per monitor.
namespacestringnoLogical grouping for monitors. When set here, takes precedence over --namespace CLI flag.
include_file_patternsarraynoGlob patterns for YAML files to scan. Default: **/*.yaml, **/*.yml.
exclude_file_patternsarraynoGlob patterns to skip.

# montecarlo.yml
version: 1
default_resource: my-snowflake
default_domain: my-domain

Where to put monitor definitions

Monitor definitions go in .yml files separate from montecarlo.yml. Two approaches:

Standalone YAML files β€” the standard approach. Place .yml files anywhere in your project directory. The CLI scans recursively. For dbt projects, place montecarlo.yml in the same directory as dbt_project.yml.

mac-project/
  montecarlo.yml        # project config only
  monitors/
    sales_checks.yml    # monitor definitions here
    pipeline_health.yml

Embedded in dbt schema.yml β€” nest monitors under a model's meta property to keep config next to the model it monitors. The meta key is required because dbt ignores unknown top-level properties. Use [[ ref('model_name') ]] for dbt ref resolution. Pass --dbt-manifest <path> when applying so the CLI can resolve refs β€” without it, the [[ ref() ]] string is passed through literally and the monitor will target an invalid table. See also: Generating monitors from dbt tests.

# models/schema.yml
version: 2

models:
  - name: orders
    meta:
      montecarlo:
        custom_sql:
          - name: orders_no_orphans
            description: "Orders must reference an existing customer"
            sql: |
              SELECT COUNT(*) FROM [[ ref('orders') ]]
              WHERE customer_id NOT IN (SELECT id FROM [[ ref('customers') ]])
            alert_conditions:
              - operator: GT
                threshold_value: 0
            schedule:
              type: fixed
              interval_minutes: 720
    columns:
      - name: order_id
        tests:
          - unique

You can also use [[ ref() ]] in standalone monitor files to reference dbt models:

data_source:
  table: "[[ref('orders')]]"

MaC uses [[ ]] instead of {{ }} to avoid conflicts with dbt's Jinja templating. The CLI resolves [[ ref('orders') ]] to the fully qualified table name (e.g., analytics:prod.orders) using the dbt manifest.

Monitor Types

MaC supports the same monitor categories as the Monte Carlo platform. Agent monitors are not MaC-configurable β€” create them through the Agent Toolkit or the Monte Carlo UI.

CategoryYAML keyMonitorWhat it monitors
Table monitorstableTable MonitorFreshness, volume, and schema changes across many tables. ML-based anomaly detection.
Table monitorsjson_schemaJSON Schema MonitorStructural changes in a JSON/variant column.
Metric monitorsmetricMetric MonitorField-level and table-level statistical metrics over time. ML or fixed thresholds.
Metric monitorsmetric_comparisonMetric ComparisonMetric differences between a source and target table.
Metric monitorsbulk_monitorBulk MonitorField-level metrics across many tables via asset selection.
Validation monitorsvalidationValidation MonitorRow-level data quality rules (predicate trees).
Validation monitorscustom_sqlCustom SQL MonitorArbitrary SQL query result against a threshold.
Job monitorsquery_performanceQuery Performance MonitorQuery runtime regressions.

For deprecated types (freshness, volume, field_health, dimension_tracking, comparison, field_quality), see migration guides.

Deploying

🚧

PUT semantics β€” updates replace the entire definition.

When you modify a monitor in YAML and re-apply, every field not in the YAML resets to its default. Always include all fields you care about β€” not just the ones you're changing.

Compile

montecarlo monitors compile --namespace <namespace> [--project-dir <dir>]

Parses monitor YAML files and checks for syntax errors. Does not validate field names, values, or constraints β€” does not flag unknown or misspelled field names. Use check-jsonschema for structural validation or apply --dry-run for full validation. Useful as a fast first gate in CI pull-request checks (no API credentials required).

Apply Changes

montecarlo monitors apply --namespace <namespace> [--project-dir <dir>]

The apply command:

  1. Scans for all monitor YAML in the project (standalone and dbt-embedded)
  2. Creates new monitors, updates changed monitors, deletes removed monitors
  3. Scope is limited to the specified namespace β€” monitors in other namespaces are untouched

Dry Run

Preview what would change without applying:

montecarlo monitors apply --namespace <namespace> --dry-run

Namespaces

A namespace is a string label that isolates a set of MaC-managed monitors β€” it has no configuration of its own and exists implicitly when you first apply to it. Each apply manages only its namespace β€” monitors from other namespaces are unaffected. This lets multiple teams, projects, or CI/CD pipelines manage monitors independently without interfering with each other.

Use cases:

  • Different teams manage monitors independently
  • Separate namespaces for dbt-managed vs standalone monitors
  • Isolate CI/CD pipelines that manage different monitor groups

Namespaces can be set via --namespace CLI flag, in montecarlo.yml, or per-monitor in the YAML. Namespaces are created implicitly on the first apply. Limit: 2,000 resources per namespace (CLI 0.52.0+). Each monitor definition counts as one resource. At 2,000 the CLI rejects apply with an error.

To move monitors between namespaces, delete from the old namespace and re-apply to the new one. Monitor incident history is not transferred.

🚧

Shared namespace danger

Each apply replaces ALL monitors in the namespace. If two teams share a namespace, each deploy overwrites the other's monitors. Use separate namespaces per team or pipeline.

List existing namespaces and monitors:

montecarlo monitors namespaces              # list all namespaces
montecarlo monitors list --namespace <ns>   # list monitors in a namespace
🚧

Precedence: montecarlo.yml wins over --namespace.

When namespace is set in montecarlo.yml, it takes precedence over the --namespace CLI flag. The CLI prints a message noting that the project-file value is being used and the flag value ignored (e.g. namespace: <project-ns> found in montecarlo.yml ignoring value passed with --namespace=<flag-ns>). This is a common gotcha in CI/CD pipelines that pass --namespace expecting it to override the project file. Remove the namespace field from montecarlo.yml if you need the CLI flag to control namespace selection.

Delete a Namespace

Remove all monitors in a namespace:

montecarlo monitors delete --namespace <namespace>

CI/CD Integration

See the CI/CD Integration guide for GitHub Actions, GitLab CI, and CircleCI patterns.

The core pattern:

pip install montecarlodata
montecarlo monitors apply \
  --namespace ${NAMESPACE} \
  --project-dir ${PROJECT_DIR} \
  --auto-yes

The CLI reads MCD_DEFAULT_API_ID and MCD_DEFAULT_API_TOKEN from the environment β€” set them as CI secrets rather than assigning them on the command line.

Use --auto-yes only in CI to skip confirmation prompts.

More Information

Schema Validation

The published JSON Schema at https://clidocs.getmontecarlo.com/mac/schema.json can be used for structural validation of your YAML files. See Validation Tiers below.

Validation Tiers

Three levels of validation, from fastest to most thorough:

# 1. Syntax check (fastest, no credentials)
montecarlo monitors compile --namespace <namespace>

# 2. Structural validation (field names, types, enums β€” no API needed)
pip install check-jsonschema
check-jsonschema --schemafile https://clidocs.getmontecarlo.com/mac/schema.json monitors.yml

# 3. Full validation (semantic checks, table existence, metric names β€” requires API credentials)
montecarlo monitors apply --namespace <ns> --dry-run
πŸ“˜

Schema validation limits

Tier 2 (check-jsonschema) uses a shared schema for all types. Per-type restrictions β€” crontab not supported on metric monitors, operator rejected on table monitors, loose schedule limited to json_schema β€” are only enforced at tier 3 (apply --dry-run). A YAML that passes tier 2 may still fail at deploy.

Default Field Stripping

Exported or previewed YAML (via --dry-run, the UI's Generate YAML button, or MCP tools) omits fields that match defaults. schedule.type: fixed and alert_conditions[].type: threshold won't appear because they're defaults. Both forms β€” compact and explicit β€” are valid input.

Exporting from the UI

Create a monitor in the UI, then use the Generate YAML button on the monitor details page to copy its definition into your codebase.

Export programmatically:

montecarlo monitors get-template --namespace <namespace> --project-dir <dir>
montecarlo monitors convert-to-mac --namespace <namespace> --project-dir <dir>
montecarlo monitors export-as-latest --namespace <namespace>

get-template exports monitors already managed by MaC. convert-to-mac converts UI-created monitors into MaC definitions. export-as-latest exports the current live state of monitors in a namespace, overwriting any local definitions.

🚧

Deprecated types in exports

If your account has legacy monitors (e.g., field_health), convert-to-mac may export deprecated types that fail on re-apply. Review the exported YAML and migrate deprecated types (see migration guides) before running apply.

Reference Pages