---
title: "@octabits-io/connections"
summary: "Connections to outside services for agents and processes: the account an app holds at a mailbox, a helpdesk or any MCP server, kept per scope with its secrets behind a cipher you plug in; its status, refreshed one at a time under a lock; slots a process names, bound per scope to a connection; and every tool an outside server offers reviewed by a person, off until then, pinned by a digest so a changed tool is off again."
install: "pnpm add @octabits-io/connections"
availability: "Available from November 2026"
version: "0.4.0"
license: "MIT"
related:
  - name: "@octabits-io/disclosure"
    url: "https://octabits.io/platform/disclosure.md"
  - name: "@octabits-io/models"
    url: "https://octabits.io/platform/models.md"
  - name: "@octabits-io/postgres"
    url: "https://octabits.io/platform/postgres.md"
  - name: "@octabits-io/result"
    url: "https://octabits.io/platform/result.md"
canonical_url: "https://octabits.io/platform/connections"
---

# `@octabits-io/connections`

Connections to outside services for agents and processes: the account your app holds at a
mailbox, a helpdesk or any MCP server, and what an agent may do with it.

- **The connection**: kept per scope, its secrets and its account sealed through a cipher you
  plug in — the scope's key, or a person's own for their grant — the secrets never in a view, a
  log line or an error.
- **Its status**: `connected`, `needs_sign_in`, `disconnected`. A token is refreshed one caller
  at a time under a lock, so a provider that rotates its refresh tokens never sees two; a
  refresh the provider refuses moves the connection to `needs_sign_in`, which a step that needs
  it waits on.
- **Slots**: a process names what it needs ("a mailbox, `inbox`"); each scope binds the slot to
  one of its connections — never to a person's grant.
- **The tool review**: every tool an outside server offers is off until a person makes it a
  read or an outward act, and the review is pinned to a digest of the tool. A server that
  changes a tool's description, schemas or annotations, or adds one, has it off again until a
  person looks.
- **The register**: where the scope's data goes — every connection with its region, its class
  ceiling, the tools a person allowed (a count of reviews: one the server changed since is off
  all the same) and the slots bound to it.
- **The mailbox**, the first typed capability: one contract (folders, list, read, watch) whatever
  is behind it — IMAP (`@octabits-io/mail/imap`) or a mail provider's MCP server — every field
  marked as the sender's or the mailbox's.
- **The host's own capabilities**: the set is open. A host declares the typed capabilities it
  serves (`capabilities: ['mailbox', 'bank']`) and writes their contracts and adapters in its own
  code; `./mcp` gives every MCP adapter its general half (`callMapped`, `mappedTools`).

```bash
npm i @octabits-io/connections zod     # + @octabits-io/postgres for ./postgres, drizzle-orm for ./drizzle,
                                        #   @modelcontextprotocol/client for ./mcp,
                                        #   ai + @octabits-io/models + @octabits-io/disclosure for ./ai-sdk
```

```ts
import { createConnections } from '@octabits-io/connections';
import { createPostgresConnectionStore } from '@octabits-io/connections/postgres';

const connections = createConnections({
  store: createPostgresConnectionStore({
    db: pool,
    transaction: inTransaction,                 // runs work on one transaction; the refresh lock needs it
    scope: { column: 'org_id', value: orgId },
  }),
  cipher,                                       // { encrypt(owner, text), decrypt(owner, text) }
  record: (change) => ledger.append(change),    // every change, for your ledger
});

// A person connects the organisation's helpdesk; the sign-in comes after.
const helpdesk = await connections.connect(
  { name: 'Helpdesk', adapter: 'mcp', server: 'https://help.example.com/mcp', region: 'eu', ceiling: 'internal' },
  actor.userId,
);

// They review the tools the server lists; every one is off until then.
const states = await connections.reviewState(id, listed);   // new | reviewed | changed | removed
await connections.reviewTool(id, listed[0], 'reads', actor.userId);

// A process binds its slot; a step resolves it, and waits on `connection_needs_sign_in`.
await connections.bind('customer-mail', 'helpdesk', id, { capability: null }, actor.userId);
const bound = await connections.resolve('customer-mail', 'helpdesk');
const tools = await connections.usableTools(id, listed);    // reviewed, unchanged, not off
```

