End-user sessions

Use this when your own users chat with an agent from your website, app or any surface you build. Your server keeps the API key and mints a short-lived session token for each of your users. The browser or app holds only that token.

your server ── API key ──▶ POST /v1/sessions        ──▶ { session_token }
browser/app ── session token ──▶ /v1/channel/...    (never the API key)

Your users never get a Senaiy account. The first time a new external_id arrives, Senaiy creates an end user under your organization. Nobody outside your organization can see or address that end user.

1. Create a signing secret

Portal → Developer → Channels → End-user identity secret → Create secret. Copy the secret to your server. It is shown only once.

Rotate secret issues a new secret and keeps the current one working as the previous secret, so your servers can switch over without downtime. Rotating again retires that previous secret.

2. Sign who the user is

Before you mint a session for a signed-in user, sign their identity with the secret. Two formats are accepted:

  • JWT, HS256. Claims:

    Claim Required Notes
    external_id (or sub) yes Your id for the user, at most 140 characters
    iat, exp yes Unix seconds; at most 24 h apart
    display_name no
    roles no A list of strings
  • HMAC. <base64url(JSON of the same claims)>.<hex HMAC-SHA256 of the base64url part>

import jwt, time
now = int(time.time())
payload = jwt.encode(
    {"external_id": "u_8231", "display_name": "Mona", "roles": ["Accounts Manager"],
     "iat": now, "exp": now + 300},
    IDENTITY_SECRET, algorithm="HS256",
)

3. Mint a session (server side)

POST /v1/sessions. The API key needs the sessions.mint scope.

curl -X POST https://platform.senaiy.ai/v1/sessions \
  -H "Authorization: Bearer $SENAIY_KEY" -H "Content-Type: application/json" \
  -d '{"agent_id": "acme-support", "channel": "web_widget",
       "identity": {"source": "client_signed", "payload": "'$PAYLOAD'"}}'
{"session_id": "…", "session_token": "sst-sf-…", "expires_in": 3600, "end_user_id": "…"}
  • Guests: send "identity": {"source": "anonymous"}. This works only on agents that allow guests.
  • Channel: lowercase letters, digits and _ (for example web_widget, mobile_app).
  • Session length: the agent's setting (default 60 min). You can pass ttl_minutes; the maximum is 1440 (24 h).

4. Talk to the agent (browser or app)

Every channel endpoint takes the session token. An API key on these endpoints is refused with api_key_not_allowed.

Method Path
GET /v1/channel/session Who this session is
POST /v1/channel/runs {"input": "…"} starts a run → {"run_id"}
GET /v1/channel/runs/{id} Status and output; only this end user's runs
GET /v1/channel/runs/{id}/events Live events (below)
POST /v1/channel/approvals/{id} The end user approves or denies a call (below)

One session is one conversation: the agent remembers earlier turns of the same session, and nothing from any other end user's sessions.

Live events

GET /v1/channel/runs/{id}/events streams the run for your surface:

  • With Accept: text/event-stream it is Server-Sent Events. Each connection lasts up to 25 s; reconnect with Last-Event-ID, or ?after=<id>, to resume. The stream ends after finished.
  • Without that header it returns {"events": [...]} for polling.
Event Fields
started
delta text: the next piece of the streamed answer
revised The answer was rewritten; replace what you showed
step A tool call: tool, step_status (running, ok, failed…), runs_as (user = runs as you, agent = runs as the agent)
approval_required tool, approval. Show approve/deny if the tool is confirmed by the end user (below)
sign_in_required tool, connection: the call needs the user's own token. Sign them in on your side, then call POST /v1/sessions/{session_id}/refresh-token from your server
finished reason, output (text), output_ui (interactive answer, if any)

Events are kept for an hour. Model-internal steps are never sent.

The end user confirms a call

In Agent → Tools, a tool that needs approval can be set to End user confirms. In a session from your surface, the run then waits for the end user rather than an operator:

POST /v1/channel/approvals/{approval} with {"approve": true} or {"approve": false}

The decision is audited with the end user's id. With no decision in 10 minutes, the call is denied. Outside your surfaces (portal, API, schedules), an operator still decides.

Browsers

