Install
$ agentstack add skill-monte-carlo-data-mc-agent-toolkit-generate-validation-notebook ✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
About
> Tip: This skill works well with Sonnet. Run /model sonnet before invoking for faster generation.
Generate a SQL Notebook with validation queries for dbt changes.
Arguments: $ARGUMENTS
Parse the arguments:
- Target (required): first argument — a GitHub PR URL or local dbt repo path
- MC Base URL (optional):
--mc-base-url— defaults tohttps://getmontecarlo.com - Models (optional):
--models— comma-separated list of model filenames (without.sqlextension) to generate queries for. Only these models will be included. By default, all changed models are included up to a maximum of 10.
Setup
Prerequisites:
gh(GitHub CLI) — required for PR mode. Must be authenticated (gh auth status).python3— required for helper scripts.pyyaml— install withpip3 install pyyaml(orpip install pyyaml,uv pip install pyyaml, etc.)
Note: Generated SQL uses ANSI-compatible syntax that works across Snowflake, BigQuery, Redshift, and Athena. Minor adjustments may be needed for specific warehouse quirks.
This skill includes two helper scripts in ${CLAUDE_PLUGIN_ROOT}/skills/generate-validation-notebook/scripts/:
resolve_dbt_schema.py- Resolves dbt model output schemas fromdbt_project.ymlrouting rules and model config overrides.generate_notebook_url.py- Encodes notebook YAML into a base64 import URL and opens it in the browser.
Mode Detection
Auto-detect mode from the target argument:
- If target looks like a URL (contains
://orgithub.com) -> PR mode - If target is a path (
.,/path/to/repo, relative path) -> Local mode
Context
This command generates a SQL Notebook containing validation queries for dbt changes. The notebook can be opened in the MC Bridge SQL Notebook interface for interactive validation.
The output is an import URL that opens directly in the notebook interface:
/notebooks/import#
Key Features:
- Database Parameters: Two
textparameters (prod_dbanddev_db) for selecting databases - Schema Inference: Automatically infers schema per model from
dbt_project.ymland model configs - Single-table queries: Basic validation queries using
{{prod_db}}.. - Comparison queries: Before/after queries comparing
{{prod_db}}vs{{dev_db}} - Flexible usage: Users can set both parameters to the same database for single-database analysis
Notebook YAML Spec Reference
Key structure:
version: 1
metadata:
id: string # kebab-case + random suffix
name: string # display name
created_at: string # ISO 8601
updated_at: string # ISO 8601
default_context: # optional database/schema context
database: string
schema: string
cells:
- id: string
type: sql | markdown | parameter
content: string # SQL, markdown, or parameter config (JSON)
display_type: table | bar | timeseries
Parameter Cell Spec
Parameter cells allow defining variables referenced in SQL via {{param_name}} syntax:
- id: param-prod-db
type: parameter
content:
name: prod_db # variable name
config:
type: text # free-form text input
default_value: "ANALYTICS"
placeholder: "Prod database"
display_type: table
Parameter types:
text: Free-form text input (used for database names)schema_selector: Two dropdowns (database -> schema), value stored asDATABASE.SCHEMAdropdown: Select from predefined options
Task
Generate a SQL Notebook with validation queries based on the mode and target.
Phase 1: Get Changed Files
The approach differs based on mode:
If PR mode (GitHub PR):
- Extract the PR number and repo from the target URL.
- Example:
https://github.com/monte-carlo-data/dbt/pull/3386-> owner=monte-carlo-data, repo=dbt, PR=3386
- Fetch PR metadata using
gh:
gh pr view --repo / --json number,title,author,mergedAt,headRefOid
- Fetch the list of changed files:
gh pr view --repo / --json files --jq '.files[].path'
- Fetch the diff:
gh pr diff --repo /
- Filter the changed files list to only
.sqlfiles undermodels/orsnapshots/directories (at any depth — e.g.,models/,analytics/models/,dbt/models/). These are the dbt models to analyze. If no model SQL files were changed, report that and stop.
- For each changed model file, fetch the full file content at the head SHA:
gh api repos///contents/?ref= --jq '.content' | python3 -c "import sys,base64; sys.stdout.write(base64.b64decode(sys.stdin.read()).decode())"
- Fetch dbt_project.yml for schema resolution. Detect the dbt project root by looking at the changed file paths — find the common parent directory that contains
dbt_project.yml. Try these paths in order until one succeeds:
gh api repos///contents//dbt_project.yml?ref= --jq '.content' | python3 -c "import sys,base64; sys.stdout.write(base64.b64decode(sys.stdin.read()).decode())"
Common ` locations: analytics, . (repo root), dbt, transform`. Try each until found.
Save dbt_project.yml to /tmp/validation_notebook_working//dbt_project.yml.
If Local mode (Local Directory):
- Change to the target directory.
- Get current branch info:
git rev-parse --abbrev-ref HEAD
- Detect base branch - try
main,master,developin order, or use upstream tracking branch.
- Get the list of changed SQL files compared to base branch:
git diff --name-only ...HEAD -- '*.sql'
- Filter to only
.sqlfiles undermodels/orsnapshots/directories (at any depth — e.g.,models/,analytics/models/,dbt/models/). If no model SQL files were changed, report that and stop.
- Get the diff for each changed file:
git diff ...HEAD --
- Read model files directly from the filesystem.
- Find dbt_project.yml:
find . -name "dbt_project.yml" -type f | head -1
- For notebook metadata in local mode, use:
- ID:
local-- - Title:
Local: - Author: Output of
git config user.name - Merged: "N/A (local)"
Model Selection (applies to both modes)
After filtering to .sql files under models/ or snapshots/:
- If
--modelswas specified: Filter the changed files list to only include models whose filename (without.sqlextension, case-insensitive) matches one of the specified model names. If any specified model is not found in the changed files, warn the user but continue with the models that were found. If none match, report that and stop.
- Model cap: If more than 10 models remain after filtering, select the first 10 (by file path order) and warn the user:
`` ⚠️ models changed — generating validation queries for the first 10 only. To generate for specific models, re-run with: --models Skipped models: ``
Phase 2: Parse Changed Models
For EACH changed dbt model .sql file, parse and extract:
2a. Model Metadata
Output table name -- Derive from file name:
/models//.sql-> table is `` (uppercase, taken from the filename)
Output schema -- Use the schema resolution script:
- Setup: Save
dbt_project.ymland model files to/tmp/validation_notebook_working//preserving paths:
`` /tmp/validation_notebook_working// +-- dbt_project.yml +-- models/ +-- /.sql ``
- Run the script for each model:
``bash python3 ${CLAUDE_PLUGIN_ROOT}/skills/generate-validation-notebook/scripts/resolve_dbt_schema.py /tmp/validation_notebook_working//dbt_project.yml /tmp/validation_notebook_working//models//.sql ``
- Error handling: If the script fails, STOP immediately and report the error. Do NOT proceed with notebook generation if schema resolution fails.
- Output: The script prints the resolved schema (e.g.,
PROD,PROD_STAGE,PROD_LINEAGE)
Note: Do NOT manually parse dbtproject.yml or model configs for schema -- always use the script. It handles model config overrides, dbtproject.yml routing rules, PROD_ prefix for custom schemas, and defaults to PROD.
Config block -- Look for {{ config(...) }} and extract:
materialized-- 'table', 'view', 'incremental', 'ephemeral'unique_key-- the dedup key (may be a string or list)cluster_by-- clustering fields (may contain the time axis)
Core segmentation fields -- Scan the entire model SQL for fields likely to be business keys:
- Fields named
*_id(e.g.,account_id,resource_id,monitor_id) that appear in JOIN ON, GROUP BY, PARTITION BY, orunique_key - Deduplicate and rank by frequency. Take the top 3.
Time axis field -- Detect the model's time dimension (in priority order):
is_incremental()block: field used in the WHERE comparisoncluster_byconfig: timestamp/date fields- Field name conventions:
ingest_ts,created_time,date_part,timestamp,run_start_time,export_ts,event_created_time - ORDER BY DESC in QUALIFY/ROW_NUMBER
If no time axis is found, skip time-axis queries for this model.
2b. Diff Analysis
Parse the diff hunks for this file. Classify each changed line:
- Changed fields -- Lines added/modified in SELECT clauses or CTE definitions. Extract the output column name.
- Changed filters -- Lines added/modified in WHERE clauses.
- Changed joins -- Lines added/modified in JOIN ON conditions.
- Changed unique_key -- If
unique_keyin config was modified, note both old and new values. - New columns -- Columns in "after" SELECT that don't appear in "before" (pure additions).
2c. Model Classification
Classify each model as new or modified based on the diff:
- If the diff for this file contains
new file mode→ classify as new - Otherwise → classify as modified
This classification determines which query patterns are generated in Phase 3.
Note: For new models, Phase 2b diff analysis is skipped (there is no "before" to compare against). Phase 2a metadata extraction still applies.
Phase 3: Generate Validation Queries
For each changed model, generate the applicable queries based on its classification (new vs modified).
CRITICAL: Parameter Placeholder Syntax
Use double curly braces {{...}} for parameter placeholders. Do NOT use ${...} or any other syntax.
Correct: {{prod_db}}.PROD.AGENT_RUNS Wrong: ${prod_db}.PROD.AGENT_RUNS
Table Reference Format:
- Use
{{prod_db}}..for prod queries - Use
{{dev_db}}..for dev queries - `` is hardcoded per-model using the output from the schema resolution script
Query Patterns for NEW Models
For new models, all queries target {{dev_db}} only. No comparison queries are generated since no prod table exists.
Pattern 7-new: Total Row Count
Trigger: Always.
SELECT COUNT(*) AS total_rows
FROM {{dev_db}}..
Pattern 9: Sample Data Preview
Trigger: Always.
SELECT *
FROM {{dev_db}}..
LIMIT 20
Pattern 2-new: Core Segmentation Counts
Trigger: Always.
SELECT
,
COUNT(*) AS row_count
FROM {{dev_db}}..
GROUP BY
ORDER BY row_count DESC
LIMIT 100
Pattern 5: Uniqueness Check
Trigger: Always for new models (verify unique_key constraint from the start).
SELECT
COUNT(*) AS total_rows,
COUNT(DISTINCT ) AS distinct_keys,
COUNT(*) - COUNT(DISTINCT ) AS duplicate_count
FROM {{dev_db}}..
SELECT , COUNT(*) AS n
FROM {{dev_db}}..
GROUP BY
HAVING COUNT(*) > 1
ORDER BY n DESC
LIMIT 100
Pattern 6-new: NULL Rate Check (all columns)
Trigger: Always. Checks all output columns since everything is new.
SELECT
COUNT(*) AS total_rows,
SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) AS _null_count,
ROUND(100.0 * SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS _null_pct,
SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) AS _null_count,
ROUND(100.0 * SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS _null_pct
-- repeat for each output column
FROM {{dev_db}}..
Pattern 8: Time-Axis Continuity
Trigger: Model is materialized='incremental' OR a time axis field was identified.
SELECT
CAST( AS DATE) AS day,
COUNT(*) AS row_count
FROM {{dev_db}}..
WHERE >= CURRENT_TIMESTAMP - INTERVAL '14' DAY
GROUP BY day
ORDER BY day DESC
LIMIT 30
Query Patterns for MODIFIED Models
For modified models, single-table queries use {{prod_db}} and comparison queries use both.
Pattern 7: Total Row Count
Trigger: Always.
SELECT COUNT(*) AS total_rows
FROM {{prod_db}}..
Pattern 9: Sample Data Preview
Trigger: Always.
SELECT *
FROM {{prod_db}}..
LIMIT 20
Pattern 2: Core Segmentation Counts
Trigger: Always.
SELECT
,
COUNT(*) AS row_count
FROM {{prod_db}}..
GROUP BY
ORDER BY row_count DESC
LIMIT 100
Pattern 1: Changed Field Distribution
Trigger: Changed fields found in Phase 2b. Exclude added columns (from "New columns" in Phase 2b) — only include fields that exist in prod.
SELECT
,
COUNT(*) AS row_count,
ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER(), 2) AS pct
FROM {{prod_db}}..
GROUP BY
ORDER BY row_count DESC
LIMIT 100
Pattern 5: Uniqueness Check
Trigger: JOIN condition changed, unique_key changed, or model is incremental.
SELECT
COUNT(*) AS total_rows,
COUNT(DISTINCT ) AS distinct_keys,
COUNT(*) - COUNT(DISTINCT ) AS duplicate_count
FROM {{dev_db}}..
SELECT , COUNT(*) AS n
FROM {{dev_db}}..
GROUP BY
HAVING COUNT(*) > 1
ORDER BY n DESC
LIMIT 100
Pattern 6: NULL Rate Check
Trigger: New column added, or column wrapped in COALESCE/NULLIF.
Important: Added columns (from "New columns" in Phase 2b) do NOT exist in prod yet. For added columns, query {{dev_db}} only. For modified columns (COALESCE/NULLIF changes), compare both databases.
For added columns (dev only):
SELECT
COUNT(*) AS total_rows,
SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) AS null_count,
ROUND(100.0 * SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{dev_db}}..
For modified columns (prod vs dev):
SELECT
'prod' AS source,
COUNT(*) AS total_rows,
SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) AS null_count,
ROUND(100.0 * SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{prod_db}}..
UNION ALL
SELECT
'dev' AS source,
COUNT(*) AS total_rows,
SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) AS null_count,
ROUND(100.0 * SUM(CASE WHEN IS NULL THEN 1 ELSE 0 END) / NULLIF(COUNT(*), 0), 2) AS null_pct
FROM {{dev_db}}..
Pattern 8: Time-Axis Continuity
Trigger: Model is materialized='incremental' OR a time axis field was identified.
SELECT
CAST( AS DATE) AS day,
COUNT(*) AS row_count
FROM {{prod_db}}..
WHERE >= CURRENT_TIMESTAMP - INTERVAL '14' DAY
GROUP BY day
ORDER BY day DESC
LIMIT 30
Pattern 3: Before/After Comparison
Trigger: Always (for changed fields + top segmentation field). Modified models only.
Important: Exclude added columns (from "New columns" in Phase 2b) from ``. Only use fields that exist in BOTH prod and dev. Added columns don't exist in prod and will cause query errors.
WITH prod AS (
SELECT , COUNT(*) AS cnt
FROM {{prod_db}}..
GROUP BY
),
dev AS (
SELECT , COUNT(*) AS cnt
FROM {{dev_db}}..
GROUP BY
)
SELECT
COALESCE(b., d.) AS ,
COALESCE(b.cnt, 0) AS cnt_prod,
COALESCE(d.cnt, 0) AS cnt_dev,
COALESCE(d.cnt, 0) - COALESCE(b.cnt, 0) AS diff
FROM prod b
FULL OUTER JOIN dev d ON b. = d.
ORDER BY ABS(diff) DESC
LIMIT 100
Pattern 7b: Row Count Comparison
Trigger: Always. Modified models only.
SELECT
…
## Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- **Author:** [monte-carlo-data](https://github.com/monte-carlo-data)
- **Source:** [monte-carlo-data/mc-agent-toolkit](https://github.com/monte-carlo-data/mc-agent-toolkit)
- **License:** Apache-2.0
- **Homepage:** https://docs.getmontecarlo.com/docs/agent-toolkit
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet — be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.