| Entry | Peer | What it is |
|---|---|---|
| `.` | `zod` | the service (`createConnections`), the store contracts and their in-memory references (`createInMemoryConnectionStore`, `createInMemoryRegistrationStore`), the tool digest (`toolDigest`), the vocabulary |
| `./postgres` | `@octabits-io/postgres` (optional, the executor type) | the stores over plain SQL (`createPostgresConnectionStore`, `createPostgresRegistrationStore`) and the four tables' DDL |
| `./drizzle` | `drizzle-orm` (optional) | the four column sets, to declare the tables for drizzle-kit |
| `./mcp` | `@modelcontextprotocol/client` (optional) | a connection to an MCP server: signing in (`createMcpConnector`, `takePendingSignIn`, `clientMetadataDocument`), listing its tools, calling a reviewed one, disconnecting with revocation |
| `./ai-sdk` | `ai`, `@octabits-io/models`, `@octabits-io/disclosure` (optional) | a connection's reviewed tools as an agent's (`connectionTools`): each with its effect, untrusted, of the connection's result class, its arguments through the disclosure gate, every call booked and capped |

The root imports nothing but `zod` and `@octabits-io/result`, so a browser bundle may import
it; the boundary lint holds that. The package type-checks with no Node typings.

## When not to use it

- **Your app's own outward acts.** Sending your own mail is `@octabits-io/mail`; reading a page
  at an address in your records is the guarded fetch of `@octabits-io/server/outbound`.
- **Model providers.** The keys to a model are `@octabits-io/models`' managed providers.
- **Serving MCP.** An MCP endpoint other agents call is `@octabits-io/server/mcp`; this package
  is the other direction.

## A connection

`connect(input, by)` checks what a person declared and creates the row:

| Field | What it is |
|---|---|
| `name` | what people call it |
| `owner` | `null` (the default) for the scope's connection; a person's id for their own grant |
| `capability` | a typed capability the host declared (`mailbox`, or its own); `null` (the default) for an untyped connection: whatever tools its server has. Any other is `connection_invalid` |
| `adapter`, `server` | what speaks to it and where: `mcp` and its URL, `imap` and its host |
| `region` | `eu`, `self-hosted` or `third-country`, as declared; the package cannot verify it |
| `transferBasis` | required for `third-country`, the basis a person confirmed; dropped for any other region |
| `ceiling` | the highest content class the provider may receive in a call, required |
| `resultClass` | the class of what an untyped connection answers; `confidential` by default |
| `secrets` | a record of strings, sealed before it is stored; without it the connection waits for a sign-in |
| `account` | the account the credential belongs to, as the provider named it; sealed like the secrets |
| `grantedScopes`, `expiresAt` | what the provider said about the credential |

A view (`get`, `list`, every answer of the service) carries `hasSecrets` and never the secrets,
and the account opened — `null` once its key is gone. The account is a person's own address as
often as the organisation's, so it is stored under the same key as the secrets: an erasure that
destroys a person's key leaves it unreadable in every copy of the row, a backup's included.
`reveal(id)` answers them plain for the one call that needs them, and only for a connected
connection: gate who reaches it. `signedIn(id, …)` stores what a sign-in or a new password
gave, and the connection is `connected` again. `update` changes the name, region, transfer
basis and classes, and records each change with its old and new value.

`setClient(id, { clientId, clientSecret }, by)` keeps the client details a person registered by
hand at a provider that offers no other way in, sealed with the secrets; the status does not
change, and a sign-in keeps them. `client(id)` answers them for the adapter's sign-in.

`disconnect(id, by)` drops the secrets, sets `disconnected` and unbinds every slot bound to it,
answering the slots it unbound; revoking the token at the provider is the adapter's, before it.
`remove` deletes a connection with its reviews and bindings; `removeOwner(person)` deletes a
person's grants — the erasure step for them.

