# Agents

> Register each AI coding agent as an MCP client with its own key and access level, so it reaches your database only through Osevel.

Source: https://osevel.com/docs/guides/agents/

An **agent** is an MCP client you register by name: Cursor, Codex, Claude Code, OpenCode or any
other. Each agent gets an access level and a token. osevel then knows which agent made each
change, shows only the tools its access level allows, and lets you revoke it.

> **Status: Phase 1, slice 1.** Every agent still uses the shared agent database role. The access
> level is enforced by the MCP server. Revocation is also enforced inside the database. Per-agent
> database roles come in slice 2. See [What this does not protect against](#what-this-does-not-protect-against).

## Register an agent

```bash
osevel agent add cursor-main --ide cursor --access write
```

- `--ide`: `cursor`, `codex`, `claude-code`, `opencode` or `other`. It only decides which
  configuration snippet is printed.
- `--access`: `read` (the default), `write` or `schema`.
- The command needs an interactive terminal and a confirmation code, like `approve`.

It prints the MCP server entry to add to the IDE's user-level configuration, for example for
Cursor (`~/.cursor/mcp.json`):

```json
{
  "mcpServers": {
    "osevel-cursor-main": {
      "command": "npx",
      "args": ["osevel", "mcp", "--project", "myapp"],
      "env": { "OSEVEL_AGENT_TOKEN": "art_…" }
    }
  }
}
```

The snippet starts the CLI with `npx @osevel/cli`, which fetches the published package. Add
`--local` to print a configuration that starts this installed CLI by absolute path (node and
`dist/bin.js`), or `--command <path>` for another install, for example
`/usr/local/lib/osevel/dist/bin.js`. IDEs start MCP servers with a minimal `PATH`, so the
paths are absolute.

The token is shown once. osevel stores only its SHA-256. If you lose the token, revoke the
agent and add a new one. Keep the snippet in the user-level file: a project file such as
`.cursor/mcp.json` can end up in git with the token.

## Access levels

| Level    | Tools                                                                                                                                                                                             |
| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read`   | `query` (from sight `masked`), `performance` (slow statements, plans, index advice; no row values), `inspect` (questions about rows answered without values of private columns), `get_schema`, `list_changes`, `status` |
| `write`  | adds `execute` (data writes, under policy and approvals), `rehearse` (the same write rolled back: rows per table and the policy's verdict) and `backfill` (fills a column in small journaled batches) |
| `schema` | adds `migrate` (schema changes, which always need approval)                                                                                                                                       |

Tools above the level are neither listed nor callable. Policy, approvals and undo apply exactly as
before at every level.

## What an agent sees

Next to what an agent may **do** (its access level) is what it may **see** (journal v28; see
design/agent-1-data-exposure.md). Every column of a managed
table has a class (`open`, `coarse`, `masked`, `hidden`; `osevel classify`), and every agent has
one of four levels:

| Sight       | The agent receives                                                                 | Tools it gets         |
| ----------- | ---------------------------------------------------------------------------------- | --------------------- |
| `structure` | Tables, columns, types, keys, plans. No answer about rows                          | no `query`, `inspect` |
| `shape`     | Answers about rows without values: counts, which rows, null or not (**default**)   | `inspect`, no `query` |
| `masked`    | Rows through the `osevel_masked_<schema>` views: private columns as stand-ins      | adds `query`          |
| `clear`     | As `masked`, and may ask a person for a timed reveal of named columns              | as `masked`           |

```bash
osevel agent add cursor-main --ide cursor --access write --sight shape
osevel agent sight cursor-main masked      # asks for the confirmation code
osevel agent sight cursor-main shape       # lowering: no code, applies at the next call
```

- **New and existing agents see `shape`.** Raising needs the confirmation code; lowering does not,
  and a running server applies it at its next call. The dashboard can lower it, never raise it.
- **Results and errors never carry a value of a column that is not open** for a registered agent,
  whether or not the database enforces the classes (the server filters them and rebuilds errors
  without values).
- **Raw SQL reads need the classes enforced in the database** (`osevel exposure on`): with free SQL
  on the real tables a value could be found by narrowing (`WHERE email LIKE 'a%'`). With the
  classes enforced the agent role cannot read, filter on or return a private column of a real
  table at all; the database refuses it.
- **Where each level is enforced.** The masked views show rows only to a login that may see
  `masked` (`may_see_masked()` inside the view). In daemon mode every agent session has its own
  database user (Security 8), so the database checks the level **of that agent**. Without the
  daemon all agents share one database role: the database then enforces the highest level of any
  active agent (with every agent at `shape`, the views are empty and no row value can be read even
  with the agent role's password), and the level of each agent is enforced by the MCP server.
- `inspect` answers count against a daily guess budget (500 per agent) when they compare a value
  with a masked column, so repeated guessing cannot read a low-variety column.

### Partial forms and the key

A masked column shows a stand-in such as `email_9f3c1a`: a keyed hash, equal for equal values.
Where it helps an agent, a person may show part of the value instead (journal v29):

```bash
osevel classify set public.users.email masked --partial domain   # …@example.org
osevel classify set public.cards.number masked --partial last4   # …4242
osevel classify set public.users.born masked --partial year      # 1990
osevel exposure rotate-key       # new key: every stand-in changes, kept ones stop matching
```

### Reveals (`clear`)

An agent at `clear` gets `request_reveal`, `read_revealed` and `end_reveal` (journal v30). It
asks for named columns with a reason; nothing is readable until a person decides:

```bash
osevel reveal list               # waiting and open reveals
osevel reveal show 4             # columns, the agent's reason, what was read (never values)
osevel reveal grant 4 --minutes 10 --rows 200   # asks for the confirmation code
osevel reveal deny 4
osevel reveal end 4
```

- At most **15 minutes on a production database** (`database settings`), 60 elsewhere; a row
  budget (default 1000). Hidden columns can never be revealed.
- The agent reads only through `read_revealed` (table, columns, filters; no SQL). The database
  function behind it checks the reveal, its end, its budget, that the agent still sees `clear`,
  and a token that only the agent's MCP server holds (never shown to the model), and logs every
  read with its table, columns and row count, never the values.
- **The panel decides too**: the database's Agents area has a Reveals view (Grant with minutes
  up to the maximum and a row budget, Deny, End), each decision signed with one passkey gesture
  and applied through the bridge's remote role. Granting on a production database stays at the
  terminal (`osevel reveal grant`, the panel shows the command); denying and ending work in the
  panel everywhere, since they only take power away. The database refuses a decision from anyone
  but the terminal and the panel, the agent's own server included.

## Agents in a project with several databases

A project can hold several databases (`osevel projects`). An agent belongs to the project
and has one grant per database: the same agent name in two databases of a project is the same
agent, registered in each database with its own role, token and access. Enforcement stays in each
database.

**One writable database.** An agent may read several databases but writes to one by default:
text it reads in one database can steer a write in another (prompt injection across databases).
Write power is access `write` or `schema`, a granted capability that is not read-only, or a granted
D1 `write` template. Giving an agent write power in a second database of its project (`agent add`,
`agent access`, `capability grant`, `d1 template grant`) is refused unless the command carries
`--second-write`, and then needs a confirmation of its own that names the other databases. A
database of the project that cannot be checked counts as writable.

## Manage agents

```bash
osevel agent list            # active agents (--all includes revoked ones)
osevel agent access codex write
osevel agent revoke codex
osevel log --agent codex     # only this agent's changes
```

- **Raising** an agent's access needs the confirmation code. Lowering it does not.
- The tool list follows the new level when the agent's MCP server next starts (restart the IDE).
  A **lower** level takes effect at once in the database: a running server's next write that the
  new level does not allow is refused before it runs.
- **From the dashboard** (Agents & sessions → Registered agents), a paired device can revoke an
  agent or lower its access with one passkey confirmation. It can never raise access: the bridge
  refuses, and the database refuses too (the `remote` role may only revoke or lower).
- **Revoking** is final and takes effect at once:
  - the token no longer starts an MCP server;
  - a server that is already running can no longer record changes, so its writes are refused before they run.
  - A revoked agent keeps its name, so the name cannot be reused.
- Once any agent is registered, `log` shows an AGENT column. Unregistered sessions and undo changes
  show `-` there.

Raw SQL writes can be turned off later without sealing the agent; the next raw write is refused
at once. Turning them on asks for the code and needs a standard agent with write or schema
access:

```bash
osevel agent raw-write cursor off
osevel agent raw-write cursor on
```

## Tasks

You can leave a task for a registered agent; the agent takes it when it asks for one.

```bash
osevel task add claude-cap "Ship every paid order from yesterday"
osevel task list             # open and taken tasks (--all, --agent <name>)
osevel task cancel 3
```

- Every registered agent has two more MCP tools:
  - `next_task` takes its oldest open task and marks it `taken`;
  - `complete_task` closes the task with a note for you.
- The server's instructions say how many tasks were open when the session started. Nothing starts the agent for you: it takes a task only while a session is open in its IDE. In practice, you ask it to "do your next task".
- **From the dashboard** (Agents & sessions), **Give task…** leaves a task and **Cancel task** cancels one, without a passkey. A task grants no permission: the agent still works only through its own tools, access level and capabilities.
- The task text reaches the model as an instruction from you. Treat it like anything you would type into the IDE yourself. The agent's closing note is its own text and is shown as such.
- The database keeps the rules (`tasks_guard`, journal v7):
  - only you create or cancel tasks, from the terminal or the dashboard;
  - only an agent's MCP server takes and closes them;
  - a revoked agent can no longer take one, and nobody deletes them.

## Agents that work together

Agents of the same database know about each other and can pass work along (journal v31; step
8-9 of design/promises-plan.md). Nothing is locked or queued.

- **Awareness.** `status` lists the other agents connected now and the changes of other agents
  that wait for approval, with their tables. After a write, the result says when another agent has
  a change waiting on a table the statement names.
- **Handoffs.** `hand_off` leaves a task for another agent by name ("check the new index on
  public.orders after my migration"). The other agent takes it with `next_task`, as **another
  agent's words, never the user's instruction**, and closes it with `complete_task`; its note is
  the reply the first agent reads with `my_handoffs`. The dashboard shows the thread on the tasks
  page.
- **A handoff grants nothing.** The receiver works with its own access, sight, capabilities and
  approvals.
- **The database keeps the rules** (`tasks_guard`): only an agent's MCP server writes a handoff;
  to another active agent of the same database that takes handoffs; never to itself; at most 20 an
  hour and 2000 characters; an agent at sight `clear` (which may hold revealed values) hands off
  only to agents at `clear`; sealed agents do not hand off.
- Switch it off for an agent (both directions): `osevel agent handoff <agent> off`. The dashboard
  can switch it off, never on.

## Notes and lessons

What people and agents learned about a database is kept in it (journal v32; step 10). A note is
at most 500 characters about the database, a table or a column; a lesson is a note that came from
a correction.

```bash
osevel note add public.orders.status "'held' means waiting for a refund, never ship"
osevel note list                     # accepted and proposed notes
osevel note accept 12                # an agent's proposal becomes a note
osevel note reject 13
osevel note retire 4
osevel deny 31 --lesson "Never update orders without a status filter"
```

- **Agents only propose** (`propose_note`); a person accepts or rejects. Only accepted notes reach
  agents: text an agent read in a row must not become every later agent's instruction.
- Agents get notes **when they matter**: `get_schema` carries the notes of each table and column,
  up to ten database-wide notes are in the server instructions, and `find_tables` searches table
  and column names and notes by words.
- A proposal from an agent at sight `clear` is flagged for the reviewer (it may quote a value). A
  note whose table or column is gone is marked stale and no longer given to agents.
- **The panel decides too**: the database's Agents area has a Notes view (Accept and Reject for
  proposals, Retire for accepted notes), each signed with one passkey gesture. The note's text is
  shown as the agent's own words.

## Rehearsal

`rehearse` (agents with raw writes) runs one data write in a transaction that is **always rolled
back**, with a 10-second statement and 1-second lock limit, and returns rows per table (cascades
included), what policy would decide (let it through, ask the user, refuse) and the notes people
left on those tables. Nothing is changed or journaled and no row value comes back, so it works at
every level of sight; a filter on a private column is refused by the database as for any read.
`DO`/`CALL` blocks cannot be rehearsed. When a write needs approval, the request the user sees
already carries the measured effect of the same trial run.

## Measurement

```bash
osevel agent stats              # every agent, last 30 days
osevel agent stats cursor-main --days 7 --json
```

Per agent, from the journal of the database only: sessions, tool calls, committed changes and
rows, refused statements, approvals asked and denied, changes a person undid, reveals asked and
granted, handoffs sent and received, notes proposed and accepted. Counts, never statements or
values; nothing is sent to us. The panel shows the same counts for the last 30 days on each
agent's page.

## Auditor agents

An auditor is a sealed agent that reads who can do what and writes a report about it (Phase 3).
It changes nothing.

```bash
osevel agent add auditor --ide other --access read --profile sealed --auditor
osevel agent auditor someagent on      # a sealed agent; asks for the code
osevel task add auditor "Audit who can write and which grants are unused"
osevel report list
osevel report show 1
```

Its MCP server connects with a separate database role, `<prefix>_auditor`, that can only run four
audit functions: `audit_agents`, `audit_capability_grants`, `audit_activity` and
`audit_role_privileges`. They return metadata only (names, levels, counts, times), never SQL
text or row data. The agent gets them as tools, plus `save_report`. Only a sealed agent can be an
auditor; the dashboard can turn the flag off but never on. A report is the agent's own text:
check its claims. Its instructions list the exact commands it may suggest for each finding (access,
raw writes, seal, revoke, capability revoke and remove).

Local agents that run in a sandbox (Phase 3, work packages 3-5) will use this; an IDE agent can be
an auditor today.

## Tested with real IDEs

On 2026-11-17 one agent per IDE was registered with `--local` on a local Postgres 17 project and
used from the real client (the Phase 1 gate "the IDEs connect"):

| IDE                                        | Access | Result                                                                            |
| ------------------------------------------ | ------ | --------------------------------------------------------------------------------- |
| Claude Code (`claude mcp add`, user scope) | write  | read and a data write; the change is recorded under the agent                     |
| Cursor (`~/.cursor/mcp.json`)              | write  | read                                                                              |
| Codex (`~/.codex/config.toml`)             | read   | read; a requested `UPDATE` was refused because `execute` is not offered at `read` |
| OpenCode (`opencode.json`)                 | write  | read                                                                              |

Every session was recorded in `agent_sessions` under its agent. Found and fixed on the way: the
printed `claude mcp add` command put the server name after `--env`, which takes several values, so
`claude` read the name as an environment variable.

## Without a token

An MCP server started without `OSEVEL_AGENT_TOKEN` refuses to start: a forgotten, copied or
old configuration must not get a session with every tool and no agent identity. For a local test,
`osevel mcp --unregistered` still serves such a session (all nine tools, no identity) and says so on
stderr. Configurations printed before this change (by `init`, without a token) must be replaced
with the one `osevel agent add` prints.

## What the database enforces

Journal version 3 (`003_agents.sql`) adds the `agent_reverse.agents` table and an `agent_id`
column on `changes` and `agent_sessions`.

- Only the approver role (your CLI) can write the registry. The `agents_guard` trigger refuses
  every other writer, including the admin (SQLSTATE `AR005`).
- Column grants let the approver change only `access` and `revoked_at`. A revoked agent can never
  be un-revoked.
- The `remote` role (dashboard bridge) may update `access` and `revoked_at` too, but `agents_guard`
  lets it only revoke or lower access, never raise it or insert an agent.
- `changes_guard` refuses to record a change for a revoked or unknown agent, a data write for an
  agent with `read` access, and a schema change for an agent without `schema` access. Undo
  changes never carry an agent.
- `sessions_guard` refuses a session for a revoked agent. A session's agent never changes.
- `changes.agent_id` is written once. The journal role has no UPDATE privilege on it.

## What this does not protect against

In this slice the token is an identity and a revocation handle, not a security boundary.

- The MCP server process reads the project's role passwords from the local store. A process
  running as your OS user that can read that store can bypass osevel's agent identity
  entirely, as described in [security.md](https://osevel.com/docs/security/model/#local-secrets-and-the-confirmation-code).
- The agent can read its own IDE configuration and so its own token. It can also read another
  IDE's configuration on the same machine and start the server as that agent.
- Access levels are enforced by the MCP server, not by database privileges. All agents share the
  agent role.

Slice 2 moves these limits into the database (one role per agent) and the local bridge (tokens
checked by a process the agent cannot impersonate).
