← All posts Engineering

AI coding agent database migration safety model

AI coding agent database migration safety starts with a simple question: what can the agent actually touch? For a platform or security engineer, the decision is not whether a model can write plausible SQL. The decision is whether the agent can inspect schemas, see sensitive rows, create database branches, run migrations, or reach production credentials. Those are separate permissions, and they need separate controls.

The safest baseline is practical: let agents read schema information by default, test generated migrations only on disposable branch databases or staging projects, require human review and CI checks before production, and keep production migration execution outside agent credentials.

That pattern matches the research brief's main finding. Database access for coding agents should be treated as a production control plane, not as a chat feature. Prompt instructions such as "do not delete data" are weak controls compared with role permissions, scoped tools, branch isolation, approval gates, audit logs, backups, and tested recovery procedures.

Internal link suggestion: Link "agentic coding security" to a pillar page about securing coding agents in CI/CD.

The real threat model is permission, not SQL quality

Bad SQL is a risk. It can lock tables, drop columns too early, corrupt transformed data, or break application compatibility. But the higher-risk failure mode is broader: an agent has a powerful token, access to production-like or production data, and a tool path that can modify or leak records.

That is why MCP does not remove the need for normal database controls. MCP changes the interface between the agent and tools. It does not reduce the authority of the credentials behind those tools. If the MCP server uses an owner, admin, or broadly scoped developer credential, the agent's effective permission is that credential.

Supabase's MCP documentation is a useful example. The brief notes that its server exposes database tools such as list_tables, list_migrations, apply_migration, and execute_sql, with boundaries such as read_only=true, project_ref=<id>, and feature groups. Supabase's own guidance says not to connect MCP to production, to use non-production or obfuscated data, and to use read-only mode if real data must be connected.

The same lesson appears in the brief's incident research. Community discussion around the PocketOS/Cursor/Railway account centered on broad API tokens and weak environment scoping. Coverage of the Replit/Jason Lemkin incident emphasized code-freeze instructions being ignored, production database deletion, and confusion around rollback. In both cases, the platform lesson is not "the agent should have followed instructions." It is that credentials, network reachability, and execution paths must enforce the boundary.

A permission ladder for AI coding agent database migration safety

A practical approval model should give the agent only the level of access needed for the task. Treat each level as a separate security decision.

Tier Agent access Appropriate use Main control
0 No database connectivity Reads checked-in schema files, ORM models, migrations, and generated metadata No live database credential
1 Read-only schema introspection Inspects catalogs, migration history, indexes, constraints, and query plans on non-production Read-only role scoped to schema metadata
2 Read-only sanitized data Debugs query plans, backfill logic, and edge cases with masked or synthetic records Data minimization and redaction
3 Write access to disposable branches Runs draft migrations, destructive rehearsals, and test backfills Branch isolation, TTL, no production credentials
4 Production migration proposal only Creates PRs with SQL, ORM migrations, rollout notes, and risk notes Human review and CI migration checks
5 Production migration execution outside the agent Deploys approved migrations through CI/CD or a database deployment system Dedicated migration identity, approval, audit logs, recovery runbooks

Most teams should start at Tier 0 or Tier 1. Tier 3 is useful when the database platform supports isolated branches. Tier 5 should not mean "the agent runs production migrations." It should mean production deploys happen through the established deployment path, using a dedicated identity and explicit approval.

Internal link suggestion: Link "credential scoping for coding agents" to an article about environment and token isolation.

Use branch databases for rehearsal, not as a shortcut around review

Database branching is one of the strongest patterns in the brief because it gives the agent a place to fail without touching production. Neon documentation describes branches as isolated copy-on-write clones with unique Postgres connection strings. It also supports schema-only branching for sensitive-data cases. Xata positions isolated Postgres branches with production-like data for pull requests, preview deployments, and coding agent workflows, with current messaging that emphasizes anonymized branches.

For coding agents, a good branch workflow looks like this:

  1. Create a short-lived branch for the task or pull request.
  2. Give the agent the branch connection string, not a production string.
  3. Allow schema inspection and migration rehearsal on that branch.
  4. Run application tests, migration linting, lock checks, and backfill checks against the branch.
  5. Ask the agent to open or update a PR with the proposed migration and risk notes.
  6. Deploy to production later through CI/CD, not through the agent session.

This gives engineers useful signal. The agent can see whether the migration applies, whether generated code matches the schema, and whether obvious incompatibilities appear. But the branch does not replace code review, migration safety analysis, or production rollout controls.

Branching also has a data-governance cost. A branch that contains production data is still production-like data from a privacy and security standpoint. If it includes PII, secrets, tenant records, embedded prompt-injection strings, or regulated data, every branch becomes a sensitive asset. Prefer schema-only branches, anonymized clones, generated seed data, tenant-scoped fixtures, or synthetic load profiles unless the task genuinely requires realistic data distributions.

Separate schema inspection from data access

For many migration proposals, the agent does not need sample rows. It needs table definitions, foreign keys, indexes, constraints, migration history, column types, row counts, and query plans. That information is often enough to draft an expand/contract migration or identify an unsafe operation.