### The cipher

```ts
interface ConnectionCipher {
  encrypt(owner: string | null, plaintext: string): Promise<string>;
  decrypt(owner: string | null, ciphertext: string): Promise<string | null>;   // null: the key is gone
}
```

`owner` is `null` for the scope's key and a person's id for theirs. `@octabits-io/pii`'s key
store fits behind it. A key that is gone makes the secrets `connection_secrets_unreadable`, and
the account `null`.

**Rows stored before 0.2.** The account was plain text then. Seal what is there once, with the key
it belongs under (`owner`), where your cipher can tell its ciphertext from text — a backfill:
`UPDATE connection SET account = <encrypt(owner, account)> WHERE account IS NOT <ciphertext>`. A
cipher that answers `null` for what it cannot open shows those accounts as `null` until then.

## Refreshing

```ts
const secrets = await connections.refresh(id, async (current, connection) => {
  const answer = await tokenEndpoint(current.refresh);
  if (answer.status === 400 && answer.error === 'invalid_grant') return { ok: false, refused: true, reason: 'invalid_grant' };
  if (!answer.ok) return { ok: false, refused: false, reason: `token endpoint answered ${answer.status}` };
  return { ok: true, secrets: { access: answer.access_token, refresh: answer.refresh_token }, expiresAt: answer.expiresAt };
});
```

The refresh runs under the store's `exclusive`: one caller at a time per connection, across
processes on Postgres (`pg_advisory_xact_lock` on the transaction `transaction` gives it). The
token is refreshed only when it expires within `REFRESH_SKEW_MS` (a minute) or with `force`, so a
caller that waited finds the token the first stored and does not refresh again.

| Outcome | The connection | The answer |
|---|---|---|
| new secrets | sealed and stored, `refreshedAt` set | the secrets |
| `refused: true` (`invalid_grant`, a revoked grant) | `needs_sign_in`, the reason as `lastError` | `connection_needs_sign_in` |
| `refused: false` (a timeout, a 5xx) | unchanged | `connection_refresh_failed`, retry later |

`needsSignIn(id, reason)` is the same move for a call that found the credential refused.

## Tools and their review

A tool as an MCP server lists it — name, title, description, input and output schema,
annotations — is a `ToolListing`. `toolDigest(listing)` is `sha256:` and the hex of its
canonical JSON, keys in order.

- `reviewState(id, listed)` answers each tool's state: `new` (never reviewed, off), `reviewed`
  (unchanged since, with the effect a person chose), `changed` (different from what was
  reviewed, off), `removed` (reviewed, no longer listed).
- `reviewTool(id, listing, effect, by)` records a person's choice, pinned to the digest:
  `reads` (the agent may call it), `outward` (the agent may only propose it) or `off`.
- `usableTools(id, listed)` answers the tools an agent may be given now: reviewed as `reads` or
  `outward`, unchanged since. Nothing while the connection is not usable.

Annotations are shown, never trusted: a `readOnlyHint` is the server's claim, and the review is
what decides. A typed connection's operations are classified in code: `usableTools` refuses it
(`connection_typed`) — an agent never gets its tools — and `reviewTool` only pins a tool its
adapter maps an operation onto, as `reads` or `off`. `pinnedTools(id, listed)` answers the tools
that may be called now on any connection; `./mcp`'s `callTool` checks against it.

## The mailbox

The contract a process reads mail through, whatever adapter is behind it:

```ts
interface Mailbox {
  folders(): Promise<Result<string[], MailboxError>>;
  list(query?: { folder?: string; since?: Date; limit?: number }): Promise<Result<MailSummary[], MailboxError>>; // newest first
  read(id: string): Promise<Result<Mail, MailboxError>>;
  watch(cursor: string | null, options?: { folder?: string }): Promise<Result<MailArrivals, MailboxError>>;
  attachment?(mailId: string, attachmentId: string): Promise<Result<MailAttachmentFile, MailboxError>>; // optional
}
```