Add your origins in Developer → Channels → Browser origins allowed (one per line, or *). Browsers on those origins can call /v1/channel/* with the session token. No cookies are used. Every other endpoint stays server-side only.

5. Revoke

POST /v1/sessions/revoke with the API key, and one of:

  • {"session_id": "…"}: one session;
  • {"end_user_id": "…"}: every session of that user;
  • {"all": true}: every session in your organization.

A revoked session's token stops working immediately.

Who may use an agent

Agent → Access → Who may use this agent from your surfaces:

Setting Who gets in
Signed-in end users (default) Any session with a valid signed identity
Guests allowed Anyone, including anonymous sessions
Listed roles Signed-in users whose roles include one of the listed strings. Matching is exact, so CFO ≠ cfo

The rule is checked when a session is minted and again on every run. If you tighten it, existing sessions stop working at their next message. Every denial is audited.

What the agent can do for an end user

Each MCP connection on the agent acts either as each user or as the agent (Agent → Access). The run trace labels every tool call the same way.

  • As the agent: works for every session, with the connection's own credential. Calls to your own system also carry X-Senaiy-End-User: a JWT (HS256, signed with your identity secret, aud = the connection name, valid 5 minutes) with sub (end user id), external_id, identity_source, roles, agent_id and session_id. It does not authorize anything. Use it to record "the agent acted for user X", or to filter if you choose. Third-party services (GitHub, Google…) never receive it. Guests can use such a connection only when Guests is switched on for it on the Access tab. It is off by default, and turning it on is audited. Otherwise a guest's call ends with [guest_not_allowed].
  • As each user: each call carries the end user's own token for your system, in place of the connection's credential, so your system applies that user's permissions. The token comes from your identity resolver (below). Without a token the call is refused and nothing is sent. Senaiy never falls back to the agent's credentials or the key issuer's.

Identity resolver

Frappe / ERPNext: apply the patched frappeassistantcore (deploy/frappe-assistant-core/). It provides a ready resolver at /api/method/frappe_assistant_core.api.senaiy_resolver.resolve, which issues each user a short-lived OAuth token. Otherwise, implement the contract below.

Set Agent → Access → Identity resolver URL to an https:// endpoint on your server. Senaiy calls it when a session starts, and again only when the token has expired or your system refused it (HTTP 401). It is never called per message.

POST <your resolver URL>
X-Senaiy-Timestamp: 1762180000
X-Senaiy-Signature: <hex HMAC-SHA256 of "<timestamp>." + body, keyed with your identity secret>
X-Senaiy-Request-Id: <the same on a retry; use it to deduplicate>

{"channel": "web_widget", "identity_source": "client_signed", "external_id": "u_8231",
 "agent_id": "acme-support", "session_id": "…", "reason": "session_start"}

reason is session_start or refresh. Before trusting a request, verify the signature, and check the timestamp is recent (for example, within 5 minutes).

Answer within 5 seconds. After one retry with the same request id, Senaiy gives up and fails closed.

{"status": "identified", "end_user_token": "<token for your system>", "token_ttl_seconds": 900,
 "user_ref": "EMP-0042", "token_type": "Bearer"}
  • token_type is how the token is sent: Bearer (default) sends Authorization: Bearer <token>, token sends Authorization: token <token> (Frappe API key:secret), and Raw sends the token as is.
  • For a guest, answer {"status": "guest"}. You may add an end_user_token that you minted for limited guest actions.
  • Tokens are stored encrypted on the session and deleted with it. Logs and audit keep only a SHA-256 fingerprint.
  • POST /v1/sessions includes resolver_status (identified, guest or unavailable) when the agent has a resolver. A session still works when the resolver is down: answers that need no "as each user" connection carry on normally.
  • When your system answers 401, Senaiy refreshes the token once and retries once. If that fails, the call ends with [sign_in_required].

Test mode, the permission check and the playground

  • Test and live keys. When you create a key, choose Test or Live.
    • A test key mints sessions only for agents in the dev environment, and those sessions are marked as test.
    • A live key mints for any agent, but if the agent uses a connection "as each user", that connection must first pass the permission check. Otherwise you get permission_check_required.
  • Permission check. On Agent → Access, click Run permission check on the connection (or Connectors → Permission check). Name the agent (its identity resolver supplies the tokens), two of your users, and a read whose answer depends on who asks (for example list_documents on ToDo). It passes when:
    • a made-up token is refused (a server that ignores the Authorization header fails here, with a clear message);
    • both users get a token;
    • the two users get different results.
  • Playground. Agent page → Try as an end user (header button): enter one of your users' ids and a message. The run goes through the access rule, your resolver and each connection exactly as a real session would, then its trace opens. The trace shows:
    • the end user and the resolver calls (reason, HTTP outcome, result; never the token);
    • every tool call with its identity, its MCP response and any 401/403;
    • each approval decision.

Errors

Code HTTP Meaning
identity_unsigned 400 client_signed without a payload
identity_not_configured 400 No signing secret yet (step 1)
identity_payload_invalid 400 Not a JWT/HMAC payload, a missing claim, or a lifetime over 24 h
identity_signature_invalid 401 Signed with a secret that is not active
identity_expired 401 exp has passed; sign a fresh payload
agent_access_denied 403 The agent's access rule does not admit this end user
api_key_not_allowed 403 An API key was sent to a channel endpoint
invalid_session 401 The session token is missing, expired or revoked
permission_check_required 409 A live session for an agent whose "as each user" connection has not passed the permission check
test_key_live_agent 403 A test key was used for an agent that is not in the dev environment
Discard
Save
This page has been updated since your last edit. Your draft may contain outdated content. Load Latest Version

On this page

Review Changes ← Back to Content
Message Status Space Raised By Last update on