Skip to main content
Trinity
Updated Nov 17, 2026main@87e21ff
API Reference

Authentication

Trinity supports three authentication methods: admin password login, email verification login, and MCP API keys. All authenticated API calls require a Bearer token in the Authorization header.

Concepts

  • JWT Token -- All authenticated API calls require a Bearer token in the Authorization header. Tokens use HS256 signing, are valid for 7 days, and are invalidated when the backend restarts. Logging out revokes the token immediately (a server-side blacklist holds it until its natural expiry) — an exfiltrated token dies with the session instead of living out its 7 days.
  • MCP API Key -- Keys prefixed with trinity_mcp_ also work as Bearer tokens. Used for MCP server authentication, agent-to-agent communication, and machine integrations. Every key has a scope that bounds what it can reach — see MCP key scopes.
  • Agent-Scoped Key -- An MCP API key restricted to a specific agent, used for agent-to-agent calls.

Admin Login

POST

/api/token

Admin login using form-encoded POST (not JSON). Returns a JWT bearer token. The username field accepts admin or the admin's registered email address.

curl -s -X POST http://localhost:8000/api/token \
  -d 'username=admin&password=your-password'

# Response
{"access_token": "eyJ...", "token_type": "bearer"}

Email Login (2-step)

POST

/api/auth/email/request

Step 1: Request a verification code sent to the user's email.

curl -X POST http://localhost:8000/api/auth/email/request \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com"}'
POST

/api/auth/email/verify

Step 2: Verify the code and receive a JWT token on success.

curl -X POST http://localhost:8000/api/auth/email/verify \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "code": "123456"}'

# Response
{"access_token": "eyJ...", "token_type": "bearer"}

Both steps take a JSON object. A body that is not valid JSON, or not an object, answers 422 with Request body must be a JSON object; a missing or malformed field answers 422in FastAPI's validation shape. On /verify a malformed body also counts as a failed attempt for the per-address rate limit, so it is not a free probe. POST /api/access/request parses its body the same way.

Code requests share one budget per address: 3 in 10 minutes, counted together across the web sign-in, the MCP email sign-in and the Telegram, WhatsApp and Slack /login steps. A request over the budget gets the same answer as any other, and no email is sent.

The verify step re-checks the email allow-list before redeeming a code. An address that is not allow-listed gets the same 401 as a wrong code, whatever channel minted the code.

A sign-in email belongs to at most one account, compared case-insensitively. Every sign-in path finds the account by its email, so whoever holds an address holds that identity — which is why changing it needs proof (see Changing your sign-in email).

The same email code can sign you in from inside an MCP client without any key — see MCP Integration → Signing in with an email code.

Second Factor Pending

If the account requires two-factor authentication, a correct password returns HTTP 403 — the login is not complete, so no session is issued:

{"detail": "mfa_required", "mfa_required": true, "mfa_enrolled": true,
 "enrollment_required": false, "challenge_token": "eyJ..."}

There is no access_token and no token_type. Finish the login by presenting the challenge_token to the second-factor verification step (or the enrollment step, if the account has not enrolled yet) — that is what returns the real token. Two-factor authentication requires an entitlement; on an instance where it is enabled, its routes are listed in the API docs at /docs.

Three outcomes, three status codes:

StatusMeaning
200Session issued — access_token present
403Credentials correct, second factor required — no session
401Credentials rejected — no session, no challenge

One other 403 exists: before first-run setup has created the admin, POST /api/token answers 403 with setup_required.

The email route (/api/auth/email/verify) is not an OAuth2 grant and keeps its 200 for the same case, simply omitting access_token.

Scripts and unattended clients: check the status, and check for the token.

resp=$(curl -s -w '\n%{http_code}' -X POST http://localhost:8000/api/token \
  -d 'username=admin&password=your-password')
code=$(echo "$resp" | tail -1)
body=$(echo "$resp" | sed '$d')

if [ "$code" = "403" ]; then
  # Don't echo $body — a challenge carries a short-lived challenge_token,
  # and script stderr often ends up in CI logs.
  echo "login needs a second factor this script cannot complete" >&2
  echo "use an MCP API key (Settings -> MCP Keys) instead" >&2
  exit 1
fi

token=$(echo "$body" | jq -r '.access_token // empty')
[ -n "$token" ] || { echo "login issued no session" >&2; exit 1; }

Two-factor authentication applies as soon as the account enrols or an administrator enables the role policy — including before anyone has enrolled — so an unattended credential can start receiving 403s without its own configuration changing. For automation, prefer an MCP API key (trinity_mcp_*), which is not subject to the second-factor flow.