- A `Mail` is a `MailSummary` (id, folder, `receivedAt`, from, to, cc, reply-to, subject, flags,
  `hasAttachments`) plus its text, its attachments named (never their bytes) and the headers a
  reply threads on. `mailSchema` and `mailSummarySchema` hold an adapter to it: `checkMail(schema,
  value)` refuses what does not fit (`mailbox_invalid_answer`).
- `MAIL_FIELD_ORIGINS` says who wrote each field: `outsider` — the sender: the subject, the text,
  the names and addresses, the headers, an attachment's name and type — or `system` — the mailbox:
  ids, dates, the folder, the flags, sizes. What the sender wrote is untrusted; a step that reads it
  is tainted.
- `watch(cursor)` answers the ids that arrived since the cursor, oldest first, and the next cursor;
  with no cursor it reports nothing and starts from now. The host keeps the cursor and starts a run
  per id — the id, never the text. `reset: true` means the mailbox could not go on from the cursor.
- **No send.** A reply is an outward act: a proposal a person approves, then a message on your mail
  transport, so its footer, its ledger entry and its delivery report hold. `replyTo(mail)` gives it
  its recipients, `Re: ` subject and threading headers (`inReplyTo`, `references`);
  `threadParticipants(mail)` is what `@octabits-io/proposal`'s `outwardFlags` compares its
  recipients with (`recipient_not_in_thread`).
- `attachment(mailId, attachmentId)` hands over one attachment's bytes (`MailAttachmentFile`:
  `id`, `name`, `contentType`, `bytes`) — for a process that files what arrives, a receipt or a
  signed contract. The name and the type are the sender's, as in `MAIL_FIELD_ORIGINS`: check the
  bytes, never trust the label. Past `ATTACHMENT_MAX_BYTES` (25 MiB) it is `mailbox_too_large`,
  never a part. **Optional:** `@octabits-io/mail/imap` serves it; the mailbox on an MCP server
  (`mcpMailbox`) does not — a provider's tools answer an attachment in no shape a mapping could
  hold — so a host checks `mailbox.attachment` before relying on it and says what is missing.
- `createInMemoryMailbox(mails)` holds mail in memory, every mail checked like an adapter's answer,
  `deliver(mail, files?)` an arrival, `files` the bytes of its attachments by id — for tests and a
  scripted world.

Errors: `mailbox_unreachable` (may pass), `mailbox_refused` (the account or a pinned tool needs a
person), `mailbox_not_found`, `mailbox_invalid_answer`, `mailbox_too_large` (an attachment past
the bound).

## The host's capabilities

A typed capability is one contract with fixed operations, whatever adapter is behind it. The
package ships one, the mailbox (`CAPABILITIES`); a host declares the ones it serves, its own
among them, and `createConnections` is typed by them:

```ts
const connections = createConnections({ store, cipher, capabilities: ['mailbox', 'bank'] });
connections.capabilities;                                            // ['mailbox', 'bank']
await connections.connect({ ...declared, capability: 'bank' }, by);  // 'bank' | 'mailbox' | null
```

Left out, the host serves the shipped ones. A name is lower-case words joined by `-`
(`CAPABILITY_NAME`); a misspelled declaration throws at once. The contract, its operations and its
adapters are the host's code — the package holds the name, refuses what was not declared, and
keeps a typed connection's tools from an agent (`connection_typed`). The store keeps the name as
text: a row named by a capability the host stopped declaring still reads, and binds to nothing.

## Slots

`bind(process, slot, connectionId, requires, by)` binds a process's slot to a connection that
serves what the slot needs — `requires.capability`, or `null` for an untyped connection
(`connection_capability_mismatch` otherwise). A capability the host did not declare is refused
first (`connection_capability_undeclared`): a process document is data, and names whatever its
author wrote. A person's own grant is refused
(`connection_personal`): a process runs for the whole scope and outlives people. `resolve`
answers the bound connection when it is usable: `slot_unbound` refuses a launch, and
`connection_needs_sign_in` is what a step waits on.

## The register

