Lock rows for AI agents. · lokra.dev
Lokra sits between AI agents (Claude Code, Cursor, OpenClaw, custom agents) and your Postgres database, and lets the database itself decide what each agent may see and change.
Agents today usually get a full database password. Lokra gives each agent its own locked-down identity instead, and puts these controls on every request:
- Scoped identity. Each agent logs in as its own Postgres role with only the tables, columns and rows its policy allows. Agents receive a short-lived signed token, never a password.
- Masking. Emails, phone numbers, payment cards, IBANs, US Social Security numbers and Australian Medicare and IHI numbers are masked in results, including inside free-text notes and renamed columns. Cards, IBANs and health identifiers are checksum-validated, so ordinary numbers are left alone.
- Human approval for writes. INSERT, UPDATE and DELETE are dry-run, shown with the number of rows they would change, and only run after a person approves them.
- Tamper-evident audit ledger, with reporting. Every request is written to a hash-chained,
signed log, and
lokra reportturns it into a per-agent activity and risk summary. - Purpose of use. An agent's token can carry a declared purpose. The policy can require one
(
require_purpose: true) and limit which purposes an agent may use, and every request records it.
v0.1, local prototype. The lab uses synthetic data only.
Quick start
Needs Docker and Python 3.11+.
docker compose up -d # lab Postgres on 127.0.0.1:55432 with fake clinic data
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/lokra provision # creates one DB role per agent in policies.yaml
.venv/bin/python -m pytest -q # runs the test suite, including attack attempts
Try it from the terminal as an agent:
.venv/bin/lokra try scheduling-bot "SELECT full_name, medicare_number FROM patients LIMIT 3"
.venv/bin/lokra try scheduling-bot "SELECT note FROM clinical_notes" # refused: no access
.venv/bin/lokra try scheduling-bot "UPDATE appointments SET status='cancelled' WHERE id=1" --write --reason "pt cancelled"
.venv/bin/lokra pending
.venv/bin/lokra approve <write_id>
.venv/bin/lokra log
.venv/bin/lokra verify-ledger
Use your own database
Install it with pipx install lokra (or uv tool install lokra), then point it at any
Postgres, including a Supabase database. lokra init connects
read-only, introspects the schema, flags likely PII columns (email, phone,
health and government identifiers) and writes a starter policy for you to review:
lokra init "postgresql://user:pass@host:5432/dbname" # read-only, writes policies.yaml
lokra check --dsn "postgresql://user:pass@host:5432/dbname" # validate it against the schema
# review and tighten policies.yaml, then provision the per-agent roles:
lokra provision --admin-dsn "postgresql://admin:pass@host:5432/dbname"
lokra dashboard
lokra check reads the database and flags grants on tables or columns that do
not exist, any sensitive-looking column an agent can read with nothing masking
it, and writes without a matching read, so you catch policy mistakes before an
agent ever connects.
For Supabase, use the connection string from Project Settings → Database (the
direct connection, not the pooler). init only reads; provision needs a role that
can create roles, such as postgres. Try it on a development project first.
policies.example.yaml is a non-healthcare starting point you can copy instead.
Tables outside the public schema are named schema.table in the policy, for example
billing.invoices: "*". Lokra grants the agent only those schemas, and takes them away
again when they leave the policy. To scaffold from several schemas at once, run
lokra init "<dsn>" --schemas public,billing.
Lock rows
Give an agent a rows rule and it only sees, inserts and updates rows whose column holds
one of the listed values, on every table it can reach that has that column:
agents:
support-bot:
rows: {column: account_id, values: [42]}
read: {customers: "*", orders: "*", products: "*"}
lokra provision turns this into Postgres row-level security policies for that agent's
role, so the database enforces it. Other roles and your app keep the access they had:
if a table had row-level security off, Lokra turns it on with a pass-through policy for
everyone except Lokra's agents, and turns it off again when no agent's rows are locked
there. Where a table names the scope differently, map it with
tables: {accounts: id}. lokra check warns about tables the agent can read that have
no column to lock by.
Connect Claude Code
Desktop app or CLI: put this .mcp.json in the folder where the agent works, then open a
new Claude Code session in that folder and allow the clinic-db server when asked.
{
"mcpServers": {
"clinic-db": {
"command": "/absolute/path/to/lokra/.venv/bin/lokra",
"args": ["--config", "/absolute/path/to/lokra/policies.yaml",
"serve", "--dev-agent", "scheduling-bot"]
}
}
}
--dev-agent issues an 8-hour token when the server starts. It is for local development
only; in production the token is issued by a human or the control plane and passed in
LOKRA_TOKEN.
CLI alternative, with an explicit token:
claude mcp add clinic-db \
-e LOKRA_TOKEN="$(.venv/bin/lokra mint-token scheduling-bot --ttl 28800)" \
-- "$PWD/.venv/bin/lokra" --config "$PWD/policies.yaml" serve
Then ask something like "which patients have appointments on Monday?".
Tools the agent sees: whoami, list_tables, query, propose_write, write_status, execute_write.
Stop an agent
Always-on agents need brakes that work in seconds, not a policy rewrite:
lokra pause support-bot --reason "deleting too much" # refuse its requests, block its DB login, end its sessions
lokra resume support-bot
lokra revoke-token <token or token id> # kill one leaked token, keep the agent's others
The dashboard lists every agent with a Pause and Resume button, and lokra slack adds a
Pause button to each approval message and posts a notice with a Resume button whenever an agent
is paused, so you can stop an agent from your phone. A paused agent stays paused through
lokra provision. To stop a stuck retry loop from
hammering the database, cap its rate in the policy with rate_limit: 60 (requests a minute);
an agent that keeps hitting its cap is flagged as looping in lokra report and the dashboard.
Every pause, resume, revocation and stopped request is written to the ledger.
Approve writes in Slack
lokra slack posts each pending write to a Slack channel, with the agent, the person it acts
for, its reason, the masked SQL and the dry-run row count, plus Approve and Deny buttons. Only
the people you list can decide, and every decision lands in the signed ledger. It connects out
to Slack over Socket Mode, so Lokra needs no public URL.
-
At api.slack.com/apps, create an app from this manifest and install it to your workspace. Copy the bot token (
xoxb-…).display_information: {name: Lokra} features: {bot_user: {display_name: Lokra}} oauth_config: {scopes: {bot: [chat:write]}} settings: {interactivity: {is_enabled: true}, socket_mode_enabled: true}
-
Under Basic Information, create an app-level token with the
connections:writescope (xapp-…), and invite the bot to your approvals channel. -
Add the channel ID and the Slack member IDs of your approvers to
policies.yaml:slack: {channel: C0123ABCD, approvers: [U0123ABCD, U0456EFGH]}
-
Install the extra and run it next to your policy:
pipx install 'lokra[slack]' LOKRA_SLACK_BOT_TOKEN=xoxb-… LOKRA_SLACK_APP_TOKEN=xapp-… lokra slack --admin-dsn "<admin dsn>"
With
--admin-dsn, pausing from Slack also blocks the agent's database login.
Writes approved or denied in the dashboard or the terminal close their Slack message too.
Agents on other machines
Always-on and hosted agents can reach Lokra over HTTP. Each request carries the agent's own short-lived token, so one Lokra serves many agents and every call is checked:
lokra serve --http --host 0.0.0.0 --port 8787 # put TLS in front of this
lokra mint-token support-bot --ttl 28800 # hand this token to the agent (max 8 hours)
claude mcp add --transport http lokra https://lokra.internal.example/mcp \
--header "Authorization: Bearer <token>"
A request without a valid token is refused and recorded in the ledger.
Website
The lokra.dev site lives in site/. Preview it locally with clean URLs:
python3 scripts/serve_site.py
Reports
The audit ledger is not just a log. lokra report reads it back into an activity
and risk summary: what each agent did, how many sensitive identifiers it touched,
and plain, explained flags such as repeated blocked statements (a sign of probing
or prompt injection) or an unusually large read.
lokra report # per-agent activity and risk flags
lokra report --json # machine-readable, for a SIEM or an evidence pack
For a live view, lokra dashboard serves a local web page (127.0.0.1) with a
dashboard, an approvals queue where you approve or deny pending writes after
seeing the statement and its dry-run row count, a full audit log, and a policy
editor that rewrites policies.yaml and reprovisions the database roles for you.
The audit log shows every statement, what was masked, why requests were blocked, and each write from proposal through approval:
Flags are rules over the ledger, so each one traces back to its entries. This is the evidence an auditor asks for, generated from what already happened.
For a review or a vendor questionnaire, lokra evidence turns the policy and the
ledger into a control evidence pack: least-privilege grants per agent, masking
rules and what they caught, the write-approval trail, the ledger's integrity
check, and blocked access attempts, mapped to the Australian Privacy Principles,
ISO/IEC 27001:2022 and the ACSC Essential Eight. When the policy handles health
identifiers it adds a section for the Healthcare Identifiers Act, the My Health
Records Act and the Notifiable Data Breaches scheme.
lokra evidence # Markdown control pack to stdout
lokra evidence --out evidence.md # or write it to a file
lokra evidence --json # structured, for your own templating
Conformance
conformance/ is a benchmark of nine safety guarantees a database access layer
should uphold against a hostile agent (reject stacked statements, no OS command
execution, no cross-tenant reads, identifiers masked, and more). It scores Lokra
and a deliberately broken reference. Lokra upholds all nine.
python -m conformance.run
Run it only against layers you operate, in the disposable lab. See conformance/README.md for the safety and disclosure rules.
Security model
The SQL parser is not the security boundary. Several "read-only" database MCP servers were bypassed in 2025-26 because they relied on parsing SQL text. Here the database itself enforces access, and each layer still holds if the one before it fails:
| Layer | Stops | Enforced by |
|---|---|---|
| Signed short-lived token | Unknown, forged or expired agents | Proxy (HMAC) |
| SQL check | Writes in the read tool, stacked statements, DDL, SET ROLE |
Proxy (sqlglot), fails closed |
| Prepared statements only | COMMIT; DROP ... style stacking |
Postgres protocol |
| Per-agent login role | Tables and columns outside the policy | Postgres grants |
| Row lock | Rows outside the agent's scope, reads and writes | Postgres RLS policies per agent role |
| Read-only transaction | Writes hidden in CTEs or functions | Postgres |
| Statement timeout | Runaway queries | Postgres role setting |
| Masking | Identifiers in results, aliases, free text | Proxy, checksum-validated detectors |
| Ledger | Silent edits or deletions of history | SHA-256 chain + HMAC |
The tests in tests/test_integration.py disable the SQL check on purpose and confirm the
database still blocks the attack.
Layout
policies.yaml who may do what
lab/db/init/ lab schema (with RLS) and generated synthetic seed data
scripts/generate_seed.py
src/lokra/
config.py loads policies.yaml, local state in .lokra/ (gitignored)
tokens.py short-lived signed agent tokens
sqlcheck.py read/write classification (usability layer)
provision.py creates per-agent Postgres roles, grants and clinic scope
masking.py column rules and Medicare/IHI/email/phone detectors
ledger.py hash-chained, signed audit log
gateway.py the request pipeline and write approvals
server.py MCP server
cli.py `lokra` command
tests/
Roadmap
- Works against any Postgres, including Supabase (
lokra initscaffolds the policy) - Slack approve/deny buttons instead of the CLI
- Conformance suite: twelve safety guarantees, scored in
conformance/ - Activity and risk reports from the ledger (
lokra report,lokra dashboard) - Control evidence pack (
lokra evidence) mapped to the APPs, ISO/IEC 27001:2022, the Essential Eight, and — for health data — the Healthcare Identifiers Act, My Health Records Act and NDB scheme - Purpose-of-use on every request: a declared, policy-enforced purpose recorded in the ledger (
require_purpose,--purpose) - Deeper mapping to the US HSCC AI vendor questionnaire, question by question
- Hosted control plane: policy editor, approvals UI, long ledger retention, SSO
- DuckDB and Snowflake adapters
License
Apache 2.0. See LICENSE.
Metadata
Release files for lokra 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| lokra-0.4.0.tar.gz | 105.8 kB | With provenance | Details for lokra-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| lokra-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for lokra-0.4.0-py3-none-any.whl |
Total release size: 196.9 kB
Release files / lokra-0.4.0.tar.gz
| Download URL | lokra-0.4.0.tar.gz |
|---|---|
| Size | 105.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
60f10eb1f4f5d8db6df547f3333038cb80e8e3052a53f5efc95cbdd2a5e3f879
|
|
BLAKE2b-256 checksum How to use checksums |
52e0c97e8d2006482081f7814e7e3bd3a6974a9b2e2fafdbb1289eb194bb89ea
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logRelease files / lokra-0.4.0-py3-none-any.whl
| Download URL | lokra-0.4.0-py3-none-any.whl |
|---|---|
| Size | 91.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
94a56bc4fe45b08bd51df09d7fde6f308b8f8f297215b6b00835fc062bebc21d
|
|
BLAKE2b-256 checksum How to use checksums |
25e436da56428ae2d186555443655d4c3e591ea7a9e11c67df0f1106c4d9f7d4
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logSecurity for lokra 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for lokra-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.