Changing your sign-in email

Binding a new sign-in email takes proof that you own the mailbox:

  1. POST /api/users/me/email/code with {"email": "new@example.com"} sends a 6-digit code to the new address (at most 3 codes per 10 minutes).
  2. PUT /api/users/me/email with {"email": "new@example.com", "code": "123456"} binds it.

A bind code completes only your own bind and never signs anyone in; a sign-in code never binds. Wrong guesses are capped as for email sign-in. An address another account already holds is refused with 409 email_in_use. On an install that cannot deliver email (no email provider configured), an admin may bind without a code, and the bind is audited as unverified; anyone else gets 409 email_verification_unavailable. Both routes accept a signed-in session only. In the UI this is Settings → General → Admin sign-in email, or the Sign-in email step of first-run setup.

Changing your password

PUT /api/users/me/password with {"current_password": "...", "new_password": "...", "revoke_api_keys": false} changes the password of the signed-in account (in the UI: Settings → General → Password). It takes a signed-in session (MCP keys are refused) and an account that already has a password; an email-only account gets 409. The new password must meet the first-run rules. Five wrong current passwords in 15 minutes block further attempts for the window.

A change signs every other session of the account out: a token issued before the change is refused everywhere, the WebSocket and terminal sockets included, and the response carries a fresh token for the caller. MCP keys are not sessions, so they keep working unless revoke_api_keys is true, which revokes the keys you created (never an agent's own key); the response says how many still work. The change survives a backend restart; a new ADMIN_PASSWORD value in .env still overrides it at the next start. See Setup → Changing the admin password.

Terms of use

A person signed in to the app who has not accepted the instance's current terms gets 403 with {"code": "terms_required", "version": "..."} on every call except signing out, GET /api/users/me and the terms routes themselves; the app then shows the terms screen. Logins from scripts and the CLI, MCP keys of operators and above, and agent keys are never asked. See Setup → Terms of use.

Using Tokens

Include the token in the Authorization header for all authenticated requests. MCP API keys (trinity_mcp_*) can be used in the same way as JWT tokens.

curl -H "Authorization: Bearer <token>" \
  http://localhost:8000/api/agents

MCP key scopes

Every MCP key carries a scope. The scope is fixed at creation and decides what the key can reach:

ScopeWhat it can reachHow it is created
userThe owner's full role, including admin, as a person. Every write except those that take a signed-in session, such as binding a credential or creating and listing keys (below); MCP lists every operator tool to it except the ones whose route takes a signed-in session. Never expires.Any user, for themselves — Settings → MCP Keys → Create API Key (the default; admins see it as the Standard choice under Key scope)
agentIts own agent (heartbeats, reports, result callbacks), the agents it is permitted to call, and the agents it spawned — see What an agent key reaches. Never satisfies an admin gate.Minted automatically when an agent is created and injected into the container
systemThe platform's own system agent; bypasses agent permission checksMinted for trinity-system only
connectorConsumption-only, bound to one agent: its exposed skills and chat, nothing elseMinted from the agent's Expose via MCP panel (POST /api/agents/{name}/connector/key, owner only); the secret is shown once
portal_delegateExactly one route — exchanging an end-user email for a Workspace session, so a trusted backend can act as that person. Every other path is refused.Admin, human-only — the Portal delegate choice on the create-key form; the exchange endpoint requires an entitlement
opsRead-only, route-fenced: GET /api/version, fleet status/health/schedules/alerts/costs/auth-report under /api/ops/, GET /api/monitoring/status, host and container telemetry, the agent roster, execution stats and slots, execution history and the live log stream, subscription usage. Every write and every other endpoint is refused; it gets no MCP tools and cannot open the event stream.Admin, from an interactive browser session only — the Ops (read-only) choice on the create-key form. No key of any scope can mint one
ops_writeFour writes, route-fenced: POST /api/agents/{name}/circuit-breaker/reset, POST /api/agents/{name}/start, POST /api/agents/{name}/stop and POST /api/agents/{name}/executions/{id}/terminate. It cannot start or stop the system agent or an ephemeral agent (403 ops_write_protected_target), and it cannot start an agent when that would issue the agent a new platform key (409 ops_write_would_mint_key). It cannot read: pair it with an ops key. Every other operation is refused (403); it gets no MCP tools and cannot open the event stream. POST /api/mcp/validate still reports it valid — that call only describes a key and grants nothing.Admin, from an interactive browser session only — the Ops (operational writes) choice on the create-key form. No key of any scope can mint one

The keys page badges non-standard scopes (Agent, Ops (read-only), Ops (writes), System, Portal Delegate) so a bounded key is never mistaken for a personal one. Requesting any other scope on POST /api/mcp/keys is a 400.

Scope fences match the path the request was actually routed to, never a URL rebuilt from the Host header. Separately, any request whose Host header contains /, ?, #, \, @, whitespace or a control character is refused with 400 Invalid Host header (a WebSocket handshake is closed with code 1008), so a crafted header cannot make a forbidden route look like an allowed one.

Creating or listing keys needs a signed-in session. POST /api/mcp/keys (every scope), POST /api/mcp/keys/ensure-default and GET /api/mcp/keys accept only a browser or login (JWT) session. An MCP key of any scope, your own user key included, gets a 403 and no key is created or listed. Both create routes write a key_create entry to the audit log. The list shows your own keys; an admin sees every key.

A key is a narrowing of its owner, never a decoupling. An ops key is the bounded machine credential for a monitoring dashboard that must keep working under enforced two-factor authentication (key validation never passes through the second-factor flow). It still requires its owner to hold the admin role at call time: demoting or suspending the owner stops the key. Mint ops keys under a dedicated service admin account, and revoke-and-re-mint any ops key held by a departing admin.

An ops_write key is the write sibling for ops automation. It is refused on every operation as soon as its owner is no longer an admin (403 ops_write_owner_not_admin) or is suspended (401), and a password change with revoke keys revokes it. Until the key itself is revoked, POST /api/mcp/validate keeps reporting it valid: that answer is about the key, not its owner, and is no evidence the owner binding failed. Demoting the owner suspends the key rather than revoking it: promoting the owner back to admin makes it work again, so revoke the key to end it. An ops_write key cannot undo a person's containment of an agent: when starting the agent would issue it a new platform key (because its key was revoked, deleted or is missing, or its container has to be rebuilt), the start is refused with 409 and {"code": "ops_write_would_mint_key"} and nothing changes; a person has to start that agent. A person's start repairs the key as before, and after that the ops_write key can start the agent again. A writer that also reads holds two keys, so offboarding re-mints both.

Every key-authenticated call is attributed to the key. The audit log records the key id, key name, and scope beside the owner, and GET /api/audit-log filters on mcp_key_id and mcp_scope — see Audit Trail.

What a Key Is Not

An MCP key resolves to the user who owns it, carrying that user's role. On a default installation where the admin owns the agents, an agent's injected key would otherwise satisfy a plain "admin only" check.

Three gates stop that:

  • Admin gates are an allowlist over scopes. Only a browser session, a user key, and the system key can pass an admin-only endpoint; agent, connector, portal_delegate, ops, ops_write and any scope invented later are refused. An individual endpoint may opt a bounded scope in — the ops reads above do, and circuit-breaker reset opts ops_write in — but the owner's admin role is still checked afterwards.
  • Endpoints whose blast radius is operator-scale require a human caller in addition to an admin role — API keys are rejected there regardless of the owner's role.
  • Grant and identity routes require a person. Some owner-level routes grant an agent new power or change who you are. They reject agent-scoped keys even when the owner is an admin (see the lists below).

The human-only gate applies to:

  • Approving an oversized data-retention deletion
  • Turning usage sharing on or off, or dismissing its consent ask
  • Restarting or reinitializing the system agent
  • Registering, editing, or syncing a skill source
  • Reading an agent's credential checklist
  • Reading, verifying, or rotating an agent's own MCP key (these additionally require an interactive browser session)
  • Minting an ops or ops_write key (interactive browser session) or a portal_delegate key
  • Binding an agent to a GitHub repository
  • Writing an agent evaluation
  • Adding or removing organizational (dept-* / reports-to-*) tags

Two more sets of routes are human-only for any owner, not only admins:

  • A person only— a browser session or the person's own user key. Agent-scoped keys (on their own agent or any other), the system key, and every other scope get a 403 with code person_required. This covers PUT /api/agents/{name}/autonomy, capabilities, capacity and api-key-setting, plus turning an agent's git pull sync on or off (PUT /api/agents/{name}/git/pull-sync). The refusal comes before the owner check, so it reveals nothing about whether the agent exists. An agent's own key can still create, enable and disable its schedules; autonomy decides whether they fire.
  • A person, or an agent an admin granted the permission — PUT /api/agents/{name}/read-only, resources, timeout, public-channel-model and guardrails accept an agent key only while that agent holds Manage other agents, only on an agent its owner owns, and never its own read-only mode or guardrails. Without the grant the agent gets a named 403 (agent_management_not_permitted). Other agent writes are fenced the same way: another agent's schedules, instruction files, creating and deleting agents, and skills. See Agent Configuration → Permissions to Change Itself.
  • A signed-in session only — no MCP key of any scope, your own included. This covers creating or listing MCP keys, changing your sign-in email (POST /api/users/me/email/code and PUT /api/users/me/email), setting or clearing your personal GitHub token (PUT / DELETE /api/users/me/github-pat), your stored UI preferences (/api/users/me/preferences), and adding an email to the login whitelist (POST /api/settings/email-whitelist). The whitelist add needs an admin's session for every role it can select, user included, because the entry gives the person a signed-in session at that role; no MCP-key scope can add entries.

If you hit a 403 on one of these from an automation, that is the gate working as intended — perform the action from the UI or with a user session.

What an Agent Key Reaches

An agent-scoped key carries its owner's role, but on the backend's own routes it reaches only:

  • Its own agent.
  • Agents it may call — those its owner allowed on its Permissions tab. It can chat with them, give them tasks and loops, and read their history and logs. Being allowed to call an agent never lets it manage that agent.
  • Agents it spawned with its current key. It can call and manage those.
  • The owner's other agents, on the routes a granted permission covers — for example another agent's schedule routes for an agent holding Change other agents' schedules. See Permissions to Change Itself.

While the agent is working for someone, its key is also held to that person's limits. When the person is someone the agent is shared with, the key reads only that person's executions and is refused every owner-tier route (configuration, creating or deploying agents, schedules and other standing work). The key's calls carry the running turn, and a call without it is judged against the turn running on the agent, so a command run from the agent's shell is held too. See Agent Sharing.

Any other agent is refused with the same answer as an agent the key may not access (usually 404, as for one that does not exist), so the key learns nothing about it. This applies whether the agent calls through MCP tools or straight against the backend with its injected key. The operator queue an agent key reads is narrowed the same way, and an agent key never gets the admin view of every user's chat history or sessions. Fleet-wide routes with no agent in the path — the agent list, execution and sync-health summaries, tag counts, telemetry, subscriptions and the /ws/eventsstream among them — answer an agent key with the same reach, never its owner's whole fleet. Two fleet health sweeps keep the owner's view, and a few routes are for people only. The full list is in Agent Permissions. People, user keys and the system key are not affected.

An admin's key acting for an agent

Some MCP tools act as the calling agent itself: raising and withdrawing asks (ask_operator, get_my_ask, withdraw_ask), report, record_metrics, get_objectives, refresh_metric_definitions and the canvas tools. The Workspace project tools are not among them: a request that passes agent_name to a project tool from an admin's key is refused. An agent's own key always acts as its own agent. An admin's user key can act for any agent by passing agent_name to the tool: the MCP server sends the request with an X-Trinity-Act-As-Agent header, and the request is held to that agent as if the agent had made it. This lets a hub running on your own key raise an ask, file a report or write a canvas for an agent.

  • Only a user-scoped key whose owner is an admin may act for an agent. Every other caller that sends the header (an agent or system key, any other scope, a non-admin's key, a browser session) gets 403 act_as_not_permitted; a blank or over-long name is 400 act_as_invalid.
  • A user key that leaves agent_name out is refused, naming the parameter. Nothing picks a default agent.
  • Each admitted request writes one acted_as_agent audit entry naming both you and the agent, and an ask raised this way records who raised it on the agent's behalf.
  • Credentials stay out of this: ask_for_credential and the credential vault still need the agent's own key.

WebSocket Authentication

Two real-time endpoints, two credentials:

EndpointCredentialWho sees what
/ws?ticket=<ticket>A single-use, 30-second ticket from POST /api/ws/ticket (JWT in Authorization). The browser uses this; an MCP client never opens /ws.Scoped to the agents the ticket's user can access: an event naming agents is delivered only when every agent it names is one you may access. Admins see everything. Both live delivery and the reconnect replay are filtered. An unknown or suspended account is closed with code 4001.
/ws/events?token=trinity_mcp_…An MCP key in the query string (Trinity Connect and external listeners)Events for the agents the key's owner can access; an agent key gets only its own reach (see What an agent key reaches). The agent list is re-read from the owner's current account when an agent is created, deleted, shared, unshared or renamed, and about once a minute. Only user, agent (non-ephemeral agents only) and system keys may open it; ops, ops_write, connector and portal_delegate keys are closed with code 4003.

Live connections follow the account. An open /ws socket, /ws/events stream or agent terminal closes when the account behind it changes. A role change, a password change and a key revocation close it at once, and every worker also re-checks its open connections about every 15 seconds, so a suspension or an email change reaches it within that time. A connection whose account is gone, suspended, or whose key was revoked closes with code 4001; any other change closes with 4000, and the client reconnects at the new scope. A terminal sends an error frame first (Your access changed. Open the terminal again to continue. or Your access to this terminal has ended.), closes with 4003 and ends its shell session in the container. Revoking or deleting an MCP key closes only the event streams opened with that key.

API Endpoints

EndpointMethodAuthDescription
/api/tokenPOSTNoneAdmin login (form-encoded)
/api/auth/email/requestPOSTNoneRequest email verification code
/api/auth/email/verifyPOSTNoneVerify email code, returns token
/api/auth/email/handoffPOSTNoneFinish a sign-in the Workspace code page started — body {email, handoff}. Redeems the one-time token the Workspace returns after a correct code for a platform account, in place of a second emailed code; otherwise the same checks, rate limits and 2FA step as /api/auth/email/verify
/api/auth/modeGETNoneGet auth mode configuration — email_auth_enabled, email_code_login_enabled, email_delivery_available (false when no email provider can send; the login page then says the code is in the backend log), setup_completed
/api/auth/logoutPOSTJWTRevoke the current token immediately (idempotent; no-op for MCP keys)
/api/auth/validateGETJWTValidate current token (rejects revoked tokens)
/api/users/meGETJWTGet current user info, including has_password
/api/users/me/passwordPUTJWT only (MCP keys refused)Change your password — body {current_password, new_password, revoke_api_keys?}; signs your other sessions out
/api/users/me/email/codePOSTJWT only (MCP keys refused)Send a confirmation code to a new sign-in email
/api/users/me/emailPUTJWT only (MCP keys refused)Bind a new sign-in email — body {email, code}
/api/setup/statusGETNoneFirst-time setup status
/api/setup/admin-passwordPOSTNoneFirst-run admin creation — provisions the first admin only; 403 whenever a usable admin account already exists, whatever the setup flag says
/healthGETNoneHealth check (503 while schema migrations are incomplete)
/api/access/requestPOSTNonePublic self-signup — adds the submitted email to the login allow-list. Disabled by default (403) until an admin enables public access requests
/api/mcp/keysPOSTJWT only (MCP keys refused)Create MCP API key — body {name, description?, scope?}; scope defaults to user, admins may request portal_delegate, ops or ops_write
/api/mcp/keys/ensure-defaultPOSTJWT only (MCP keys refused)Create a default user key if you have none; returns null when one already exists
/api/mcp/keysGETJWT only (MCP keys refused)List MCP API keys — your own, or every key for an admin
/api/mcp/keys/{id}GETJWTOne of your MCP API keys (never the secret)
/api/mcp/keys/{id}/revokePOSTJWTRevoke (deactivate) an MCP API key
/api/mcp/keys/{id}DELETEJWTPermanently delete an MCP API key
/api/ws/ticketPOSTJWTMint a single-use 30-second ticket for /ws (503 when Redis is unavailable)

MCP API Keys

POST

/api/mcp/keys

Create a new MCP API key. Keys are prefixed with trinity_mcp_. Body: {name, description?, scope?}; scope defaults to user; admins may request portal_delegate, ops or ops_write (any other scope is a 400). See MCP key scopes.

curl -X POST -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-key", "description": "CI integration"}' \
  http://localhost:8000/api/mcp/keys

# Response
{
  "id": "key_abc123",
  "name": "my-key",
  "key": "trinity_mcp_...",
  "created_at": "2026-03-26T12:00:00Z"
}
GET

/api/mcp/keys

List MCP API keys — your own, or every key for an admin. Key values are redacted in list responses. Requires a signed-in session; an MCP key of any scope gets a 403.

POST

/api/mcp/keys/:id/revoke

Revoke (deactivate) an MCP API key. The key immediately stops working for authentication but stays listed.

DELETE

/api/mcp/keys/:id

Permanently delete an MCP API key.

MCP API keys management interface showing key creation and listing

MCP API keys management in the Trinity dashboard

Unauthenticated Endpoints

The following endpoints do not require a Bearer token:

/api/auth/mode/api/auth/email/request/api/auth/email/verify/api/auth/email/handoff/api/access/request/api/setup/status/api/setup/admin-password/api/token/health

Full interactive API docs are available at http://localhost:8000/docs when running locally (Swagger UI). See also the MCP Integration guide for MCP API key usage and agent-to-agent auth, Roles and Permissions for what each role may do, and the Audit Trail for where key-attributed actions are recorded.