`register()` lists the scope's connections — never a person's grant — each with its view, the
number of tools enabled as reads and as outward acts, and the slots bound to it. It is what a
page shows as "where our data goes", and what an export for the records of processing reads.

## `./mcp` — a connection to an MCP server

```ts
import { createMcpConnector, takePendingSignIn, clientMetadataDocument } from '@octabits-io/connections/mcp';
import { createOutboundFetch } from '@octabits-io/server/outbound/node';

const outbound = createOutboundFetch();                           // public addresses only
const identity = { name: 'The Office', redirectUrl: `${origin}/api/connections/callback`, metadataUrl: `${origin}/oauth/client.json` };

const connectorFor = (orgId: string) => createMcpConnector({
  connections: connectionsFor(orgId),
  scopeKey: orgId,
  registrations,                                                  // the deployment's RegistrationStore
  client: identity,
  pending,                                                        // { put(state, entry), take(state) }, short-lived
  fetch: outbound.fetch,
});

// GET /oauth/client.json — the client ID metadata document
return Response.json(clientMetadataDocument(identity));

// POST /api/connections/:id/sign-in — send the person to the authorization server
const started = await connectorFor(orgId).startSignIn(id, actor.userId);
if (started.ok) return Response.redirect(started.value.authorizationUrl);

// GET /api/connections/callback?code&state — the person comes back
const entry = await takePendingSignIn(pending, url.searchParams.get('state') ?? '');
if (!entry.ok || entry.value.by !== actor.userId) return problem('mcp_sign_in_expired');
await connectorFor(entry.value.scopeKey).finishSignIn(entry.value, { code: url.searchParams.get('code') ?? '' }, actor.userId);

// The review page, and an agent's tools
const listed = await connector.listTools(id);                    // → connections.reviewState(id, listed)
const tools = await connector.usableTools(id);                    // reviewed, unchanged, not off
const call = await connector.callTool(id, 'search_tickets', { customer });
```

**Signing in** is the SDK's `auth()`: the server's protected resource metadata, the
authorization server's metadata, PKCE, the resource indicator, the code exchange. The client is
registered in the order the MCP specification gives:

1. the details registered by hand on the connection (`setClient`);
2. the deployment's client ID metadata document, where the authorization server advertises
   `client_id_metadata_document_supported` and `client.metadataUrl` is set — nothing is
   registered, and `clientMetadataDocument(identity)` is the document to serve there;
3. dynamic registration, kept once per authorization server in the deployment's
   `RegistrationStore` and reused by every scope (a registration that lapsed is made again; a
   client secret a server issues anyway needs `deploymentCipher`);
4. none of these: `mcp_sign_in_failed`, and a person registers the client by hand.

The deployment is a public client (`token_endpoint_auth_method: 'none'`). What the callback needs
waits in `pending` under the `state` the authorization address carries, for ten minutes
(`pendingTtlMs`), and is taken once: `takePendingSignIn` answers `mcp_sign_in_expired` for
an unknown, a used or a late one. The entry names its scope and who started it; check that the
callback is theirs. `finishSignIn` refuses an entry of another scope.

**Whose account.** The token belongs to whoever signed in at the provider, and that may not be the
organisation's account. `exchangeSignIn(entry, { code })` exchanges the code and saves nothing: it
answers the secrets to save and the `account` the server names — the ID token's `email`,
`preferred_username` or `name` when the token endpoint sent one (read without checking its
signature, as OpenID Connect allows for a token straight from the token endpoint over TLS), else the
same from the `userinfo_endpoint` in the server's metadata, else `null`. Show it, ask the person to
type it where it is `null`, have them confirm it is the organisation's, then save it:
`connections.signedIn(id, { ...exchange.signedIn, account }, by)`. Hold the exchange in between as
you would the secrets: sealed, and short-lived. `finishSignIn` is the exchange and the save in one,
the account kept where the server named it.

