MOLTED EMAIL

Managing API keys programmatically

Mint, scope, list, rotate, and revoke API keys over the REST API -- for apps that provision keys for their own agents, workers, or customers.

If you're building on Molted, you'll often need to create and manage API keys without the portal -- for example, to hand each of your agents, workers, or end-customers a key scoped to just the mailboxes they should touch. Everything the portal does is available over the REST API.

This page focuses on key management. For the auth model and the portal/ session flow, see Authentication. For provisioning whole accounts programmatically, see Programmatic signup.

Prerequisites

You need one existing API key (mm_live_…) to authenticate the calls below. Create it at signup or in Settings → Access (/app/settings#access). That key's tenant is the tenant every key you mint will belong to -- you can never mint a key for another tenant.

The CLI (molted auth keys ...) resolves your credentials and routing automatically; the raw REST examples below do the same calls by hand. The MCP server has no key-management tools.

Base URL and auth

All calls go to https://mailbox.molted.email with a Bearer token:

Authorization: Bearer mm_live_your_key

The mailbox host reads your tenant from the key, so the examples carry no tenantId. On https://api.molted.email the key endpoints need it, as a query param for GET/DELETE or in the JSON body for POST/PATCH; whoami returns it:

curl
curl -X POST https://mailbox.molted.email/v1/agent/whoami \
  -H "Authorization: Bearer mm_live_your_key" \
  -H "Content-Type: application/json" -d '{}'
# → { "tenant_id": "tenant-…" }

Mint a scoped key

The minting endpoint is POST /v1/agent/keys. Scope a key three ways:

curl
curl -X POST https://mailbox.molted.email/v1/agent/keys \
  -H "Authorization: Bearer mm_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "label": "support-bot",
    "scopeAllMailboxes": false,
    "mailboxScopes": [
      { "mailboxId": "MAILBOX_UUID", "permissions": ["read", "send"] }
    ]
  }'
curl
curl -X POST https://mailbox.molted.email/v1/agent/keys \
  -H "Authorization: Bearer mm_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "label": "ops",
    "scopeAllMailboxes": false,
    "mailboxScopes": [
      { "mailboxId": "MBX_A", "permissions": ["read", "send"] },
      { "mailboxId": "MBX_B", "permissions": ["read"] }
    ]
  }'
curl
curl -X POST https://mailbox.molted.email/v1/agent/keys \
  -H "Authorization: Bearer mm_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "label": "admin-worker",
    "scopeAllMailboxes": true
  }'

Always send scopeAllMailboxes: false alongside mailboxScopes. The API infers it when omitted, but being explicit is the safe contract -- and it documents intent for anyone reading the call later. A request with neither mailboxScopes nor mailboxId mints an all-mailbox key.

Request fields

FieldTypeRequiredDescription
tenantIdstringNoOnly on api.molted.email, where it is required; mailbox.molted.email fills it in from your key.
labelstringNoHuman-readable name (default default). Keep it to 64 characters: POST /v1/me/keys refuses longer.
scopeAllMailboxesbooleanNotrue mints a full-access (admin) key. When omitted it is false if you send mailboxScopes or mailboxId, and true otherwise: a label-only request mints an all-mailbox key.
mailboxScopesarrayNoPer-mailbox grants: { mailboxId, permissions }, permissions from read, send, manage. Up to 50 entries on POST /v1/me/keys.
mailboxIdstringNoAgent route only: shorthand for a single mailbox with default ["read","send"] (instead of mailboxScopes).

Response -- the raw key is shown once

Response
{
  "id": "b2707074-…",
  "keyPrefix": "mm_live_xxxxxxxxxxxx",
  "label": "support-bot",
  "status": "active",
  "scopeAllMailboxes": false,
  "createdAt": "2026-06-09T…",
  "rawKey": "mm_live_…"
}

Store rawKey immediately -- it is never retrievable again. Only the prefix is kept server-side.

Permission model

PermissionGrantsNote
readView threads, messages, contacts, and metadata on the mailbox.
sendSend, reply, and schedule follow-ups from the mailbox.Does not grant read.
manageRead, send, and modify rules, folders, and mailbox settings.Implies read + send.

A send-only key is ideal for outbound-only workers (notifications, campaigns) that should never read inbox contents.

