Chatto API
Chatto exposes typed protobuf APIs for clients, bots, tools, and operator automation. Use the public ConnectRPC API for normal integrations, realtime for live updates, and the operator socket only for trusted local recovery. The ConnectRPC API reference lists all services and methods.
API Surfaces
Section titled “API Surfaces”| Surface | Path or transport | Use for |
|---|---|---|
| Public ConnectRPC API | /api/connect/chatto.api.v1.* | Normal client and integration behavior. |
| Admin ConnectRPC API | /api/connect/chatto.admin.v1.* | Permission-gated administrative tools. |
| Realtime WebSocket | /api/realtime | Snapshots, public events, and short-gap resume. |
| MCP | /mcp, when enabled | Agent tool discovery and user-scoped operations. |
| Operator API | Unix socket | Root-equivalent local automation and recovery. |
Do not expose the Operator API over a network.
Role Metadata and Permission Decisions
Section titled “Role Metadata and Permission Decisions”chatto.admin.v1.AdminRole contains role metadata and optional aggregate counts.
It no longer includes the permissions and permission_denials arrays. This
also applies to roles returned by AdminUserService.GetMember.
If your integration used these arrays, read decisions through
AdminPermissionService:
- Use
GetRolePermissionMatrixto read one role’s complete matrix. - Use
ListRolePermissionDecisionsto read decision rows in scope pages. - Set the scope to
SERVERto replace the former server-level arrays.
These role-permission reads require role.manage. An authenticated caller
without that permission can read role metadata but cannot read the former
permission summary. Role assignment limits remain available through the role
assignment APIs.
Start With Server Discovery
Section titled “Start With Server Discovery”Call ServerDiscoveryService.GetServer first. It returns the server identity,
the available login providers, the public profile to show before sign-in, and
the software version. Discovery does not expose method-level feature flags, so
pin and test the server releases that your client supports.
Authentication Choices
Section titled “Authentication Choices”| Client | Credential |
|---|---|
| Same-origin browser app | HttpOnly cookie session. No bearer credentials. |
| Cross-origin Chatto frontend | OAuth authorization code with PKCE, then a renewable bearer session. |
| User-authorized client | OAuth authorization code with PKCE, then a renewable bearer session. |
| Bot integration | Bot API key. See Bots & Webhooks. |
| Agent host | See Model Context Protocol. |
| Local recovery automation | Operator socket, not user authentication. |
Access tokens, refresh credentials, and bot API keys are opaque. They are not JWTs.
Authorize a Human User
Section titled “Authorize a Human User”Use this flow when a person lets your app act as their Chatto account. The
examples use https://client.example.com for your app and
https://chat.example.com for the Chatto server.
Publish Your Client Identity
Section titled “Publish Your Client Identity”Serve this Client ID Metadata Document (CIMD) at
https://client.example.com/oauth/client-metadata.json:
{ "client_id": "https://client.example.com/oauth/client-metadata.json", "client_name": "Example Chat Client", "client_uri": "https://client.example.com", "application_type": "web", "redirect_uris": ["https://client.example.com/oauth/callback"], "token_endpoint_auth_method": "none", "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"]}The document URL is your client_id. You do not get a client secret.
- The
client_idin the JSON must exactly match the document URL.client_urimust have the same origin. - Serve HTTP 200 with
Content-Type: application/json, at most 5 KiB, over public HTTPS, without authentication. - The URL must have a non-root path and no query or fragment. Chatto does not follow redirects or fetch private network addresses on a public deployment.
- The callback must exactly match an entry in
redirect_uris.
A server operator can block your client even if its metadata is valid.
Serve the callback page in the same browser tab and origin as the page that
starts sign-in. Process the callback before you load third-party content. Use
Referrer-Policy: no-referrer, and keep callback query strings out of access
logs and analytics.
For a native app, set application_type to native and register a callback
for that app. Literal loopback IP callbacks can change their port. Named
localhost callbacks must use their registered port.
Discover the Server and Start Authorization
Section titled “Discover the Server and Start Authorization”Save this browser module and use it on the sign-in page and the callback page.
Call beginAuthorization() from your sign-in button. Web Crypto requires a
secure browser context.
const issuer = 'https://chat.example.com';const clientId = 'https://client.example.com/oauth/client-metadata.json';const redirectUri = 'https://client.example.com/oauth/callback';const pendingKey = 'chatto-oauth-pending';
function base64url(bytes) { return btoa(String.fromCharCode(...bytes)) .replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');}
async function discover() { const response = await fetch(`${issuer}/.well-known/oauth-authorization-server`, { credentials: 'omit', redirect: 'error' }); if (!response.ok) throw new Error('Chatto discovery failed'); const metadata = await response.json(); if (metadata.issuer !== issuer || metadata.client_id_metadata_document_supported !== true || !metadata.code_challenge_methods_supported?.includes('S256')) { throw new Error('Unsupported authorization server'); } for (const key of ['authorization_endpoint', 'token_endpoint']) { const endpoint = new URL(metadata[key]); if (endpoint.origin !== issuer || endpoint.username || endpoint.password) { throw new Error('Unexpected authorization endpoint'); } } return metadata;}
export async function beginAuthorization() { const metadata = await discover(); const state = base64url(crypto.getRandomValues(new Uint8Array(32))); const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)); const challenge = base64url(new Uint8Array(digest)); sessionStorage.setItem(pendingKey, JSON.stringify({ state, verifier })); const url = new URL(metadata.authorization_endpoint); url.search = new URLSearchParams({ response_type: 'code', client_id: clientId, redirect_uri: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', state }).toString(); location.assign(url.href);}The issuer is the configured public origin of the Chatto server. If you connect through an alias, set the canonical origin. The PKCE verifier stays in your app. Only its SHA-256 challenge goes to Chatto. Each tab has one pending attempt; a new attempt replaces it.
Do not send scope or resource, and do not send scope=openid. Chatto uses
scopes only for MCP, and this flow does not return an ID token. Chatto handles
sign-in and consent. Then it redirects to your callback with code, state,
and iss, or with an OAuth error.
To start account creation, add screen_hint=signup to the authorization
request. The server opens registration and resumes authorization after signup.
This hint does not bypass registration or invitation rules. Older servers can
ignore the hint and show their sign-in page instead.
Validate the Callback and Exchange the Code
Section titled “Validate the Callback and Exchange the Code”Add this function to the module. Call finishAuthorization() once on the
callback page, and treat a rejected promise as a failed sign-in. The iss
check follows RFC 9207.
export async function finishAuthorization() { const callback = new URL(location.href); if (callback.origin + callback.pathname !== redirectUri) { throw new Error('Unexpected callback location'); } const raw = sessionStorage.getItem(pendingKey); sessionStorage.removeItem(pendingKey); history.replaceState(null, '', redirectUri); const pending = raw ? JSON.parse(raw) : null; const query = callback.searchParams; if (!pending || query.getAll('state').length !== 1 || query.get('state') !== pending.state || query.getAll('iss').length !== 1 || query.get('iss') !== issuer) { throw new Error('Invalid authorization response'); } if (query.has('error')) throw new Error('Authorization was not granted'); if (query.getAll('code').length !== 1 || !query.get('code')) { throw new Error('Missing authorization code'); } const metadata = await discover(); const response = await fetch(metadata.token_endpoint, { method: 'POST', credentials: 'omit', redirect: 'error', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code: query.get('code'), code_verifier: pending.verifier, client_id: clientId, redirect_uri: redirectUri }) }); if (!response.ok) throw new Error('Code exchange failed; start sign-in again'); const session = await response.json(); if (session.token_type !== 'Bearer' || typeof session.access_token !== 'string' || !session.access_token || typeof session.refresh_token !== 'string' || !session.refresh_token || !Number.isFinite(session.expires_in) || session.expires_in <= 0 || !Number.isFinite(session.refresh_token_expires_in) || session.refresh_token_expires_in <= 0) { throw new Error('Invalid token response'); } return session;}Use the same client_id and redirect_uri in both requests. The code is
short-lived and works only once. If the exchange fails or you lose the
response, start a new attempt. The token response is ordinary OAuth JSON:
expires_in and refresh_token_expires_in are numbers of seconds. Do not log
codes, verifiers, tokens, or full callback URLs.
Call the API and Renew Access
Section titled “Call the API and Renew Access”Send only the access token to ConnectRPC and realtime:
const session = await finishAuthorization();const response = await fetch( 'https://chat.example.com/api/connect/chatto.api.v1.MyAccountService/GetSettings', { method: 'POST', credentials: 'omit', redirect: 'error', headers: { Authorization: `Bearer ${session.access_token}`, 'Content-Type': 'application/json', 'Connect-Protocol-Version': '1' }, body: '{}' });if (!response.ok) throw new Error('Settings request failed');const { settings } = await response.json();The current permissions of the account still apply to each call. This example keeps the session in memory. Select a storage policy that is correct for your app.
Before the access token expires, send a POST to /oauth/token with
grant_type=refresh_token, the refresh_token, and your client_id. Save
each new token pair together. Serialize refresh requests.
To make a refresh safe to retry, add an optional refresh_request_id:
- Generate a random UUID version 4 for each rotation.
- Save it before you send the request. Keep it secret, like a token.
- If the network fails or the server returns
5xx, retry immediately with the same ID. Stop when you have saved the complete response.
An exact retry during the lifetime of the access token from that rotation
returns the same token pair. If you did not use a token from a newer pair, a
later retry with the previous refresh token gets a new pair. If you used a newer
pair, an older refresh token is stale reuse and revokes the session. An
invalid_grant response means that the user must sign in again.
Realtime Delivery
Section titled “Realtime Delivery”Authenticated clients connect to /api/realtime and exchange protobuf
chatto.realtime.v1 frames. Chatto 0.5 accepts only protocol version 4. The
stream sends authorized public events for messages, edits, reactions, rooms,
membership, profiles, calls, and other activity. A bot usually selects
LIVE_ONLY and reads details through ConnectRPC. The same room membership,
permission, and session checks apply as for the rest of the API.
Realtime does not replace ConnectRPC. Use ConnectRPC for reads, pagination, commands, and read-your-writes results. See Realtime for the protocol and a TypeScript client.
Integration Patterns
Section titled “Integration Patterns”| Goal | API |
|---|---|
| Render room navigation | RoomDirectoryService.ListRooms and ListRoomGroups |
| Read room history | RoomService.GetRoomEvents and RoomService.GetRoomEventsAround |
| Post, edit, or delete messages | MessageService |
| Add or remove reactions | MessageService.AddReaction and MessageService.RemoveReaction |
| List all users of one reaction | MessageService.ListReactionUsers |
| List thread participants | ThreadService.ListThreadParticipants |
| Mark rooms and threads as read | RoomService.MarkRoomAsRead and ThreadService.MarkThreadAsRead |
| Read stored read positions | RoomService.GetRoomReadState and ThreadService.GetThreadReadState |
| Read your time zone and time format | MyAccountService.GetSettings |
| React to bot activations | Realtime events and NotificationService.ListNotificationOccurrences |
| Start DMs | RoomService |
| Read users and profiles | UserService.ListUsers, GetUser, and BatchGetUsers |
| Manage bots and their keys | BotService |
| Manage roles or permissions | chatto.admin.v1 role and permission services |
| Inspect operational health | AdminDiagnosticsService, metrics, and exporter |
ListThreadParticipants returns the distinct authors of current replies. The
root author appears only if they also replied. The batch read-state methods
accept at most 100 targets. A read state without marker means that no
position is stored. A read-state call does not mark anything as read.
Creating a message does not mark its room or thread as read or clear older
notifications. If your client previously relied on that side effect, call
RoomService.MarkRoomAsRead or ThreadService.MarkThreadAsRead when the user
views the messages. Set upToEventId to the newest message the user has seen.
A thread read does not mark the parent room as read.
Page Through Lists
Section titled “Page Through Lists”List methods use a page field. For example, to list rooms:
{ "page": { "limit": 100, "offset": 0 } }The default is 50 items, and the maximum is 100. While page.hasMore is true,
add the number of returned items to offset and request again with the same
filters. Pages are live reads, so changes between requests can move items. To
rebuild local state, collect all pages first, and discard the result if a
request fails.
Search Messages or Threads
Section titled “Search Messages or Threads”Use MessageSearchService.SearchMessages for message search and for My
Threads search. By default, it returns individual messages in relevance order.
To get one result for each followed thread, send:
{ "query": "from:alice", "scope": "MESSAGE_SEARCH_SCOPE_FOLLOWED_THREADS", "groupBy": "MESSAGE_SEARCH_GROUP_BY_THREAD", "order": "MESSAGE_SEARCH_ORDER_THREAD_ACTIVITY", "pageSize": 20}Each result contains message, relevanceScore, and threadContext with the
root, latest reply, room, and thread state. Accessible DM threads are included.
To get the next page, send nextCursor as cursor with the same query and
options. Results are live, so start pagination again after changes.
scopeandgroupByare independent. Omitscopeto group all accessible threads. OmitgroupByto get individual matches in followed threads.NEWESTorders by the newest matching message.THREAD_ACTIVITYorders by the latest thread activity and requires thread grouping.- Room, author, date, and attachment filters apply in all modes.
- Within
FOLLOWED_THREADS, setrootAuthorFiltertoTHREAD_ROOT_AUTHOR_FILTER_VIEWERorTHREAD_ROOT_AUTHOR_FILTER_OTHERSto select who started the threads. Omit it to include all followed threads. This filter also applies toThreadService.ListFollowedThreads. Search still checks roots and replies;from:selects matching message authors.
See the search API reference.
Message Body Tokens
Section titled “Message Body Tokens”Message bodies are plain text with a Markdown subset: headings, emphasis, links and autolinks, inline and fenced code, blockquotes, ordered and unordered lists, and GFM pipe tables with alignment markers.
Bodies can also contain timestamp tokens such as <t:UNIX_SECONDS:F>. Show a
valid token as that UTC instant in the viewer’s locale and time zone. If your
client does not support timestamps, show the token unchanged.
The bundled frontend offers Source and Render tabs for mermaid, svg, and
ansi fences. Add rendered after the language to show only the visual, without
tabs or a toolbar. Click an SVG or Mermaid image to open the large viewer.
Plain fences present code with a preview option.
Mermaid uses Pele, and SVG uses isolated images. Keep the
source unchanged when sending, editing, quoting, or copying messages. Clients
without these renderers can show the code. See Format Messages
for syntax and rendering limits. Rendering does not require an external service.
Programmatic Safety
Section titled “Programmatic Safety”- Use generated protobuf clients, not hand-built JSON or paths.
- Treat
NOT_FOUNDon a singular read as the normal “does not exist” result. - Use pagination. Do not expect unbounded lists.
- Keep access tokens, refresh credentials, and refresh request IDs out of logs, URLs, and issue reports.
- Handle permission errors. Admin APIs check permissions for each method.
Runnable Node Example
Section titled “Runnable Node Example”The Runling bot example
receives outbound webhooks for mentions and DMs. It loads the complete thread,
composes a reply with an LLM through OpenRouter, and posts a thread reply
through the ConnectRPC JSON API. It does not use realtime. The bot needs
message.post-in-thread and read access, and it ignores messages from bots to
prevent reply loops. Follow the example README to set it up.