**Calling** never lets the SDK refresh on its own. The transport has no auth provider; the
connector sets the bearer token on each request, from `connections.refresh` — one caller at a
time under the connection's lock, the token refreshed only when due. A 401 forces one refresh
and retries the session once; a second 401 is `mcp_unauthorized` and moves the connection to
`needs_sign_in`, as a refused refresh does.

**Every request** — discovery, registration, tokens, revocation, the MCP server — goes through
the `fetch` you pass. Pass the guarded fetch (`@octabits-io/server/outbound/node`): the address
of an MCP server is one a person typed, and the guarded fetch dials public addresses only.

**A tool call** runs only for a tool that is reviewed and unchanged on a listing taken in the
same session (`mcp_tool_not_allowed` otherwise), and answers the effect a person allowed beside
the result. An `outward` tool's call belongs to the approver: make it only for a proposal a
person approved, with the arguments they saw.

**Disconnecting** revokes the refresh token at the authorization server's revocation endpoint,
where it has one (best effort, answered as `revoked`), then disconnects the connection.

### A mailbox on an MCP server

A mail provider's MCP server becomes a `Mailbox` when you map its tools onto the contract: per
operation, the tool, its arguments from the contract's input, and the contract's value from its
answer (`toolJson(result)` reads structured content or a JSON text part). Connect it with
`capability: 'mailbox'`, and have a person pin the tools the mapping names (`mappedTools`) as
`reads`:

```ts
import { mappedTools, mcpMailbox, toolJson, type McpMailboxMapping } from '@octabits-io/connections/mcp';

const mapping: McpMailboxMapping = {
  list: { tool: 'search_email', args: ({ folder, limit }) => ({ mailbox: folder, limit }), result: (r) => (toolJson(r) as Found[]).map(toSummary) },
  read: { tool: 'read_email', args: ({ id }) => ({ emailId: id }), result: (r) => toMail(toolJson(r) as Found) },
};
for (const listing of (await connector.listTools(id)).value.filter((t) => mappedTools(mapping).includes(t.name))) {
  await connections.reviewTool(id, listing, 'reads', personId);   // shown to the person first
}
const inbox = mcpMailbox({ connector, connectionId: id, mapping });
```

A tool the server changes after it was pinned is not called: the operation fails with
`mailbox_refused`, naming the tool, until a person pins it again. Every answer is held to the
contract. `watch` lists since the cursor's instant, so it sees at most 200 arrivals between two
watches.

### A capability of your own on an MCP server

`mcpMailbox` is built on the general half every MCP adapter shares. An operation is an
`McpOperation<In>` — `{ tool, args(input), result(output) }` (`McpMailboxOperation` is the same
type) — and `callMapped(connector, connectionId, operation, input)` calls it, answering what
`result` made of the tool's answer, or one of three failures:

| Key | When |
|---|---|
| `refused` | a person can fix it: the tool is not pinned or changed since (`mcp_tool_not_allowed`), the connection needs a sign-in or is disconnected, the server refused the credential (`mcp_unauthorized`, `mcp_sign_in_expired`) |
| `unreachable` | any other failure of the call, or a tool that answered with an error — never read into the value; the error answer is beside it (`answer`), for the capability to tell a failure its contract names (an unknown id) from one that may pass |
| `invalid_answer` | `result` threw: the answer is not what the mapping expects |

A capability renames the three to its own keys and holds the value to its contract:

```ts
import { callMapped, mappedTools, toolJson, type McpOperation, type McpToolCaller } from '@octabits-io/connections/mcp';

interface BankMapping { transactions: McpOperation<{ account: string; since: Date | null }>; statement?: McpOperation<{ account: string; month: string }> }

function mcpBank(connector: McpToolCaller, connectionId: string, mapping: BankMapping): Bank {
  return {
    async transactions(account, since) {
      const answer = await callMapped(connector, connectionId, mapping.transactions, { account, since });
      if (!answer.ok) return err({ key: `bank_${answer.error.key}`, message: answer.error.message });
      return checkTransactions(answer.value);                         // the host's contract
    },
  };
}
mappedTools(mapping);   // the tools a person pins as reads — any record of operations
```

