Skip to main content

Lokra

Lock rows for AI agents. · lokra.dev

An agent's read is masked, then its attacks are blocked because each agent is its own Postgres role

CI License: Apache-2.0 Python 3.11+

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:

  1. 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.
  2. Masking. Medicare numbers, IHIs, phone numbers and emails are masked in results, including inside free-text notes and renamed columns.
  3. 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.
  4. Tamper-evident audit ledger, with reporting. Every request is written to a hash-chained, signed log, and lokra report turns it into a per-agent activity and risk summary.
  5. 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.

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 86400          # hand this token to the agent
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.

Lokra dashboard: agents, statement outcomes and risk flags

The audit log shows every statement, what was masked, why requests were blocked, and each write from proposal through approval:

Lokra audit log: masking breakdown, blocked reasons and activity feed

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 init scaffolds 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.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lokra 0.3.0
File Size Uploaded Provenance Actions
lokra-0.3.0.tar.gz 93.9 kB With provenance Details for lokra-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for lokra 0.3.0
File Interpreter ABI Platform Actions
lokra-0.3.0-py3-none-any.whl Python 3 none any Details for lokra-0.3.0-py3-none-any.whl

Total release size: 176.7 kB

Release files / lokra-0.3.0.tar.gz

Download URL lokra-0.3.0.tar.gz
Size 93.9 kB
Tags Source
SHA-256 checksum
How to use checksums
82576f3a8928c8d88339427570108d24d9b7210a4f07cc8886fc2f6c5d8884b5
BLAKE2b-256 checksum
How to use checksums
71b9c83182c473f0c0a0322e76ac8f097905d364d4f3dcb67a48bb51c14f4610
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 log

Release files / lokra-0.3.0-py3-none-any.whl

Download URL lokra-0.3.0-py3-none-any.whl
Size 82.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ea7c7e7be7ad180acebe0379e9b657e28f7082fef0087ac0b513ae733c7b6650
BLAKE2b-256 checksum
How to use checksums
78d5c4c60dd2778e45d2020e02594bd37740857eb143ac4c8cb0a6f3d379ea04
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 log

Security for lokra 0.3.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.

Select from 2 files

Attestation for lokra-0.3.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 log

A 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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page