Your own agent desk
When your app already signs its agents in (a CRM, a helpdesk, a messaging inbox), they shouldn’t need a second login to answer calls. Your server signs them in to MoreVoice with an agent session, and the softphone engine of @morevoice/softphone takes and places calls with it inside your page: offers from your queues, outbound calls, hold and transfer controls, the copilot.
| Object | ID | What it is |
|---|---|---|
| Managed user | usr_… |
An agent or supervisor your app manages, keyed by your own external_id. No password, invitation or email of ours: they never sign in to the dashboard. |
| Agent session | ags_… |
One sign-in of that person to the agent desk, minted by your server. Its bearer token (mvas_…) is returned once. |
| Socket ticket | A one-use, 60-second pass for one socket (/ws/agent, /ws/call), made from the session. |
1. Sign the agent in from your server
Section titled “1. Sign the agent in from your server”When a signed-in person opens your agent desk, your server creates or updates them as a managed user (the same external_id always updates the same user), then creates their session:
# Your server, when a signed-in agent opens your app's agent desk. A live secret or restricted key with# users:write and agent_sessions:write; never in a browser.# 1. Create the agent the first time, update them after that: external_id is your own id for the person.curl https://api.morevoice.ai/v1/users \ -H "Authorization: Bearer $MOREVOICE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "external_id": "agent-1042", "name": "Dana Levi", "email": "dana@example.com", "role": "agent" }'
# 2. Sign them in for one shift, from your website only. Hand the response (token, expires_at) to their browser.curl https://api.morevoice.ai/v1/agent_sessions \ -H "Authorization: Bearer $MOREVOICE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "external_id": "agent-1042", "ttl_s": 28800, "origin": "https://app.example.com" }'import MoreVoice from "@morevoice/sdk";
const mv = new MoreVoice(); // reads MOREVOICE_API_KEY: a live key, on your server only
// Your server, when a signed-in agent opens your app's agent desk.// 1. Create the agent the first time, update them after that: external_id is your own id for the person.const user = await mv.users.upsert({ external_id: "agent-1042", name: "Dana Levi", email: "dana@example.com", role: "agent" });
// 2. Sign them in for one shift, from your website only.const session = await mv.agentSessions.create({ external_id: "agent-1042", ttl_s: 28800, origin: "https://app.example.com" });
// Hand the browser the token and its expiry (createTokenAuth refreshes before it); never log the token.console.log(user.id, session.id, session.expires_at);const forBrowser = { token: session.token, expires_at: session.expires_at, ws_ticket: session.ws_ticket, ws_ticket_expires_at: session.ws_ticket_expires_at };void forBrowser;import os
import requests
API = "https://api.morevoice.ai/v1"HEADERS = {"Authorization": f"Bearer {os.environ['MOREVOICE_API_KEY']}"} # a live key, on your server only
# Your server, when a signed-in agent opens your app's agent desk.# 1. Create the agent the first time, update them after that: external_id is your own id for the person.response = requests.post( f"{API}/users", headers=HEADERS, json={"external_id": "agent-1042", "name": "Dana Levi", "email": "dana@example.com", "role": "agent"}, timeout=30,)response.raise_for_status()user = response.json()
# 2. Sign them in for one shift, from your website only.response = requests.post( f"{API}/agent_sessions", headers=HEADERS, json={"external_id": "agent-1042", "ttl_s": 28800, "origin": "https://app.example.com"}, timeout=30,)response.raise_for_status()session = response.json()
# Hand the browser the token and its expiry (createTokenAuth refreshes before it); never log the token.print(user["id"], session["id"], session["expires_at"])for_browser = {"token": session["token"], "expires_at": session["expires_at"], "ws_ticket": session["ws_ticket"], "ws_ticket_expires_at": session["ws_ticket_expires_at"]}- Who. Agents and supervisors only, and only active ones (
409 resource_conflictwithmember_deactivatedotherwise). Each managed user takes a seat (402 plan_limitwhen none is free). Passuser_idinstead ofexternal_idfor a member who joined by invitation. - How long.
ttl_sfrom 300 (5 minutes) to 86400 (24 hours), default eight hours, a shift. It never slides: the softphone gets a new session before it ends (step 2). - From where.
originbinds the session to your website: its token and tickets then work only from that exact origin (scheme, host and port). In a browser, always bind it: the agent desk’s REST routes allow cross-origin calls only from the origins of live sessions. - The response carries the
token(once: never log it or store it),expires_at, a firstws_ticketand thews_urlof the agent socket. Give the browser the token, its expiry and the first ticket; the softphone’sserveris the host inws_url. - Signing out. When the person signs out of your app,
DELETE /v1/agent_sessions/{id}: the token and its tickets stop at once, and open sockets close. Deactivating the user (DELETE /v1/users/{id}) ends all of their sessions. GET /v1/agent_sessionslists the live ones (filter byuser_idorexternal_id), andPOST /v1/agent_sessions/{id}/ticketmakes a socket ticket from your server, for clients that cannot call MoreVoice with the token themselves.
A minimal endpoint, behind your own sign-in: it upserts the person and returns their session (mv.users.upsert in Node.js, client.users.upsert in Python):
# What your endpoint sends, for the signed-in person (your own id for them: $ME_ID).curl https://api.morevoice.ai/v1/users \ -H "Authorization: Bearer $MOREVOICE_API_KEY" -H "Content-Type: application/json" \ -d '{"external_id": "'"$ME_ID"'", "name": "Dana Levi", "role": "agent"}'curl https://api.morevoice.ai/v1/agent_sessions \ -H "Authorization: Bearer $MOREVOICE_API_KEY" -H "Content-Type: application/json" \ -d '{"external_id": "'"$ME_ID"'", "ttl_s": 3600, "origin": "https://app.example.com"}'import MoreVoice from "@morevoice/sdk";
const mv = new MoreVoice(); // MOREVOICE_API_KEY: a live key with users:write and agent_sessions:writeconst APP_ORIGIN = "https://app.example.com"; // your website, exactly as the browser sends Origin
/** POST /voice/agent-session in your app: the signed-in person's agent session, for their browser only. */export async function agentSession(me: { id: string; name: string; email: string }) { await mv.users.upsert({ external_id: me.id, name: me.name, email: me.email, role: "agent" }); const s = await mv.agentSessions.create({ external_id: me.id, ttl_s: 3600, origin: APP_ORIGIN }); return { token: s.token, expires_at: s.expires_at, ws_ticket: s.ws_ticket, ws_ticket_expires_at: s.ws_ticket_expires_at };}from morevoice import MoreVoice
client = MoreVoice() # MOREVOICE_API_KEY: a live key with users:write and agent_sessions:writeAPP_ORIGIN = "https://app.example.com" # your website, exactly as the browser sends Origin
def agent_session(me_id: str, name: str, email: str) -> dict[str, str]: """POST /voice/agent-session in your app: the signed-in person's agent session, for their browser only.""" client.users.upsert(me_id, name=name, email=email, role="agent") s = client.agent_sessions.create({"external_id": me_id, "ttl_s": 3600, "origin": APP_ORIGIN}) return {"token": s.token, "expires_at": s.expires_at.isoformat(), "ws_ticket": s.ws_ticket, "ws_ticket_expires_at": s.ws_ticket_expires_at.isoformat()}2. Connect the softphone in the browser
Section titled “2. Connect the softphone in the browser”createTokenAuth signs the softphone engine in with the sessions your endpoint returns. It asks for one when the engine first connects, again shortly before it expires, and once more if MoreVoice refuses it:
import { createTokenAuth, SoftphoneEngine, type SoftphoneSessionErrorCode, type SoftphoneState } from "@morevoice/softphone";
declare function render(state: SoftphoneState): void; // your UIdeclare function showSignedOut(code: SoftphoneSessionErrorCode): void;
const session = createTokenAuth({ // Your endpoint from step 1 (your own cookie or header authenticates it). fetchToken: async () => { const res = await fetch("/voice/agent-session", { method: "POST" }); if (res.status === 401) return null; // signed out of your app: final, "signed_out" if (!res.ok) throw new Error(`agent session: HTTP ${res.status}`); // transient: the engine retries return res.json(); }, onError: (error) => showSignedOut(error.code),});
const engine = new SoftphoneEngine({ auth: session.auth, api: session.api });engine.subscribe(render); // conn, presence, ringing offers, the callengine.configure({ server: "https://api.morevoice.ai" }); // the host in the session's ws_url
// A ringing offer: answer it (the microphone opens), or decline.engine.subscribe((state) => { const offer = state.offers[0]; if (offer && confirm(`Answer ${offer.from}?`)) void engine.answer(offer.offerId);});- The token lives in memory only: never in
localStorage,sessionStorage, a cookie or a URL. Reloading the page asks your endpoint again. engine.status("available"),engine.dial({ number, mode: "me", via: "panel" }),engine.hangup(),engine.mute(on)andengine.dtmf(digits)work as in MoreVoice’s own agent workspace.- When
onErrorfires the engine is signed out (state.connis"unauthorized"). Once the person can work again,engine.reconnectNow()asks your endpoint for a new session.engine.configure(null)signs out and forgets the token.
How it works
Section titled “How it works”The sequence, from sign-in to sign-out:
your backend MoreVoice the agent's browser──────────── ───────── ─────────────────── fetchToken() → POST /voice/agent-sessionPOST /v1/users {external_id, …} → the managed user (upsert)POST /v1/agent_sessions → {token mvas_…, expires_at, {external_id, ttl_s, origin} ws_ticket, ws_url}{token, expires_at, ws_ticket} ─────────────────────────────────────→ kept in memory ← GET wss://…/ws/agent?ticket=<ws_ticket> Origin: your site → presence, offers (the socket stays open; 15 s pings) ← POST /api/auth/ticket Authorization: Bearer mvas_… → {ticket}: one use, 60 s (each reconnect, each outbound call's /ws/call) ← POST /api/sip/calls/{id}/hangup, /api/telephony/… Bearer mvas_… expires_at − 60 s: fetchToken() againPOST /v1/agent_sessions (a new one) → …the next requests use it; open sockets stay upperson signs out of your app:DELETE /v1/agent_sessions/{id} → token and tickets refused, sockets closed (4001)Credentials
Section titled “Credentials”| Agent session token | Socket ticket | |
|---|---|---|
| Looks like | mvas_… |
an opaque string |
| Lifetime | ttl_s: 5 minutes to 24 hours, fixed |
60 seconds, one use |
| Where it goes | Authorization: Bearer on the agent desk’s REST routes |
?ticket= on one socket URL |
| Made by | POST /v1/agent_sessions (your server) |
POST /api/auth/ticket with the token (the softphone), or POST /v1/agent_sessions/{id}/ticket (your server); the create response carries the first one |
| Ends | at expires_at, on DELETE /v1/agent_sessions/{id}, or when the user is deactivated |
when used or after 60 s; on revocation |
The token reaches only the agent desk: the sockets /ws/agent (offers, presence, answer and decline), /ws/call (calls placed from the softphone), /ws/meeting and /ws/join, and the REST routes /api/telephony/*, /api/callbacks/*, /api/agent/*, /api/me/settings, /api/me/extension, /api/me/directory, /api/kb/search, /api/copilot/*, /api/notifications*, /api/queues, GET /api/users, POST /api/sip/calls/{id}/hangup and POST /api/auth/ticket. Every other route answers 403 embedded_route_forbidden, and the person’s role (agent or supervisor) applies as everywhere.
Refresh
Section titled “Refresh”createTokenAuth asks fetchToken for a new session at expires_at minus one minute (refreshBeforeMs; half the lifetime when that is shorter). The new token is used from the next request on; sockets that are open stay open, and the older session simply runs out (revoke it from your server if you prefer: the softphone then reconnects on the new one). A refresh that fails is retried every 15 seconds while the old token still works. If fetchToken returns only a token string, with no expires_at, there is no early refresh: a refused token is refreshed on demand.
Errors
Section titled “Errors”| What happens | What MoreVoice answers | What createTokenAuth does |
|---|---|---|
| The token is refused: revoked, expired, or the user deactivated | 401 agent_session_invalid |
Calls fetchToken once and retries. Refused again: final session_expired (it was past expires_at) or session_revoked |
| The session is bound to another website | 401 origin_not_allowed |
Final origin_not_allowed at once (a new session would be bound the same way) |
| The agent socket closes as signed out (the session was revoked) | close code 4001 |
Calls fetchToken once and reconnects. A second one within 30 seconds: final |
fetchToken resolves null |
Final signed_out |
|
fetchToken resolves something other than an mvas_… token, such as an API key |
Final invalid_token |
|
fetchToken throws (your backend is down) |
Not final: the engine shows offline and retries with backoff | |
| A route outside the agent desk | 403 embedded_route_forbidden |
Passed to the caller (a bug in the calling code) |
Final errors are SoftphoneSessionErrors with a typed code: onError gets each one once, session.error keeps the last, and the engine stops (state.conn is "unauthorized") until engine.reconnectNow().
Origin rules
Section titled “Origin rules”- A session created with
originworks only from that origin: each REST call’sOriginheader must equal it exactly, and a ticket made from it opens sockets only from it (401 origin_not_allowedotherwise). Withoutoriginit works from anywhere, but browsers can’t use it across origins (no CORS). - Browsers send
Originthemselves on cross-origin requests and on every socket. Outside a browser (a Node.js or Electron process), passorigintocreateTokenAuthfor the REST calls, and give the engine aWebSocketthat sends the sameOriginheader. - The agent desk’s REST routes answer CORS for the origins of live sessions only:
AuthorizationandContent-Typeheaders, never cookies (credentials: "omit"). - The API key never leaves your server; the browser only ever holds the session token, in memory.