**Which mapping.** A host with more than one mapping for a capability (a bank, served by each provider's
tools) names it in the connection's adapter: `mcp/<mapping>`, lower-case words joined by `-`. The connector
treats `mcp` and every `mcp/<mapping>` alike; `isMcpAdapter(adapter)` says whether an adapter is one, and
`mcpMapping(adapter)` answers the mapping's name (`mcp/qonto` → `qonto`, `null` for a plain `mcp`):

```ts
await connections.connect({ name: 'Business account', capability: 'bank', adapter: 'mcp/qonto', server, region: 'eu', ceiling: 'confidential' }, by);
const mapping = BANK_MAPPINGS[mcpMapping(view.adapter) ?? ''];   // the host's, by name
```

There is no generic capability factory on purpose: what an answer must be, how a cursor moves
and what a missing value means are the contract's, and each capability writes its own.

## `./ai-sdk` — a connection's tools for an agent

`connectionTools(options)` answers the tools a step's agent may use of one connection now — the
`usableTools` of its source (`createMcpConnector`, or any adapter with `usableTools` and
`callTool`) — as `agentTool`s of `@octabits-io/models`, ready for `runAgentToExit` or
`streamAgentTurn`:

```ts
import { connectionTools } from '@octabits-io/connections/ai-sdk';

const helpdesk = await connectionTools({
  source: connector,                           // createMcpConnector({ … })
  connection: view,                            // connections.get(id)
  disclosure: { class: 'internal', audit: { sink: log.sink({ scopeKey, correlationId: runId }) } },
  restore: (args) => vault.restore(args),      // pseudonym tokens back to values, after the gate
  prefix: 'helpdesk_',
  limits: { calls: 20, bytes: 200_000 },       // this step's caps for the connection
  meter: (use) => usage.book(use),             // { connection, tool, bytes, outcome }
  admit: ({ connection }) => rateLimit.take(connection),
});
if (!helpdesk.ok) return helpdesk;             // connection_not_connected | connection_tools_unavailable
await runAgentToExit({ model, tools: { ...own, ...helpdesk.value.tools }, propose, modelClass, checkpointCipher, … });
```

- **The effect a person chose.** A `reads` tool runs; an `outward` one becomes a proposal through
  `propose`, and runs when the approval path calls `runProposedToolCall` with the arguments the
  approver saw.
- **Untrusted, of the connection's class.** Every tool is `untrusted`: once one answered, the run
  is tainted — its fetches of an address the agent chose are refused, its proposals say what they
  were drafted after, and its checkpoint is sealed (`checkpointCipher`). Every tool carries the
  connection's `resultClass` (`confidential` unless a person declared lower), so an agent whose
  model is not cleared for it is refused before the first model call.
- **The gate on the arguments.** Each call passes `guardSystemCall` of `@octabits-io/disclosure`
  with the connection as the system and its `ceiling` as the limit: `disclosure.class` is what the
  arguments are (omitted, `confidential`), a detector may raise it, and above the ceiling the call
  never leaves — the agent sees `{ refused: 'above_ceiling' }` and the log a denial. `restore` runs
  only after the gate let the call through, so a pseudonym token reaches the server as its value
  only within the ceiling; declare `disclosure.class` as the class of those values.
- **Booked, capped, admitted.** `meter` receives every call by connection with the bytes it
  answered (`ok`, `refused`, `failed`). `admit` is your rate limit for the connection across the
  scope: `false` answers the agent `{ refused: 'rate_limited' }`. Past `limits.calls` or
  `limits.bytes` the tool throws `ConnectionCapReached`, marked never to retry, and the answer
  that crossed the cap never reaches the agent; `usage()` answers what the step has used.
- **Changed mid-step.** A tool turned off or changed since the step began is refused on the
  source's fresh listing: `{ refused: 'not_allowed' }`. A call the server failed throws
  `ConnectionToolFailed` with the source's key (`mcp_unauthorized`, `connection_needs_sign_in`, …).

