Scan your whole stack
Are you using @deepagents/text2sql?
Find out what’s in your code.
Scan your apps free in minutes (opens in a new tab)Latest version: v7.41.0
@deepagents/text2sql was last scanned on 26 Nov 2026 at version 7.41.0. Risk score 0 of 100. No malicious behavior was detected.
| Version | Published | Status |
|---|---|---|
| 7.41.0 LATEST | 26 Nov 2026 | No rules fired |
| 7.40.0 | 26 Nov 2026 | Not shown |
| 7.39.1 | 26 Nov 2026 | Not shown |
| 7.39.0 | 26 Nov 2026 | Not shown |
| 7.38.2 | 26 Nov 2026 | Not shown |
Findings for v7.41.0. The score is a capped sum of the weights of the rules that fired — not CVSS, not exploitability, and not a probability. It is not comparable across packages with different scan coverage.
The score describes 7.41.0; other versions have their own rules, not their own score.
The publisher’s own README, as collected from the registry.
AI-powered natural language to SQL. Ask questions in plain English, get executable queries.
npm install @deepagents/text2sql
Install the database driver or client library that matches your adapter:
npm install pg # PostgreSQL
npm install mssql # SQL Server
npm install mysql2 # MySQL / MariaDB
npm install @duckdb/node-api # DuckDB
npm install @google-cloud/bigquery # BigQuery
npm install @clickhouse/client # ClickHouse, or use your preferred client
# PostHog uses native fetch and needs no additional client package
The spreadsheet adapter requires xlsx for Excel, CSV, and TSV files. It is
an optional peer dependency; install it only if you use
@deepagents/text2sql/spreadsheet. With npm 12, add this to your project's
.npmrc to allow directly declared URL dependencies:
allow-remote=root
Then install SheetJS xlsx 0.20.3 from its CDN:
npm install https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz
Requires Node.js LTS.
import { groq } from '@ai-sdk/groq';
import pg from 'pg';
import { Text2Sql, toSql } from '@deepagents/text2sql';
import {
Postgres,
columnValues,
constraints,
indexes,
info,
rowCount,
tables,
views,
} from '@deepagents/text2sql/postgres';
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
const adapter = new Postgres({
execute: async (sql) => {
const result = await pool.query(sql);
return result.rows;
},
grounding: [
tables(),
views(),
info(),
indexes(),
constraints(),
rowCount(),
columnValues(),
],
});
const text2sql = new Text2Sql({ adapters: { main: adapter } });
const fragments = await text2sql.index({ names: ['main'] });
const { sql } = await toSql({
input: 'Show me the top 10 customers by revenue',
adapter,
fragments,
model: groq('openai/gpt-oss-20b'),
});
console.log(sql);
index() introspects the database schema and returns it as context fragments.
toSql() gives these fragments to the model and validates the SQL that the
model writes.
The adapter-map key (main here) is the adapter name. Reuse that same key in
text2sql.index({ names: ['main'] }) and in any sql validate <db> "..." /
sql run <db> "..." calls from a sandbox where the package CLI is installed.
This is the configured connection name, not the SQL-level database or schema
name (for example, SQLite's default main schema).
Adapter names must match /^[A-Za-z_][A-Za-z0-9_]*$/. If you build adapter
maps dynamically, use isValidAdapterName(name) to check one key or
validateAdapterNames(names) to fail fast before constructing Text2Sql or
the sandbox-side adapter module used by the sql CLI.
Text2SQL works with any model provider supported by the Vercel AI SDK, including OpenAI, Anthropic, Google, Groq, and more.
Text2Sql owns SQL generation and schema indexing, but you own the chat loop.
Build the agent by composing a ContextEngine, a sandbox, and agent +
chat from @deepagents/context:
import {
ContextEngine,
type ContextFragment,
InMemoryContextStore,
agent,
chat,
createBashTool,
createDockerSandbox,
errorRecoveryGuardrail,
npm,
user,
} from '@deepagents/context';
import {
createSqlCommandHooks,
instructions,
sqlValidateReminder,
} from '@deepagents/text2sql';
const store = new InMemoryContextStore();
const context = new ContextEngine({
store,
chatId: 'chat-123',
userId: 'user-456',
});
const backend = await createDockerSandbox({
installers: [npm('@deepagents/text2sql', { ensureRuntime: true })],
volumes: [
{
type: 'bind',
hostPath: process.cwd(),
containerPath: '/workspace',
readOnly: true,
},
],
env: {
TEXT2SQL_ADAPTERS: '/workspace/text2sql-adapters.ts',
TEXT2SQL_OUT_DIR: '/tmp/text2sql',
},
});
const sandbox = await createBashTool({
sandbox: backend,
...createSqlCommandHooks({ adapters: { main: adapter } }),
});
const indexResult = await sandbox.sandbox.run({ command: 'sql index' });
if (indexResult.exitCode !== 0) throw new Error(indexResult.stderr);
const manifest = JSON.parse(indexResult.stdout) as { fragmentsPath: string };
const fragmentsText = await sandbox.sandbox.readTextFile({
path: manifest.fragmentsPath,
});
if (fragmentsText === null) throw new Error('sql index wrote no fragments');
const fragments = JSON.parse(fragmentsText) as ContextFragment[];
context.set(...instructions(), ...fragments);
context.set(sqlValidateReminder());
const ai = agent({
name: 'sql-assistant',
sandbox,
model: groq('openai/gpt-oss-20b'),
context,
guardrails: [errorRecoveryGuardrail],
maxGuardrailRetries: 3,
});
await context.continue(user('Show me the top 10 customers by revenue'));
const stream = await chat(ai);
for await (const chunk of stream) {
// handle streaming response
}
The /workspace/text2sql-adapters.ts module must exist in the sandbox and
default-export your adapter map. Mount your project into /workspace (as above)
or upload or write that module before calling sql index. With a remote Docker
daemon, the bind mount's hostPath must exist on the daemon's host.
TEXT2SQL_OUT_DIR keeps schema and query artifacts in the sandbox's writable
/tmp/text2sql directory. The default ./sql would be inside the read-only
/workspace mount.
instructions() returns the SQL-flavored system fragments (policies, workflows,
clarifications, style guides) — spread them into context.set() alongside the
schema fragments returned by sql index. The index output starts with an
available_databases fragment that lists the exact configured adapter names the
model must pass to sql validate <db> and sql run <db>. Add or replace the
instructions with your own domain fragments as needed.
sqlValidateReminder() returns a context reminder fragment backed by
SQL_VALIDATE_REMINDER. After a successful sql run <db> "...", it adds a
model-only tool-output reminder before the next generation when no prior
sql validate <db> "..." used the same configured adapter name and exact SQL
text. The raw SQL command result remains unchanged. During streamed chat()
turns, the reminder is persisted as a synthetic user message for replay and
prompt caching; bare createReminderSession() integrations and
agent.generate() own persistence of their generated assistant history.
sql validate <db> "..." and sql run <db> "..." are real commands from the
@deepagents/text2sql package. <db> is the configured adapter name. With a
single configured adapter, a mistaken database selector is routed to that sole
adapter and the command prints a note; with multiple adapters, unknown names
fail and print the available list. sql index writes an available_databases
fragment, schema fragments, and progress events for chat setup, indexing all
configured adapters by default (same as --all) unless adapter names are
provided.
Install the package inside the sandbox and set TEXT2SQL_ADAPTERS to a module
whose default export is Record<string, Adapter>. Missing sql means the
sandbox was not prepared correctly. The CLI also loads a plain object with the
methods its commands call: format(sql), validate(sql) for sql validate,
and run(sql) for sql run. sql run gives the formatted SQL to run and
never calls validate, so a plain object's run checks its own SQL and gives
{ result: rows } or { error: message }. sql index also calls
introspect().
sql index output details:
stdout: JSON manifest with fragmentsPath, eventsPath, adapters, and
fragment count.--verbose pretty or --verbose json: mirrors progress events to stderr
while keeping stdout as the manifest.--out-dir <path>: writes artifacts under that path (default:
$TEXT2SQL_OUT_DIR or ./sql).The sql CLI caches introspected schema only when you opt in via env: set
TEXT2SQL_INDEX_CACHE_DIR (where cache files live) and/or
TEXT2SQL_INDEX_VERSION (an invalidation token — bump it when the schema
changes). With neither set, every sql index introspects fresh. See
Schema index caching for
the underlying injectable primitives.
For in-process or virtual-sandbox usage, install just-bash and wrap an existing
Text2Sql instance as a custom command:
import { InMemoryFs } from 'just-bash';
import { createVirtualSandbox } from '@deepagents/context';
import {
type CreateSqlCommandOptions,
type CreateSqlCommandResult,
Text2Sql,
createSqlCommand,
} from '@deepagents/text2sql';
const text2sql = new Text2Sql({ adapters: { main: adapter } });
const commandOptions: CreateSqlCommandOptions = {
outputDir: '/sql-artifacts',
};
const sqlCommand: CreateSqlCommandResult = createSqlCommand(
text2sql,
commandOptions,
);
const sandbox = await createVirtualSandbox({
fs: new InMemoryFs(),
customCommands: [sqlCommand.command],
});
await sandbox.run({ command: 'sql validate main "SELECT 1"' });
CreateSqlCommandOptions configures command defaults (currently outputDir).
CreateSqlCommandResult returns the command plus a repair(raw) helper for
normalizing model-generated argv before execution.
Spread createSqlCommandHooks({ adapters }) into createBashTool() for
model-driven bash calls. The before hook preserves
the old virtual-command tolerance for common LLM quote mistakes, rewrites SQL
identifier backticks so bash does not run them as command substitutions, and
blocks raw database access so read-only and scope checks stay behind
sql validate / sql run. The after hook restores hidden formattedSql
metadata from the host adapter map without putting that concern into the real
CLI.
Read-only enforcement parses a single SELECT/WITH statement even when it
starts with whitespace or SQL comments (-- ..., /* ... */). Before any
adapter validator or executor runs, the dialect policy rejects write
statements, multi-statement batches, parser failures, SELECT INTO, locking
reads/hints, assignments, known state/file/extension/remote-access functions,
BigQuery external queries, qualified BigQuery persistent routines, and
ClickHouse table functions or unsafe UDF origins.
Scope checks compare referenced base tables and views against the entities
produced by tables() and views() groundings. Entity-free queries such as
SELECT 1 do not run grounding just to resolve an empty allowlist, and metadata
groundings such as indexes(), constraints(), rowCount(),
columnStats(), and columnValues() annotate schema context without expanding
the validation allowlist.
This parser policy is one safety layer, not a database permission boundary.
Static analysis cannot prove arbitrary unqualified user-defined functions are
side-effect free, and an otherwise valid SELECT can still consume excessive
CPU, memory, bytes, locks, or time. Production connections must use a dedicated
least-privilege identity with SELECT only on intended relations; disable or
withhold extension, file, remote-query, and routine execution capabilities; and
configure dialect-appropriate statement timeouts, byte/result limits, and
compute/memory limits.
The DuckDB adapter uses DuckDB's native JSON AST instead of the shared SQL
parser, so DuckDB-specific syntax is analyzed in its real grammar. It resolves
every referenced relation to a quoted catalog.schema.table, rejects writes,
multi-statement batches, side-effecting or user-defined functions and macros,
and arbitrary table functions, then compares those relations with the tables
and views produced by grounding. Production DuckDB connections must still be
read-only, disable external access and automatic/community extension loading,
set resource limits, and lock configuration after setup.
The PostHog adapter does not pass HogQL through the local SQL parser. It asks
PostHog to parse each query with HogQLMetadata, checks the returned base-table
names against grounded schema, and only then sends a HogQLQuery for execution.
Direct adapter.execute(sql, values) calls forward named HogQL values unchanged
after validation, which is useful for application-owned filters added outside
the model loop. Shell-escaped dollar-prefixed PostHog properties such as
properties['\$device_type'] are decoded before validation and execution.
Each adapter checks SQL with a policy before its validator or executor runs.
Text2Sql.run checks once, then validates and executes. A policy is a
SqlPolicyAnalyzer, and every adapter takes one as its policy option in
place of its default.
The building blocks are in @deepagents/text2sql/policy. A fact source reads
the SQL into facts, and rules check the facts in order; the first violation
wins, and a rule that is not reached reads no fact. SqlText reads the SQL
text with node-sql-parser and gives Statements, Relations, Calls and
Constructs. A rule names the facts it reads, so a rule that the source cannot
serve does not compile.
| Rule | Reads | Refuses |
|---|---|---|
OneSelect |
Statements |
anything but one SELECT, SELECT INTO included |
DeniedCalls |
Calls |
calls by name, by name prefix or by qualified name |
Forbid |
Constructs |
table hints, linked-server relations, locking reads, assignments |
InScope |
Relations |
relations outside the grounded tables and views |
InScope(new GroundedNames()) matches names without case, and it matches an
unqualified name by the last part of an allowed entity. Each dialect exports
its default policy: policy() of sqlite, postgres, mysql and bigquery,
and textPolicy() of sqlserver. FirstViolation runs policies in order,
and the first violation wins:
import {
DeniedCalls,
FirstViolation,
SourcePolicy,
SqlText,
} from '@deepagents/text2sql/policy';
import * as sqlserver from '@deepagents/text2sql/sqlserver';
const adapter = new sqlserver.SqlServer({
execute,
grounding: [sqlserver.tables()],
policy: new FirstViolation(
sqlserver.textPolicy(),
new SourcePolicy(new SqlText({ dialects: ['transactsql'] }), [
new DeniedCalls({ names: ['HASHBYTES'] }),
]),
),
});
A source that cannot read the SQL throws UnreadableSql, and the policy gives
SQL_SCOPE_PARSE_ERROR. Any other error of a source rejects the check. A
source of one entry point, such as SqlServerPlan of ./sqlserver, works in
a SourcePolicy of ./policy.
textPolicy() reads T-SQL with node-sql-parser, whose grammar refuses valid
T-SQL such as STRING_AGG ... WITHIN GROUP, TRY_CAST,
COUNT_BIG, OPENJSON ... WITH, OFFSET without FETCH, OPTION,
LIKE ... ESCAPE and TOP ... WITH TIES. sqlserver.planPolicy(principal)
asks SQL Server instead: a database user, the principal, compiles the SQL
under SET SHOWPLAN_XML ON, which plans each statement and runs none.
Find threats in your stack.
OX Radar can check high-priority threats, like critical package CVEs, against your context.
Each incident is marked Detected or Not Detected with a remediation plan and proof all tracked in the Response Center.
The probe returned only these fields for this server — auth requirement, protocol and tool list weren’t observed, so they’re not shown (never guessed).
The publisher’s own links, as the registry reports them. These are not sources for the assessment on this page.