Python sample code for the Moveworks Conversations API. It includes a client library, runnable examples for each authentication path, and a reference chat app.
Note
The Conversations API is in Controlled Availability. Endpoints, behaviors, and configuration surfaces may change during CA. Contact your Moveworks account team to participate.
Use it to build:
- A custom chat surface where employees sign in through your identity provider and talk to the Moveworks assistant from your portal, app, or other channel.
- A backend or workflow integration where a trusted service acts on behalf of specific users.
- An evaluation harness that runs test queries through the assistant.
- An example MCP server that you host, which lets an AI client such as Claude Code or Gemini call the assistant as the signed-in user.
- A voice experience where employees talk to the assistant out loud. The voice example puts a realtime voice model in front of the API (the voice harness) and has it hand real work to the Moveworks orchestrator through the API, since the API itself is text only.
| Directory | Contents |
|---|---|
moveworks_capi/ |
A client library: HTTP client, auth providers, responses, streaming, file upload, conversations, event polling, webhook verification, and helpers for displaying messages |
examples/ |
Runnable scripts, one pattern each. examples/README.md lists the environment variables, expected output, and common failures for each. examples/voice/ is a browser voice demo on OpenAI Realtime. |
app/ |
A reference web app: a chat surface built on the library. See Reference web app. |
mcp_server/ |
An example MCP server that exposes the assistant as tools, with setup for Claude Code, Gemini, and other MCP clients. See mcp_server/README.md. |
tests/ |
An offline test suite |
moveworks_capi/
├── client.py # HTTP client, Assistant-Name header, retries, backoff
├── errors.py # Named exceptions
├── responses.py # Build turn input, submit, poll to completion; extract text and actions
├── streaming.py # SSE client for /responses/stream
├── files.py # Files API (alpha) upload, for files attached to a turn or a modal FILE field
├── conversations.py # Create, list, fetch, and update conversations; list messages
├── rendering.py # Helpers for displaying assistant messages in a UI
├── auth/ # Okta and Entra ID OIDC (PKCE), self-signed JWT (S2S), HTTP Connector API Key
└── notifications/ # /events polling with a checkpoint, single-event reads; webhook signature verification
Each library module can be used on its own. Two small interfaces connect them:
BearerProvider = Callable[[], str]. The client asks its provider for a bearer on every request, and the provider handles caching.Checkpoint, a Protocol (load(user_id),advance(user_id, event_id)) that the polling loop calls.InMemoryCheckpointandFileCheckpointare included; in production, back it with a database.
Requires Python 3.10 or later and a Moveworks instance set up for the Conversations API (see Moveworks setup).
-
Clone the repo and change into it.
git clone https://github.com/moveworks/conversations-api-starter.git cd conversations-api-starter -
Confirm your Python version, then create a virtual environment and activate it.
python3 --version python3 -m venv .venv source .venv/bin/activateOn an older Python, the install in the next step fails with
File "setup.py" or "setup.cfg" not found. Install Python 3.10 or later and create the virtual environment with it.On Windows, use
pyin place ofpython3, and activate with.venv\Scripts\activatein Command Prompt or.venv\Scripts\Activate.ps1in PowerShell. If PowerShell blocks the script, runSet-ExecutionPolicy -Scope Process RemoteSignedin that window first. -
Install the library and the examples. This is an editable install, so changes you make to
moveworks_capi/take effect without reinstalling.pip install -e . -
To run the reference web app or
receive_webhook.py, also install theappextras. This adds FastAPI and uvicorn.pip install -e ".[app]"For the MCP server, install the
mcpextras instead (pip install -e ".[mcp]"). -
Copy the environment template, then fill in your base URL, Bot Name, and the credential for your auth path.
cp .env.example .env
In Windows Command Prompt, use
copyin place ofcp. -
Check your setup. The script confirms your environment variables, authentication, and a full round trip, and names the likely cause of any failure.
python examples/check_setup.py
If calls fail with
CERTIFICATE_VERIFY_FAILEDon a network that inspects TLS traffic, set theREQUESTS_CA_BUNDLEenvironment variable in your shell to the path of a PEM file containing your company's root CA certificate. -
Make a first call. Each hello-call script creates a conversation, sends a message, and prints the reply and its actions. Use the one for your auth path:
s2s_jwt_call.py,okta_call.py,entra_call.py, orapi_key_call.py.python examples/s2s_jwt_call.py
Run scripts from the repo root so .env and relative key paths resolve.
A first call with the S2S credential: create a conversation, send one turn, wait for the reply, then print its text, actions, and Get Help menu. Replace the placeholder strings with the values from your .env.
from moveworks_capi.auth import S2SJwtBearer from moveworks_capi.client import ConversationsApiClient from moveworks_capi.conversations import create_conversation from moveworks_capi.responses import create_response, extract_actions, extract_handoff, extract_text, wait_for_completion base_url = "https://api.moveworks.ai" bearer = S2SJwtBearer(base_url, issuer="your-issuer", audience="your-audience", key_id="your-key-id", private_key="keys/private_key.pem", user_identifier="[email protected]") client = ConversationsApiClient(base_url, bot_name="your-bot-name", bearer_provider=bearer) conversation_id = create_conversation(client, title="First call")["conversation_id"] response_id = create_response(client, conversation_id, "How do I reset my password?")["response_id"] response = wait_for_completion(client, conversation_id, response_id) print(extract_text(response)) for action in extract_actions(response): print(action.type, action.label) for category in extract_handoff(response): print(category.name, [item.title for item in category.items])
To attach a file to a turn, upload it with files.upload_file, then pass its id in file_ids. A path uploads under its file name; bytes or a stream need a filename. A turn carries up to five files.
from moveworks_capi.files import upload_file uploaded = upload_file(client, "screenshot.png") response_id = create_response(client, conversation_id, "What does this error mean?", file_ids=[uploaded.id])["response_id"]
When the reply offers forms, its text ends with a plain-text copy of each one. A surface that shows forms as buttons displays rendering.strip_flattened_forms(output["message"]) for each MESSAGE output in response.outputs instead of extract_text(response). For other auth paths, swap the bearer provider; see the hello-call scripts in examples/.
| You are building | Start with | Auth path |
|---|---|---|
| A custom chat surface, users sign in with Okta | okta_call.py, then the reference web app |
Okta OIDC + PKCE |
| A custom chat surface, users sign in with Entra ID | entra_call.py |
Entra OIDC + PKCE |
| A backend service that acts on behalf of specific users | s2s_jwt_call.py |
Self-signed JWT |
| An evaluation harness that runs queries as many users | s2s_jwt_call.py |
Self-signed JWT |
| A backend that acts as a single service-account user | api_key_call.py |
HTTP Connector API Key |
| Tools for an AI client such as Claude Code or Gemini | mcp_server/ |
Okta or Entra ID token exchange, or self-signed JWT |
| A voice experience, in the browser or behind a phone line | examples/voice/ |
Self-signed JWT, or HTTP Connector API Key |
| Any of the above, plus proactive notifications | poll_events.py or receive_webhook.py |
Any backend path |
| Path | Credential | Use for | Setup |
|---|---|---|---|
| Okta OIDC (PKCE) | The user signs in through your Okta tenant. | User-facing chat surfaces | Okta setup |
| Entra ID (PKCE) | The user signs in through your Entra tenant. | User-facing chat surfaces | Entra setup |
| Self-signed JWT (S2S) | You hold a private key and sign a JWT with the user in sub for each call. |
Backend services and evaluation harnesses that act on behalf of users. One key can act as any provisioned user. | S2S setup |
| HTTP Connector API Key | A long-lived bearer bound to one user. | Backends that always act as one service-account user | API Credentials. Confirm with your Moveworks account team that the Conversations API accepts an API Key for your Moveworks instance. |
| Pattern | Use when | Example |
|---|---|---|
| Outbound webhook | You can host a public HTTPS endpoint. This is the recommended default: lower latency and less load on Moveworks. | receive_webhook.py |
| Polling | You cannot host a public receiver, or you want to reconcile missed webhook deliveries. | poll_events.py |
Both use the same per-user checkpoint. See Receive via polling and Receive via outbound webhook. To produce a test notification, use trigger_listener.py.
A chat surface over the Conversations API, built on the library, with FastAPI on the server and plain ES modules in the browser. There is no build step.
python -m app # serve on http://127.0.0.1:8090 python -m app --no-stream # submit and poll instead of streaming python -m app --port 9000 # serve on another port
The app serves on port 8090 unless you pass --port. If that port is in use, the app exits with a message naming the port.
The connect screen accepts either credential:
- API key. Paste an HTTP Connector API key. The server holds it in memory only, never on disk or in browser storage.
- S2S credential from
.env. The server reads theMW_S2S_*values (see.env.example), signs the JWT, and exchanges it for a bearer. The browser never receives the key. The screen shows which user the app acts as.
Base URL and Bot Name default to MW_BASE_URL and MW_BOT_NAME. The app makes one ListConversations call to confirm the credential before it opens the chat.
The app handles:
- Streamed replies over server-sent events, with the reasoning trail. A stream that closes before the answer falls back to polling.
- Action buttons for links, callbacks, and modal forms, including user-consent (OBO/UCA) links. Once one action on a message is taken, the others are disabled.
- Offered forms. The plain-text copy of each form is removed from the answer (
rendering.strip_flattened_forms), and buttons that share the label "Complete this request" are named after their form. - Native modal forms (
GetModal,RefreshModal,SubmitModal), including conditional fields that refresh when a field flaggedtriggers_refreshchanges. - Smart-handoff actions, and the Get Help menu from
Message.handoff. AHANDOFF_ACTIONopens the menu from its place in the actions row. Otherwise the menu sits behind one button on the newest turn. - Citations, as a collapsed Sources list.
- Feedback, with an optional comment on "not helpful" (
additional_feedback). - Proactive notifications from the events API. Follow-ups for the open conversation join the thread, and notifications for other conversations appear in a drawer.
- Live agent replies (
actor: LIVE_AGENT) as they arrive, under the agent's name and picture fromsender_infowhen present, or "Live agent" otherwise, and the farewell after the user exits the chat. - A conversation list with titles, paging (
next_cursor), rename, archive, and an archived view. - Conversation history, with older pages loaded on demand and attached file names shown.
The app runs locally with one connected Moveworks instance per process. It binds to 127.0.0.1, has no login, and rejects requests with a non-local Host, cross-origin writes, and non-JSON writes, so other websites cannot drive it through your browser. Do not expose it on a network.
The demo app is a styled build of the same surface, with file attachments, inline form cards, a protocol inspector, motion, dark mode, and a test notification form. To build your own surface, fork this repo.
Before the code in this repo can make calls, your Moveworks instance must be set up for the Conversations API, per the Conversations API overview:
- Your Moveworks account team enables the Conversations API for your Moveworks instance. Requests return
404until it is enabled. - You create the Conversations API chatbot in Moveworks Setup. Its Bot Name is the
Assistant-Nameheader value on every request. - You create a credential for your auth path, following that path's setup guide. The users you act for must resolve against your Moveworks roster, by email by default.
To receive proactive notifications, the user must have sent a message through your Conversations API integration. Moveworks routes proactive messages to the user's most recent channel; see the proactive notifications overview.
- A production chat UI. The reference web app runs on localhost for one Moveworks instance, with no login or multi-user sessions. Hosting and hardening are up to your integration.
- A batch evaluation harness. Wrap the S2S JWT provider in your own parallelization and output.
- Live agent session state. The app renders agent replies, handoff actions, and the action that ends the chat, but does not track queue position or whether the session is still open.
- File upload in the reference app. The library uploads files (
files.upload_file), but the app has no attach button and shows modalFILEfields as unsupported. ListResponseMessages. Useconversations.list_messages, which returns the messages for the whole conversation.- An async client. The library uses
requests. In async code, call it from a worker thread withasyncio.to_thread, as the reference app does.
This repo is sample code, not an official Moveworks SDK. The API is standard REST and works with any HTTP client.
- Send turns as
chatoractioninput. A typed turn is{"input": {"chat": {"text": ...}}}, with text up to 20,000 characters and up to five files infiles. A button press is{"input": {"action": {"callback_id": ...}}}. The flat{"text"}and{"callback_id"}inputs are deprecated.responses.user_inputbuilds either. - Upload files before the turn that attaches them. The Files API is in alpha and enabled per Moveworks instance; until it is enabled, uploads return
404.files.upload_filesendsPOST /rest/v1alpha1/filesasmultipart/form-data, with thepurposefield before thefilepart as the API requires. A file can be up to 100 MB;upload_filechecks the size and the filename rules before it sends anything. A large file can need more than the client's per-request timeout, so passtimeouttoupload_file. Like a turn, an upload is not resent after a timeout, and a timed-out upload may have been stored with noidreturned. Moveworks detects the content type from the bytes and returns it ascontent_type. A file expires 24 hours after it is created, and a turn that references an expired id, or a file another user uploaded, is rejected. There is no operation to read, list, or delete a file. - Use the
/rest/v1base path./assistant/v1is deprecated, and modals are available only on/rest/v1. To correlate a request with Moveworks logs, read thex-trace-idresponse header. - Render both
actionsandMessage.handoff. Assistant replies can carry anactionsarray (URL_ACTION,CALLBACK_ACTION,MODAL_ACTION,HANDOFF_ACTION), which a text-only client drops.responses.message_actionsnormalizes it.Message.handoffcarries the Get Help menu and can appear on any turn, including during a handoff. Unless the message carries aHANDOFF_ACTION, offer it on the newest turn. - Open the handoff menu from a
HANDOFF_ACTION. Render its label in its place in the actions row. Pressing it opens a menu built from the same message'shandoffoptions and sends nothing. Omit it when the message has no handoff options. The menu ishandoff.handoff_categories[], each with aname, an optionaldescription, andhandoff_items[]. AnACTIONitem carries a regularaction; aTEXTitem carriestextto display.responses.message_handoffnormalizes it. - Attribute live agent messages by
actor. ALIVE_AGENTmessage is from a human agent. Agent replies arrive on responses of their own, through the events API or a webhook like proactive notifications, and in conversation history.sender_info.display_nameand the optionalsender_info.avatar_urlgive the agent's name and picture for live chats through the ServiceNow integration, when both of these are on: Agent names and avatars in your ServiceNow instance (Conversational Interfaces > Settings > Agent Chat > User Chat Settings), and Enable Agent Impersonation in Moveworks Setup (Ticketing Automation > Handoff > Message Brokering). Withoutsender_info, show a generic label such as "Live agent". The agent's name, if any, is in the message text. - Treat
avatar_urlas external content. The picture is hosted by the live chat provider, outside the Moveworks API. The app accepts onlyhttpsURLs, loads the image with no referrer, and drops it if it fails to load. - End a live chat with the agent message's action. The action that ends the chat is the
CALLBACK_ACTIONon aLIVE_AGENTmessage. Identify it by type and actor, since its label can vary and itscallback_idis opaque. - Detect the end of a live chat from the messages. The API has no session resource. A
LIVE_AGENTmessage without the end-chat action, after earlier ones that carried it, means the agent ended the chat. When the user ends it, the response to the end-chat action completes with no output; see "Re-read history after an empty response" below. - Open user-consent links in a new tab. When a plugin's connector needs per-user authorization, the assistant sends a
URL_ACTIONwhoseurl_action.purposeisUSER_CONSENT_AUTH. Whenpurposeis absent, the link is unclassified and can still be a consent link, sois_auth_linkalso flags anhttps://{org}.moveworks.com/connections?...URL. Treat an unknownpurposevalue as unclassified. After the user consents, the original request resumes automatically. Listen on the events endpoint or webhook for the resumed message in the same conversation, and do not resend the request. - Disable a message's other actions once one is taken. This keeps a user from pressing a second action after answering.
- Merge follow-up events into the open thread. A response can complete before the work it started does, such as filing a ticket. The follow-up message arrives later as an event on the same conversation, through the events API or a webhook.
- Route events by
category. An event'scategorysays where it came from, such asUSER_CONSENT_AUTHorLIVE_AGENT. The library reads it asEvent.categoryand, for a webhook'sdata.category,WebhookEnvelope.category. Treat an absent or unrecognized value as an ordinary assistant message. On aUSER_CONSENT_AUTHevent,consent_operation_typeisAUTHORIZEwhen consent completed, orREVOKEwhen a connection was removed, and is absent on the message that asks the user to consent. The confirmation and every resumed request carryAUTHORIZE, so one consent can produce severalAUTHORIZEevents; treat the first as completion. ALIVE_AGENTevent whoselive_agent_session_stateisENDEDmarks the end of a live agent session, with or without a message, so checkhas_messagebefore reading message fields. Treat an unrecognized state as no change. - Convert message text to Markdown in one place. Message text, labels, citation titles, and notification text can contain Slack-style links (
<https://url|label>,<host|label>) and:emoji_name:shortcodes, and modalDISPLAYfields can contain HTML.moveworks_capi.renderingconverts these to CommonMark (normalize_markup,clean_label,citation_label,modal_html_to_markdown). - Remove form text your client renders itself. When the assistant offers catalog forms, the message text can end with a plain-text copy of each form's citation.
rendering.strip_flattened_formsremoves it, andrendering.layout_messagealso reports wherecontent_referencesplaces the forms. - Name buttons that share a label. Several form actions can carry the label "Complete this request". For a
MODAL_ACTION, the form's name is the modal's firstDISPLAYfield withstyle: HEADER. For aURL_ACTION, the link redirects to the form's portal URL, which matches a citation'surl;rendering.form_link_citationspairs them. Pair by URL, not by position. - Show a
CHOICEfield'sprefill. ACHOICEfield can have nooptionsand a server-resolvedprefill, such as the requesting user. - Treat modal ids as single-use. Re-read the message for a fresh id rather than reusing one.
- Re-read history after an empty response. Some replies, such as the farewell after "Exit Live Chat", are written to history under an earlier response. When a response completes with no outputs, re-read recent history and use
conversations.replies_after_inputto find them. - Conversation titles come with the list.
ListConversationsreturns eachtitle, so a conversation list renders from one request. Without a title, the API assigns one generated from the first response; set one at creation or withPATCHto control the label. - Serialize reads.
ListConversations, history reads, and/eventspolls all count against the same rate limit. Read one at a time and poll at a conservative interval. - Back off on 429. The shared client backs off with jitter, with or without a
Retry-Afterheader. For batch work, follow the concurrency guidance in the overview's practical considerations, test in a small batch first, and ask your Moveworks account team about your limits before sizing a rollout. - Decide what the first poll does. Polling
/eventswithoutstarting_afterreturns events from the user's history.PollingLooptakes afirst_runpolicy. The default,"skip_history", sets the checkpoint to the newest event and dispatches nothing;"replay_history"dispatches the history, oldest first. - Poll
-for new events.EventsPollingClient(client, conversation_id=...)lists one conversation's events, andnotifications.get_eventfetches one event by id with its real conversation id. Listing one conversation is eventually consistent, so poll-for new events, as the List events reference describes. - Branch on error fields. Every API error carries
status_code, the body'serror.code, andtrace_id. A 401 raisesAuthenticationError, a 429 raisesRateLimitedError, and other 4xx responses raiseRequestRejectedError, including an upload over the size limit (413) or one whose content failed validation (422).extract_texton aFAILEDresponse raisesResponseFailedError. A mid-streamERRORevent raisesStreamError. A stream that closes before its terminal event raisesStreamClosedErrorwith theresponse_id, so you can finish withwait_for_completion. A stream'stimeout_secondsis an idle timeout per read. - Never resend a turn. The client retries a 429 on every method, and a 5xx or network error only on
GET,HEAD, andPATCH.create_response, streaming, andupload_fileare not retried after a timeout or 5xx, because the server may already have accepted the turn or the file. After a 401, the S2S and OIDC providers fetch a new bearer and the client retries once; an API Key 401 raises immediately.max_retries(default 3) caps retries, and0turns them off. - Check the Bot Name first if every call fails.
MW_BOT_NAMEmust match the Bot Name of the chatbot in Moveworks Setup.check_setup.pychecks for this.
pip install -e ".[app,test]"
python -m pytestThe suite runs offline, using synthetic keys, mocked endpoints, and recorded message fixtures. It covers:
- The HTTP client: headers, retries, and backoff
- The S2S JWT and OIDC (PKCE) auth providers
- Conversations, responses, streaming, and file upload
- Event polling and the checkpoint
- Webhook signature verification
- The rendering helpers
- The reference app's server
- The MCP server: the auth gate, sign-in modes, the demo OAuth server, forms, and tool behavior
- The voice example: speech prep, tuning, the Realtime session and client secret, the orchestrator turns, and the server
This repo is versioned 0.x, and breaking changes can land in minor versions. CHANGELOG.md records each release. To depend on the library, pin a tag.
See SUPPORT.md. Questions about your Moveworks instance's Conversations API setup go to your Moveworks account team or [email protected]. Bugs in this code go to a GitHub issue on this repo. Report security issues as described in SECURITY.md.
MIT. This repository is sample code, provided as-is. It is not a supported Moveworks product and carries no SLA. Verify against the Conversations API documentation before using it in production.