A JSON Schema from the server is handed to the model as it is; the server checks the arguments
against it, and an approved outward call runs with exactly the arguments the approver saw.

## Every change, for your ledger

`record(change)` is called after each change: `connected`, `client_set`, `signed_in`, `refreshed`,
`needs_sign_in`, `updated`, `disconnected`, `removed`, `tool_reviewed`, `bound`, `unbound` —
with the connection, who (`null` for the package itself), when, and what changed, never a
secret. Hand the service a store and a `record` bound to one transaction to keep the change and
its entry together.

## Storage

Four tables. The scope column is yours on the first three; the registrations are the
deployment's and carry none.

| Table | Key | What a row is |
|---|---|---|
| `connection` | `id` | a connection, its secrets and its account as ciphertext |
| `connection_tool` | `(connection_id, tool)` | a person's review of one tool, with the digest it is pinned to |
| `connection_binding` | `(scope, process, slot)` | a slot bound to a connection |
| `connection_registration` | `issuer` | the deployment's client registration at one authorization server |

**Plain SQL.** `connectionDdl`, `connectionToolDdl`, `connectionBindingDdl` and
`connectionRegistrationDdl` emit them, each with `{ table, scope: { column, type } }`.
`createPostgresConnectionStore({ db, transaction, tables, scope })` runs on any
`SqlExecutor`; `transaction(work)` runs `work` on one transaction — PGlite's
`(work) => db.transaction(work)`, a `pg` pool's client between `BEGIN` and `COMMIT`.

**Drizzle.** Spread the column sets into your tables and declare the composite keys with your
scope column; the store runs over `drizzleExecutor`:

```ts
import { connectionBindingColumns, connectionColumns, connectionRegistrationColumns, connectionToolColumns } from '@octabits-io/connections/drizzle';
import { drizzleExecutor } from '@octabits-io/postgres/drizzle';

export const connection = pgTable('connection', { orgId: text('org_id').notNull(), ...connectionColumns }, (t) => [index().on(t.orgId)]);
export const connectionTool = pgTable('connection_tool', { orgId: text('org_id').notNull(), ...connectionToolColumns }, (t) => [primaryKey({ columns: [t.connectionId, t.tool] })]);
export const connectionBinding = pgTable('connection_binding', { orgId: text('org_id').notNull(), ...connectionBindingColumns }, (t) => [primaryKey({ columns: [t.orgId, t.process, t.slot] })]);
export const connectionRegistration = pgTable('connection_registration', connectionRegistrationColumns);

const store = createPostgresConnectionStore({
  db: drizzleExecutor(db),
  transaction: (work) => db.transaction((tx) => work(drizzleExecutor(tx))),
  scope: { column: 'org_id', value: orgId },
});
```

A test holds every column set equal to its DDL, column for column; one conformance suite runs
the in-memory store, the SQL store on PGlite and the SQL store over `drizzleExecutor`, and an
integration suite races ten refreshes on a Postgres pool.

## Errors

Every call answers a `Result`. `./mcp` adds `mcp_not_mcp`, `mcp_sign_in_failed`,
`mcp_sign_in_expired`, `mcp_unauthorized`, `mcp_call_failed` and `mcp_tool_not_allowed`; `./ai-sdk`
adds `connection_not_connected` and `connection_tools_unavailable`, and throws
`ConnectionCapReached` (`connection_cap_reached`) and `ConnectionToolFailed`. The root's:
`connection_invalid`, `connection_transfer_basis_missing`,
`connection_not_found`, `connection_disconnected`, `connection_needs_sign_in`,
`connection_secrets_unreadable`, `connection_refresh_failed`, `connection_personal`,
`connection_typed`, `connection_capability_mismatch`, `connection_capability_undeclared`,
`slot_unbound`, and
`connection_store_failed` for the store. A message never carries a secret.

## Not in it yet

Tickets and calendars as shipped capabilities come after the mailbox has shaped the contract; a
host that needs one sooner declares it as its own. The
mailbox on IMAP is `@octabits-io/mail/imap`. The design is
`docs/specs/connections.md` in the platform repository.