← Catalog

pi-snowflake-query

Pi extension for read-only Snowflake queries via the team `claude` connection, with a specialized snowflake-analyst agent.

Extension

Install

Install with PiG

pig install npm:pi-snowflake-query

Install with Pi

pi install npm:pi-snowflake-query
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "skills": [
    "./skills"
  ],
  "extensions": [
    "./snowflake-query.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.3.0 (README.md). PiG does not review it.

pi-snowflake-query

Pi extension for read-only Snowflake queries via the team claude connection plus a dbt tool that wraps the local dbt env (run, test, build, compile, seed, snapshot, debug, deps, parse, clean, docs-generate, run-operation, list, source-freshness). Ships a snowflake-analyst subagent that uses openai-codex/gpt-5.4-mini.

The extension enforces the safety rules from the dbt repo's CLAUDE.md:

  • Every Snowflake query uses the official snowflake-sdk driver. It tests [connections.<SNOWFLAKE_CONNECTION>] in connections.toml before trying SNOWFLAKE_* environment credentials.
  • Only one SQL statement per query-tool call. No ;-chained DDL/DML smuggling. snowflake_analytics_query additionally confines relation access to analytics.dbt.
  • The first SQL keyword must be one of SELECT, WITH, SHOW, DESC, DESCRIBE, EXPLAIN, LIST. Anything else is rejected before exec.
  • A tool_call gate blocks direct bash invocations of snow sql that don't use the configured connection or that look destructive.
  • dbt --full-refresh is opt-in and is refused when the selector mentions raw tables (matches the "never full-refresh raw tables" rule — those models permanently delete their S3 source files).
  • Snowflake query rows never enter the agent context. Every query writes its complete result plus a shape index to an isolated local directory and returns only paths, shape metadata, and local inspection examples. dbt output remains bounded and spills to a temp file when it exceeds the context limits.
  • Every database-capable dbt command is blocked unconditionally — not only run/build/seed/snapshot, but also test/compile/list/parse/docs-generate/source-freshness. A subcommand's label, declared hooks, or a role's name do not prove a dbt invocation cannot execute SQL: dbt evaluates full project Jinja, including runtime-only {% if execute %} blocks that no static check can rule out. There is currently no supported way to run these commands against a dev destination through this extension. See "Settings: tool disabling and production-write policy" below and Security.

Install

Bundled with this repo. To run it as a one-off extension:

pi -e extensions/snowflake-query/snowflake-query.ts

To wire it into the standard team runtime, add the same -e flag to bin/pi-team.sh or bin/pi-safe.sh.

To install as a package elsewhere:

pi install npm:pi-snowflake-query

Requirements

  • A [connections.claude] profile in ~/.snowflake/connections.toml (or whatever name you set via SNOWFLAKE_CONNECTION) with account, user, and password. The driver tests this profile first, then falls back to SNOWFLAKE_ACCOUNT, SNOWFLAKE_USER, and SNOWFLAKE_PASSWORD.
  • For the dbt tool: Python with dbt-core and the selected adapter installed. The extension auto-detects it (see below); set DBT_PYTHON only to override.

Configuration

Env varDefaultPurpose
SNOWFLAKE_CONNECTIONclaudeProfile name in connections.toml to test before environment fallback.
SNOWFLAKE_CONFIG_PATH~/.snowflake/connections.tomlOverride the profile file path.
SNOWFLAKE_QUERY_TIMEOUT_MS120000Per-query timeout in ms. Hard ceiling is 600000 ms (10 min).
DBT_PYTHONauto-detectedPython executable with dbt-core and the selected adapter installed.
DBT_PROJECT_DIRauto-detectedWorking directory used for dbt invocations.
DBT_PROFILES_DIRauto-detectedPassed to dbt-core as --profiles-dir.
DBT_TIMEOUT_MS1800000Per-invocation dbt timeout in ms. Hard ceiling is 3600000 ms (1 hour).

dbt environment auto-detection

All three dbt settings are resolved from the filesystem at startup, so the dbt tool works with no DBT_* variables set. An explicit env var always wins, and /snowflake-conn prints each resolved value with the rule that produced it.

Python interpreter — first match wins:

  1. DBT_PYTHON.
  2. $VIRTUAL_ENV/bin/python, if a dbt entrypoint sits beside it.
  3. <project>/.venv, <project>/venv, or <project>/env, same check.
  4. The dbt executable on $PATH, resolved through symlinks, a shell wrapper's DBT_BIN=... assignment, or a console script's shebang.
  5. python3.

Ordering matters when a machine has several dbt installs: an activated virtualenv wins over whatever dbt is on $PATH, so source .venv/bin/activate is how you pin a project's exact dbt-core/dbt-snowflake releases. /snowflake-conn prints the resolved versions so a mis-detected environment is visible before you run anything.

Project directory — DBT_PROJECT_DIR, else the nearest ancestor of the cwd containing dbt_project.yml, else the project a dbt wrapper on $PATH declares (DEFAULT_PROJECT_DIR= or --project-dir, accepted only when that path really is a dbt project), else a sibling data-dbt checkout found from a cwd ancestor, else the cwd. So the tool works from any subdirectory of the project and from another repo in the Aptive workspace. When nothing resolves to a dbt project the dbt tool fails immediately with that path named, rather than passing a doomed invocation to dbt.

Profiles directory — DBT_PROFILES_DIR, else ~/.dbt when it holds a profiles.yml, else dbt's own default. The override of dbt's default matters: dbt prefers ./profiles.yml when the project has one, and a checked-in project profiles.yml is usually a credential-less CI profile, which fails at connect time with 251006: Password is empty. Developer credentials live in ~/.dbt. Pass the dbt tool's profilesDir parameter for a one-off override.

Config file

Auto-detection cannot know which dbt target you want, or which targets your profile defines. Copy snowflake-query.example.yaml to snowflake-query.yaml beside the extension for those, plus any path the detector gets wrong:

target: claude
targets:
  - dev
  - prod
  - claude
python: ~/aptive-data/data-dbt/.venv/bin/python

Every key is optional and unset keys stay auto-detected, so an empty file behaves like no file. target supplies the target when a dbt tool call does not name one; targets restricts what the tool accepts, so a typo is rejected before dbt connects. SNOWFLAKE_QUERY_CONFIG points at a different path, and snowflake-query.yaml is gitignored.

Precedence for the three paths is env var, then this file, then detection: a per-invocation override beats persistent config, which beats a guess.

The format is a flat map of scalars plus one list, with ~ expanded — no nesting, anchors, or multi-line strings. Unknown keys and malformed lines are reported by line number and fail the dbt tool rather than being silently dropped.

Settings: tool disabling and production-write policy

Pi's Settings type has no index signature and no extension API exposes arbitrary settings.json keys, so this is not read through a Pi API call — the extension reads .pi/settings.json (project) and ~/.pi/agent/settings.json (global) directly off disk, under a namespaced snowflakeQuery key. There is also no extension API to ask Pi whether the current project has been granted project trust, even though Pi itself only loads .pi/settings.json after that decision. So this does not replicate Pi's own project-overrides-global precedence for the whole namespace:

  • disabledTools only narrows capability (it can never grant a write), so it is honored from both layers and the two are unioned — a project can add disabled tools but can never re-enable one the global/user settings disabled.
  • devDatabase, devSchema, and preferredRole are safety-relaxing, so they are honored from the global (user) settings file only. Project settings cannot set them — an untrusted project's checked-in .pi/settings.json could otherwise redefine devSchema/preferredRole to match the credential's real production role/schema and turn the write gate into a rubber stamp, purely by running Pi inside that directory. A project attempt to set these keys is reported (see /snowflake-conn and SETTINGS_ERRORS) and otherwise ignored.
  • An unreadable settings file (exists but fails to read, e.g. a permission error) or one with invalid JSON is not treated the same as an absent file: it fails that layer closed by disabling every known tool, rather than silently proceeding as if nothing were configured (which could re-enable a tool an admin meant to keep off). JSON parse-error messages surfaced here are Node's own SyntaxError text (a token and a character position only — never file content), so this never echoes settings content back.

snowflake-query.settings.example.json shows the shape; merge its snowflakeQuery key into your global ~/.pi/agent/settings.json — do not replace the whole file with it, since a real settings.json has unrelated keys too, and do not put devDatabase/devSchema/preferredRole in a project .pi/settings.json, since they are ignored there:

{
  "snowflakeQuery": {
    "disabledTools": ["dbt", "snowflake_create_raw_external_table"],
    "devDatabase": "analytics",
    "devSchema": "DBT_PORENTA",
    "preferredRole": "CLAUDE_CODE_ROLE"
  }
}
KeyTypeDefaultWhere it's honoredPurpose
disabledToolsstring[][]global + project (union)Tool names to not register at all this session: snowflake_analytics_query, snowflake_global_query, snowflake_query, snowflake_describe, snowflake_create_raw_external_table, dbt. A disabled tool is never registered with Pi, so it cannot be called by the model, a subagent, or any nested invocation — there is no separate re-enable path. Unknown entries are reported (see /snowflake-conn) and otherwise ignored, so a typo fails visibly rather than silently disabling nothing.
devDatabasestring"analytics"global onlyDatabase snowflake_create_raw_external_table's destination must resolve to in order to be considered dev-confined. Not used for dbt — see below.
devSchemastring"DBT_PORENTA"global onlySchema snowflake_create_raw_external_table's destination must resolve to in order to be considered dev-confined. Not used for dbt — see below.
preferredRolestring"CLAUDE_CODE_ROLE"global onlyThe only Snowflake role snowflake_create_raw_external_table ever considers safe to write with. If the resolved role for the pinned connection is anything else — including the role the credential normally has for ordinary (non-agent) use, or a role that cannot be verified because of ambiguous credential fallback (see Security) — the write is blocked and the extension falls back to read-only. This selection is passive only: the extension never requests, switches to, or attempts to acquire this role itself; it only recognizes an operation as safe when the role already in effect happens to match. On a machine whose credentials do not have this role at all, the correct behavior is read-only fallback, which is exactly what happens.

Policy semantics (see _shared/write-policy.ts and _shared/snowflake-role.ts for the enforcing code and tests/write-policy.test.ts and tests/snowflake-role.test.ts for the regression coverage):

  • Reads through the dedicated SQL query tools are unaffected. snowflake_global_query, snowflake_analytics_query, snowflake_query, snowflake_describe already structurally allow only SELECT/WITH/SHOW/DESC/DESCRIBE/EXPLAIN/LIST, plus a narrow allowlist for Snowflake's SYSTEM$... namespace (_shared/sql-gate.ts, see Security); nothing here changes that.
  • Every database-capable dbt command is blocked unconditionally, not just by default. run, build, seed, snapshot, run-operation, test, compile, docs-generate, source-freshness, list, and parse all evaluate full project Jinja (including any custom macro or model body that calls run_query/statement, or a runtime-only {% if execute %} block) under the connection's resolved role. No selector, target, resolved node schema/database, declared hook, or role name this extension could read proves a model/macro body is free of side effects: dbt ls itself resolves with execute = false and would report a hook-free, built-in- materialization node exactly like a safe one, even when that same node's body runs arbitrary SQL once execute becomes true during run/build/compile/test/etc. There is no dev-schema proof this extension can construct from outside the Jinja evaluation itself, so devDatabase/devSchema/preferredRole have no effect on dbt — only deps, clean, and debug ever run. deps/clean never evaluate project Jinja or touch Snowflake; debug is dbt-core's own fixed, non-project-customizable connectivity check.
  • Both the tool_call pre-flight gate and the dbt tool's own execute() call the same blockDatabaseCapableDbtCommand function, so a blocked command is blocked in both places identically. The check is a pure, synchronous lookup on the command name alone — no child process is spawned and no Snowflake/dbt connection is attempted for any of these commands, ever.
  • snowflake_create_raw_external_table is the one place devDatabase, devSchema, and preferredRole still apply — see "Security" below for its (narrower, Jinja-free) proof.

Limitations — read before relying on this as a SQL/privilege firewall

  • This enforces the extension's own tool surface, not Snowflake privileges. Nothing here revokes, grants, or inspects what a role can actually do; a role with broader Snowflake privileges than this policy intends is a Snowflake configuration fact this extension cannot see or change.
  • No project-trust check. This module has no API to learn whether Pi has granted the current project trust, so it cannot gate project settings on that decision the way Pi itself does for .pi/settings.json. Instead, safety-relaxing keys are restricted to the global settings layer only (see "Settings" above) — a deliberate, narrower substitute for a trust check this extension cannot perform, not an equivalent of one.
  • debug is assumed safe based on dbt-core's own documented behavior (a fixed connectivity check, no project macros/hooks), which this extension has no way to verify at runtime without executing it. If a future dbt-core version changes that behavior, this assumption would need revisiting.
  • There is currently no supported way to run a database-capable dbt command (including read-labeled ones like test/compile) against a dev destination through this extension. An earlier version of this policy tried to prove confinement from dbt ls-resolved node metadata (role, target schema/database, declared hooks, resolved per-node schema/database/materialization/hooks); that proof does not hold, because none of those checks constrain what a model or macro body executes once execute is true (see "Settings" above). Closing this gap would require a boundary this extension cannot construct — e.g. a Snowflake role whose grants are independently confined to the dev schema regardless of what SQL the dbt process issues — not a richer static check of dbt-ls output.
  • The SYSTEM$... SQL function gate (_shared/sql-gate.ts) is a narrow, explicit allowlist, not a complete side-effect guarantee: Snowflake external functions and ordinary UDFs are syntactically indistinguishable from any other function call and cannot be proven free of side effects by any lexical gate. See Security.
  • Nothing in this extension is OS-level isolation. An agent with bash access can always reach Snowflake or dbt directly outside this extension's tools — the tool_call gate in _shared/safety.ts only recognizes specific snow sql/snowsql/Python-one-liner shapes (see its own doc comment for exactly which). Arbitrary shell or code execution is not, and cannot be, made safe by an extension-level guard; this is a defense against the model routing through this tool's intended path, not a sandbox.
  • Preferred-role selection is passive only. This extension never requests, switches, or attempts to elevate to preferredRole; it only recognizes an operation as safe when the credential's resolved role already matches. On a machine whose credentials never have preferredRole available, every write stays blocked — there is no path to acquiring that role through this extension, by design.
  • An unproven or ambiguous role is never read as the environment's role. Every credential source the connector may attempt must declare the same explicit role. A present TOML profile without a role never inherits the environment's role. Conflicting roles deny even if one source appears incomplete, because missing secrets do not prove it cannot connect. This is a conservative configuration check, not a live CURRENT_ROLE() check.

Bundled skills

This package ships two Pi Agent Skills:

  • pi-snowflake-query at skills/pi-snowflake-query/SKILL.md for general read-only Snowflake and dbt work.
  • diagnose-aptive-dbt-errors at skills/diagnose-aptive-dbt-errors/SKILL.md for evidence-based Aptive dbt failure diagnosis using this extension's snowflake_analytics_query, snowflake_global_query, snowflake_describe, and dbt tools.

Load them with the package or invoke /skill:pi-snowflake-query or /skill:diagnose-aptive-dbt-errors explicitly. The package's skills/**/* manifest includes each skill and its references.

Tools

  • snowflake_analytics_query — Run a single read-only SELECT or WITH query for analytics.dbt dbt models. Metadata commands, table functions, and IDENTIFIER() are rejected so their alternate object-reference grammars cannot escape the analytics schema restriction. A bare model name such as model_marketing_sms_audiences is rewritten to analytics.dbt.model_marketing_sms_audiences; analytics.<model> is rewritten the same way. Relations outside analytics.dbt are rejected. It accepts query, warehouse, format, outputDir, and timeoutMs.
  • snowflake_global_query — Run a single read-only SQL statement against other Snowflake schemas, including SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY. It accepts query, optional database, schema, warehouse, format, outputDir, and timeoutMs.
  • snowflake_query — Deprecated compatibility alias for snowflake_global_query.
  • snowflake_describe — Convenience wrapper around DESC TABLE <name>. Use this before issuing a SELECT to avoid wasted warehouse resumes. It accepts an optional outputDir.
  • snowflake_create_raw_external_table — Creates a new IF NOT EXISTS external source table for the raw-ingestion pattern. It is limited to raw and raw_staging, the approved stages and file formats, and cannot replace or drop existing objects. Create the dbt raw model and schema YAML separately.

Local query output

All Snowflake query tools stream complete rows to a unique pi-snowflake-* directory under os.tmpdir(). Pass outputDir to snowflake_analytics_query, snowflake_global_query, snowflake_query, or snowflake_describe to choose a different parent directory. Each result directory contains:

  • rows.jsonl by default, or rows.csv/rows.tsv when explicitly selected;
  • index.json with format, encoding, row count, column count, column names, byte count, and data filename. Column names come from the Snowflake Statement's result metadata, so columns/columnCount are populated even for a zero-row result.

rows.tsv fields and header names are backslash-escaped so tabs, carriage returns, newlines, and literal backslashes in Snowflake values survive the round trip losslessly: a literal backslash becomes \\, a tab becomes \t, a carriage return becomes \r, and a newline becomes \n (each a two-character escape sequence, not the raw control character). Quotes are not TSV delimiters and are left as-is.

The tool result contains no row values. It reports the full result-directory path and shape index, then includes commands such as:

DIR='/tmp/pi-snowflake-example' jq . "$DIR/index.json"
DIR='/tmp/pi-snowflake-example' jq -s '.[0:10]' "$DIR/rows.jsonl"

When @hypabolic/pi-hypa resolves in the running Pi installation, the result also includes a bounded hypa_read example that reads only index.json. It does not suggest loading result rows into agent context.

  • dbt — Run a dbt subcommand against the configured project. Parameters:
    • command (enum, required): run, test, build, compile, seed, snapshot, debug, deps, parse, clean, docs-generate, run-operation, list, source-freshness.
    • select, exclude (string, optional): selectors.
    • target (dev | prod, optional): profiles.yml target.
    • fullRefresh (boolean, optional): pass --full-refresh. Refused when the selector mentions raw tables.
    • vars (string, optional): YAML/JSON passed verbatim to --vars.
    • operation, operationArgs (string, optional): required when command is run-operation.
    • timeoutMs (integer, optional): per-invocation timeout. Default 30 min, capped at 1 hour.

Commands

  • /snowflake <SQL> — Ask Pi to run a read-only query for you via snowflake_query without composing a full prompt.
  • /snowflake-conn — Print the currently configured Snowflake + dbt context (connection, binaries, working dir, timeouts).
  • /dbt <args> — Ask Pi to run a dbt command via the dbt tool (e.g. /dbt run --select tag:Aspyn).

Specialized agent: snowflake-analyst

A read-only persona pairs naturally with these tools. The agent definition is single-sourced at:

  • .pi/agents/snowflake-analyst.md

That's the canonical path the team's launchers (bin/pi-team.sh, bin/pi-safe.sh) already pick up. The package itself does not ship a duplicate copy.

Key frontmatter:

name: snowflake-analyst
tools: read, grep, find, ls, bash, snowflake_analytics_query, snowflake_global_query, snowflake_describe, dbt
model: openai-codex/gpt-5.4-mini
systemPromptMode: replace

The persona's job is to inspect Snowflake data and debug transformations using the read-only query tools. Every database-capable dbt command, including compile and test, is currently blocked unconditionally (see "Settings" and "Limitations"); only deps/clean/debug run.

Model availability: the extension itself doesn't pin a model; the agent frontmatter does. If your Pi install doesn't expose openai-codex/gpt-5.4-mini, update the model: line in the agent file to a model your providers actually serve (e.g. openai-codex/gpt-5.4-mini for the ChatGPT/Codex SSO route).

Try it

> /snowflake-conn
Snowflake connection: `claude` ... dbt Python: `python3` ...

> Use snowflake_analytics_query: SELECT count(*) FROM model_marketing_sms_audiences LIMIT 10
> It executes: SELECT count(*) FROM analytics.dbt.model_marketing_sms_audiences LIMIT 10

> Use snowflake_global_query: SELECT query_id, error_code FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY WHERE query_id = '01c6b3c0-0421-9310-0025-6403b4bc4f0a'

> /dbt deps
> /dbt compile --select model_aspyn_customers
> It refuses: dbt compile is blocked by production-safety policy: ... (every database-capable command is currently blocked unconditionally — see "Limitations")

Security

  • The extension uses the official snowflake-sdk Node.js driver. It tests the configured connections.toml profile before trying SNOWFLAKE_* environment credentials.
  • The read-only gate is a defense-in-depth check, not a substitute for a least-privilege Snowflake role. Always grant both credential sources the minimum role required.
  • Beyond a leading SELECT/WITH/etc. keyword, _shared/sql-gate.ts also rejects Snowflake SYSTEM$... function calls except for a short, explicit allowlist of known read-only metadata functions (SYSTEM$CLUSTERING_INFORMATION, SYSTEM$TYPEOF, etc.) — a leading SELECT does not prove a statement has no side effects, since SYSTEM$CANCEL_QUERY, SYSTEM$ABORT_SESSION, and similar pseudo-functions are callable from inside one. This is a default-deny allowlist, not a blocklist, so it also rejects SYSTEM$... functions not yet known to this extension. It does not cover Snowflake external functions or ordinary UDFs, which are syntactically indistinguishable from any other function call — no lexical gate can prove those side-effect-free. That residual risk is a Snowflake privilege/grant concern (least-privilege roles, UDF/external-function grants), not something this gate can close.
  • The dbt tool does not use the Snowflake driver connection. It runs with the credentials and target defined by your dbt profile. Every database-capable command (run, build, seed, snapshot, run-operation, test, compile, docs-generate, source-freshness, list, parse — everything except deps/clean/debug) is blocked unconditionally: dbt evaluates full project Jinja under whatever role the profile resolves to, and no static check this extension could perform (role name, declared hooks, a selector, or a dbt ls-resolved node's own schema/database) proves a model or macro body has no side effects — see "Settings" above. Treat dbt access as separately privileged regardless; use least-privilege profiles and explicit selectors/targets.
  • fullRefresh:true requires an explicit select. Before running, the extension resolves it with dbt ls and rejects any resolved raw model. This prevents indirect graph selectors from full-refreshing raw external tables.
  • snowflake_create_raw_external_table performs narrowly scoped DDL through the pinned claude connection. It creates only an external table with IF NOT EXISTS; it cannot alter or drop existing objects. It is also a production write under the policy above: its destination schema is read from EXTERNAL_TABLES_SCHEMA (_shared/raw-external-table.ts), the same constant the SQL builder itself uses — always external_tables, which can never equal the configured dev database/schema, so it is blocked by default regardless of role. Its role check also denies the write outright (rather than trusting either credential source) when connections.toml and the SNOWFLAKE_* environment fallback both look connectable and declare different roles — see "Limitations" above.
  • The tool_call gate only inspects bash calls that match snow sql. It permits only one inline -q/--query payload using the configured connection; file/stdin SQL and other shells (e.g. Python) are not intercepted.
  • Snowflake query rows are persisted locally instead of entering the LLM context. Result directories may contain sensitive data. Restrict permissions on custom output parents and clean result directories periodically. dbt output remains bounded and writes an oversized captured tail under os.tmpdir().

Development

npm run typecheck --prefix extensions/snowflake-query
npm run test --prefix extensions/snowflake-query
npm run pack:dry-run --prefix extensions/snowflake-query
pi -e extensions/snowflake-query
pi -e extensions/snowflake-query/snowflake-query.ts

The unit tests cover the read-only SQL gate (_shared/sql-gate.ts) and run via node --test after a tsc step into .tmp-test/, mirroring the extensions/verifier test harness.