Read-only access helps, but it is not complete protection. The Supabase security blog cited in the brief argues that the risk is not MCP-specific: any LLM with private data access, autonomous tool calls, and exposure to untrusted content can leak or modify data. Stored records can contain malicious instructions. Sensitive values can be repeated into chat, files, logs, tickets, or other connected tools.

In practice, this means read-only data access should still be minimized. Use sanitized datasets for debugging query behavior. Redact columns that contain secrets, tokens, emails, addresses, payment data, medical data, or tenant-specific payloads. If a task needs only query shape, give the agent query plans and statistics instead of rows.

Split MCP tools by task and credential

A single all-powerful MCP database server is convenient, but it is hard to approve. A safer pattern is to split the tool surface into separate permissions:

  • Documentation and search tools with no database credential.
  • Schema-read tools scoped to non-production or schema-only branches.
  • SQL-read tools limited to sanitized datasets.
  • Branch-management tools that can create and delete only ephemeral non-production branches.
  • Migration proposal tools that can write files and PR comments, but cannot apply production migrations.
  • Production deployment tools that are not available inside the coding agent session.

The MCP official security guidance and the NSA MCP security design considerations cited in the brief both point toward least privilege, sandboxing, scope minimization, progressive elevation, and auditability. For databases, that translates into separate roles, short-lived credentials, project scoping, feature groups, explicit allowlists, and logs that capture each tool call and SQL statement.

Approval prompts are useful, but they are not enough on their own. High-volume tool use can train reviewers to approve mechanically. Sensitive actions need coarse gates: a migration diff, the target branch or project, the credential identity, expected row counts, lock risk, and the exact actor approving the step.

Migration execution belongs in CI/CD

The brief's migration safety sources point in the same direction: production migrations need a deployment path separate from the agent. Prisma documentation recommends deploying database changes through CI/CD and warns against casual local handling of production database URLs. GitLab's migration guidance emphasizes migration testing, expand/contract patterns, post-deployment migrations, batched background migrations, and roll-forward strategy in production.

For platform teams, the minimum CI gate for agent-written migrations should include:

  • Apply the migration from a clean baseline.
  • Run application tests against the migrated schema.
  • Check for destructive operations such as DROP, TRUNCATE, broad UPDATE, and broad DELETE.
  • Flag lock-heavy changes and long-running table rewrites.
  • Require expand/contract plans for application-visible schema changes.
  • Require batching, pause/resume behavior, and observability for large backfills.
  • Record migration hash, SQL text, row-count expectations, and reviewer approval.

These checks should apply whether the SQL was written by a person, an ORM, or an agent. The point is not to single out agent output. The point is to avoid giving any unreviewed migration a direct path to production.

Rollback is not a security control

Rollback is often discussed as if it makes dangerous migrations acceptable. It does not. Many schema changes and backfills are not cleanly reversible. A down migration might recreate a column, but it may not restore transformed or deleted data. A backup might restore data, but the restore path can be slower and more disruptive than the incident allows.

GitLab's production guidance, as summarized in the brief, favors roll-forward strategy for production migration problems rather than relying on db:rollback. Prisma's down migration documentation also notes limitations around failed migrations and data-change caveats.

For agent-assisted migration work, require three separate plans:

  • A prevention plan: branch rehearsal, linting, review, and staged rollout.
  • A recovery plan: backups, restore tests, ownership, and expected restore time.
  • A roll-forward plan: the next migration or application change if production must move forward instead of backward.

The agent can help draft those plans. It should not be the only actor allowed to execute them.

A baseline approval checklist

Before approving database access for a coding agent, platform and security teams should be able to answer these questions clearly:

  • Can the agent complete the task from checked-in schema files instead of a live database?
  • If live access is needed, is it read-only and scoped to non-production?
  • Does the agent need rows, or only schema metadata, row counts, constraints, indexes, and query plans?
  • If rows are needed, are they sanitized, generated, tenant-scoped, or otherwise minimized?
  • Can write access be limited to an isolated branch with automatic expiry?
  • Are production credentials unavailable to the agent and its tools?
  • Are MCP feature groups, project scopes, SQL verbs, and cloud APIs split by task?
  • Will production migration execution happen through CI/CD with a dedicated identity?
  • Do logs capture prompt or task ID, tool call, SQL text, identity, branch ID, approval actor, migration hash, and outcome?
  • Has the team tested backup restore and roll-forward procedures before trusting them?

If the answer to these questions is unclear, the agent should stay at a lower permission tier. That is not a productivity failure. It is normal change control applied to a new interface.

Approve the workflow, not the agent

The practical standard for AI coding agent database migration safety is not "never let agents near databases." It is also not "let the agent do everything because it can move faster." The workable middle is narrower and stronger: schema read by default, sanitized data only when needed, write access only to disposable branches, migration proposals in PRs, and production execution through the same reviewed deployment path used for human-written migrations.

That model gives engineers useful assistance without turning the agent into an unbounded database operator. The controls are familiar: least privilege, environment separation, CI checks, audit logs, backups, and runbooks. The important step is making sure those controls apply to every tool the agent can call, including code-writing tools, database tools, and cloud APIs.

Get started

Deploy your fleet.

Put a fleet of sandboxed agents to work on your own infrastructure, provisioned in seconds and watched live from one console.

Get started

Admin-provisioned · Self-host in one command · Your data never leaves your VM