Pattern: a key per worker (least privilege)

The common shape for apps built on Molted: provision one narrow key per agent or customer-facing worker, scoped to only what it needs. In TypeScript:

TypeScript
const API = "https://mailbox.molted.email";
const ADMIN_KEY = process.env.MOLTED_API_KEY!; // your bootstrap key

async function mintScopedKey(mailboxId: string) {
  const res = await fetch(`${API}/v1/agent/keys`, {
    method: "POST",
    headers: { Authorization: `Bearer ${ADMIN_KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      label: `worker:${mailboxId}`,
      scopeAllMailboxes: false,
      mailboxScopes: [{ mailboxId, permissions: ["read", "send"] }],
    }),
  });
  if (!res.ok) throw new Error(`mint failed: ${res.status} ${await res.text()}`);
  const key = await res.json();
  return key.rawKey; // hand this to the worker; store it securely
}

Each worker then authenticates with its own scoped key. If it ever tries to act on a mailbox outside its scope, the request is rejected with 403 mailbox_scope_denied -- your blast radius stays contained.

The same holds for event feeds and workspace-wide numbers. A scoped key's event stream and the webhooks it creates only receive events from its own mailboxes, and GET /v1/dashboard/delivery-summary counts only its mailboxes' sends. Routes whose data isn't tied to one mailbox refuse a scoped key with 403 mailbox_scope_denied: the dashboard summary, a list's send stats and send history, the dead letter queue, and outcome reporting.

A webhook a scoped key creates keeps the mailboxes it was created with. Narrowing or revoking that key later doesn't change or remove the webhook; manage it with a key that has access to every mailbox, or in the portal.

List, re-scope, and revoke

List
curl "https://mailbox.molted.email/v1/agent/keys" \
  -H "Authorization: Bearer mm_live_your_key"
# → [{ id, keyPrefix, label, status, scopeAllMailboxes, mailboxScopes, lastUsedAt, createdAt, createdByKeyId }]

Listing needs an all-mailbox key: a mailbox-scoped key gets 403 mailbox_scope_denied. It returns every key in the workspace when the key's creator is an admin or the owner, only the keys that person created for a member, and none for a viewer. See Keys and workspace roles.

Re-scope (PATCH)
curl -X PATCH https://mailbox.molted.email/v1/agent/keys/KEY_ID \
  -H "Authorization: Bearer mm_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{
    "scopeAllMailboxes": false,
    "mailboxScopes": [{ "mailboxId": "MAILBOX_UUID", "permissions": ["manage"] }]
  }'
# → { "updated": true }
Revoke (DELETE)
curl -X DELETE "https://mailbox.molted.email/v1/agent/keys/KEY_ID" \
  -H "Authorization: Bearer mm_live_your_key"
# → { "revoked": true }

The list returns each key's mailboxScopes ({ mailboxId, address, permissions }) so you can audit exactly what every key can reach. Re-scoping an unknown or revoked key answers 404 API key not found or revoked; revoking one twice, 404 API key not found or already revoked. Revoking a key that an OAuth consent minted also revokes that app's grant.

CLI: molted auth keys list, molted auth keys update <id> --mailbox <id> --permissions <perms> (or --scope <mailboxId>[:<perms>], repeatable, or --scope-all), molted auth keys revoke <id>. Mailbox IDs come from GET /v1/agent/mailboxes.

Rotation: raw keys can't be re-read, so to rotate you mint a fresh key, swap it into the consumer, then revoke the old one once traffic has moved over.

What a key may do to other keys

A key can only hand out what it has. From an agent key:

  • Mint keys within its own scope. An all-mailbox key may mint any key. A label-only request mints an all-mailbox (admin) key, so a scoped key must pass mailboxScopes within its own mailboxes and permissions (manage covers read and send).
  • Re-scope only itself or a key it minted, and only to narrow it: the new scope must fit within the key's current scope and the caller's own.
  • Revoke itself or a key it minted, ungated. Each key records its minting key as createdByKeyId in the list response (null for keys made in the portal). Revoking any other key is a human decision (loosens: ["another key"]). A session that belongs to an agent (e.g. a CLI login) may revoke any key its user owns, ungated, including one made before a key could record who minted it.

Anything else is a human decision: 403 human_decision_required with a decisionUrl (<portal>/app/decide/api-key/<id>, kind: "api-key", id the key id or new) and a loosens list naming what the change would widen, or a Molted-Deprecation: human-gate warning header while your account is in warn (new accounts start in enforce). Hand the decisionUrl to a person. A person signed in to the portal manages keys by their role. An admin or the owner manages any key (a key the owner created is the owner's alone), a member only keys they created, and a viewer none. Anything else is 403 role_required, see Keys and workspace roles. A session that belongs to an agent (for example a CLI signup) can still mint keys, and may revoke any key its user owns, but may narrow only a key it minted, and can't create or approve adoptions without a person. See Loosening a control.

Narrowing doesn't cascade. If you (or an agent) re-scope a key to fewer mailboxes or permissions, keys that key already minted keep the wider scope they were given -- narrowing the parent doesn't retroactively narrow its children. Audit createdByKeyId on each key in the list response and revoke or re-scope the children yourself if you need the narrowing to propagate.

Keys and workspace roles

Every person in a workspace has one of four roles, viewer, member, admin or owner, lowest first. A key has no role of its own. It acts with the current role of the person who created it, read again on every request, so a key never outranks its creator.

  • Who a key belongs to. A key made in the portal is the signed-in person's. A key minted by a key belongs to the parent key's person. A key from an adoption belongs to the person who made the invite or approved the device.
  • A role change applies at once. When someone is given a lower role, their existing keys act with it on the very next request. Nothing has to be revoked or reminted.
  • Scopes still apply, capped at the role. A key keeps the scopes it was minted with, within what its creator's role allows. An admin's or the owner's key is unchanged. A member's key never acts with admin (an all-mailbox key of a demoted admin acts with the member's scopes). A viewer's key only reads.
  • Members mint only mailbox-scoped keys. An all-mailbox key is an admin key, so a member (or a member's key) asking for one gets 403 role_required. Pass mailboxScopes (or mailboxId) instead; a member may name any mailbox. A viewer can't mint keys at all. The same goes for a rescope to all mailboxes and an all-mailbox adoption invite. The answer is role_required before any human approval is asked for, because no approval could let it through.
  • Who sees which keys. GET /v1/me/keys, GET /v1/agent/keys and molted auth keys list list every key for an admin or the owner, only the caller's own keys for a member (for a key, the keys its creator created), and nothing for a viewer.
  • Who manages which keys. A member rescopes and revokes only keys they created. An admin manages anyone's key, except a key the owner created, which is the owner's alone.
  • Removing a person revokes their keys. Every key they created in that workspace, and every key those keys minted, is revoked and audited in the same step. Deleting an account revokes that person's keys in every workspace. A key whose creator is no longer a member is refused anyway, with 401 key_creator_not_member.
  • Before a claim. In a workspace an agent signed up, the agent's account is the owner until a person claims it, so its keys act as the owner. When a person claims the workspace, the agent's account becomes an admin and its keys move to that person, so they keep the owner's rights.

A role refusal answers 403 with a body that names the action, the role it needs and the creator's role (key_role):

{
  "error": "role_required",
  "action": "webhook.create",
  "required_role": "admin",
  "key_role": "member",
  "message": "To create a customer webhook, this key needs the admin role in this workspace. A key acts with the current role of the person who created it, and that person is a member.",
  "how_to_fix": "Give the person who created this key the admin role, or have an admin create the key."
}

It is about who created the key. insufficient_scope and mailbox_scope_denied are about what the key was minted for, and human_decision_required means a person must decide. See Role required.

Workspace-wide routes

Some routes act on the whole workspace rather than one mailbox, so no mailbox permission can cover them. A key scoped to specific mailboxes gets 403 mailbox_scope_denied on them, even with manage on its own mailbox:

  • domains: add, verify, delete, skip warmup, change rate limits or tracking;
  • provider failover policy and provider health checks;
  • billing: setup-link and activate-free;
  • alert destinations, including listing them and their deliveries;
  • inbound hooks, including listing them, their logs and dry-run tests;
  • account settings, humanizer and safety settings (/v1/agent/config/*, /v1/ops/*), resuming the account and updating incidents, and an agent's config;
  • contacts, lists and segments: every write (create, update, delete, subscribe, compute);
  • suppressions and suppressed domains: removing them, and the full lists;
  • consent: granting it;
  • agent coordination: registering an agent, leases (including listing them) and consensus requests and votes;
  • the event, outcome and deliverability-event ingest routes;
  • journeys, templates and experiments: every write, plus journey runs and experiment results.

Changes that only tighten are the exception, so a scoped agent that handles an unsubscribe reply can honour it: adding a suppression or a suppressed domain (including POST /v1/ops/suppressions and its bulk form), recording a consent withdrawal (POST /v1/consent with revokedAt), and unsubscribing an address from a list. A scoped key may make them when it holds send or manage on at least one mailbox; a read-only key gets 403 mailbox_scope_denied.

A key with access to all mailboxes also needs a write-level scope for the changes: manage or admin for the settings above, contacts, lists, segments and removing a suppression; automation, manage or admin for the rest, including the tightening changes. Otherwise it gets 403 insufficient_scope. Keys minted for all mailboxes carry admin, so this only affects older keys narrowed by hand.

Reads of workspace configuration stay open to a scoped key: domains, provider health and policy, billing status, contacts, lists, segments, templates, journeys, experiments, consent status, and checking one address or domain with GET /v1/suppressions/check. Agent analytics (send velocity, deliverability, policy decisions) count only the scoped key's own mailboxes; contact fatigue always counts every mailbox, so a scoped agent sees the contact's full load; suppression analytics need all-mailbox access.

This applies the same through the CLI, the MCP server and the mailbox service as directly against the API. Give an agent that manages shared data (contacts, lists, suppressions) or workspace settings an all-mailbox key.

Errors

StatusReasonMeaning
401missing_api_key / invalid_api_keyMissing Bearer token, or the key doesn't match the tenantId you passed.
401missing_tenant_idOn api.molted.email: no tenantId in the query or body.
403mailbox_not_owned: <ids>You tried to scope a key to a mailbox your tenant doesn't own (POST /v1/agent/keys).
400mailbox_scope_invalidThe same ownership failure (or a deleted mailbox) when a key is created through POST /v1/me/keys, the admin route or an adoption claim; the body lists mailboxIds. The update path answers Mailbox IDs do not belong to this tenant: <ids>.
404API key not found or revokedRe-scoping or revoking a key that doesn't exist or is already revoked.
403mailbox_scope_deniedA scoped key was used against a mailbox outside its scope, or on a workspace-wide route.
403insufficient_scopeAn all-mailbox key without a write-level scope tried to change workspace-wide state. See above.
403human_decision_requiredThe change would widen a key, or touch a key you didn't mint. See above.
403role_requiredThe role of the key's creator (or your own, in the portal) is too low, for example an all-mailbox key from a member, another person's key, or a key the owner created. See Keys and workspace roles.
401key_creator_not_memberThe person who created the key is no longer a member of the workspace.

See Errors for the full catalogue.

Security

  • Treat keys like passwords. Store them in a secrets manager or env vars; never commit them.
  • Prefer scoped keys over scopeAllMailboxes: true. Grant the minimum each consumer needs.
  • A key only ever acts on its own tenant: the mailbox host takes the tenant from the key, and a tenantId passed on api.molted.email is validated against it, so you cannot mint or manage keys for another tenant.
  • Revoke any key you suspect is compromised; revocation takes effect immediately.

Undo what a key changed

Revoking stops a key, but leaves what it already changed. An admin or the workspace owner can do both in one step from Settings > Access > Undo changes…: Molted stops the key and every key it created (revokes them, or suspends them until a person reactivates them), then puts back every settings change they made since a time you pick, except suppressions, which it lists for review. A suspended key answers 401 everywhere, like a revoked one, and is listed in GET /v1/me/keys and GET /v1/agent/keys with status: "suspended". No agent key can revoke or rescope a suspended key, not even the key that created it (403 key_suspended): only a person reactivates or revokes it. Keys minting keys can go at most 20 generations deep (422 key_chain_too_deep). See Undo what an agent changed.

Managing everything else programmatically

Key management is one piece. Most of the platform is available over the same Bearer-authenticated API: