Getting Started

REST API Integration

Chat API reference: request and response fields, file uploads, conversation history, streaming, and errors.

Overview

Use the Chat API to send messages and read conversation history. Each API channel key selects an agent and grants access to that channel's conversations.

For the public API, see API overview. Conversation export uses a platform API key and covers customer conversations across channels. Health is public and needs no key. The channel-key instructions below apply to the Chat API endpoints in this guide.

Base URL
https://api.mu.chat/v2

Your active plan must include API access, and the agent's API channel must be active.

Quick Start

In the dashboard, select your agent, open Deploy → API → Setup (or Manage), and create or copy its API key.

Create an API channel key in the MuChat dashboard

Keep the key on your server. Organization API keys and the widget's websiteToken do not authenticate these endpoints.

Environment variable
export MUCHAT_API_KEY='YOUR_API_CHANNEL_KEY'
cURL
curl --request POST 'https://api.mu.chat/v2/chat' \
  --header "Authorization: Bearer $MUCHAT_API_KEY" \
  --header 'Content-Type: application/json' \
  --data '{
    "query": "Hello! How can you help me?",
    "external_message_id": "message-001",
    "stream": false
  }'

For the next message, include the returned data.metadata.conversation_id and a new external_message_id. Wait for the previous request to finish; history is stored automatically.

HeaderValue
AuthorizationRequired: Bearer YOUR_API_CHANNEL_KEY.
Content-Typeapplication/json for chat; let your client set multipart headers for uploads.
Last-Event-IDOptional: last received SSE id, when resuming the same request.

Key API Endpoints

MethodPathPurpose
POST/v2/chatSend a message; receive JSON or SSE.
POST/v2/chat/uploadsUpload a file.
GET/v2/chat/conversationsList conversations.
GET/v2/chat/conversations/{conversation_id}Read a conversation's current state.
GET/v2/chat/conversations/{conversation_id}/messagesRead public messages.

Send a Message: Request Fields

Send a JSON body to POST /v2/chat. Fields are optional unless marked required. Extra fields are rejected.

FieldData typeDefaultPurpose
queryText""The user's message. Without a file, text is required and cannot contain only spaces.
attachmentsList of file objects[]Uploaded files in display order. Send up to 5 files with different IDs.
attachments[].blob_idPositive integerNone; requiredThe ID you received when uploading the file.
conversation_idText (UUID)nullSend the ID from the previous response to continue that conversation. Leave it out to start a new one.
external_message_idTextnullYour system's message ID. It must be unique within the channel, nonblank, and at most 255 characters. The server creates one if you leave it out.
contactJSON objectnullUser details, such as name and email. Leave it out to keep the current conversation's contact.
system_promptTextnullInstructions for this message. If omitted or blank, the channel's instructions apply, falling back to the agent's instructions.
knowledge_base_idsList of IDsnullKnowledge bases to search for this reply. Select up to 100 active bases assigned to the agent. Leave it out to use all, or send [] to disable search.
streamtrue or falsefalseWith true, receive the reply as it is generated. With false, receive the complete reply at once.

For fields with a null default, sending null has the same effect as leaving the field out.

system_prompt and knowledge_base_ids apply only to this request; saved agent settings stay unchanged.

Contact Fields

All contact fields are optional. Leave a field out to keep its current value. Send null to clear a text field, except identifier. Leading and trailing spaces are removed, and blank text is treated as null. Verified information or operator edits may be protected from API changes.

FieldData typeLimitPurpose
contact.identifierTextUp to 255 charactersThe signed-in user's stable ID in your system, such as "customer-42". It cannot change during a conversation.
contact.nameTextUp to 255 charactersThe name displayed for the user.
contact.first_nameTextUp to 255 charactersGiven name.
contact.last_nameTextUp to 255 charactersFamily name.
contact.emailTextValid emailThe user's email address. Stored in lowercase.
contact.phone_numberTextUp to 64 charactersA valid phone number, stored in E.164 format. Numbers without a country code are treated as Iranian.
contact.localeTextUp to 32 charactersProfile language, such as "fa". This does not set the reply language.
contact.custom_attributesJSON object—Extra data, such as {"plan":"premium"}. Only supplied keys change. Send null for a key to clear its value. Defaults to {}.

contact.identifier identifies the same user. To continue the same conversation, send conversation_id.

Retries: send the same request with the same external_message_id. Only stream may change. If you left out conversation_id the first time, leave it out again. The server returns the original result, even if it failed. It does not create another message or generate a new reply.

Send a Message: Response Fields

JSON success returns 200 with data.message and data.metadata. The paths below are inside data.

FieldData typeMeaning
messageJSON object or nullReply, or null when no AI reply was generated.
message.idText (UUID)MuChat's reply message ID.
message.roleTextassistant for the AI; history also includes user and operator.
message.partsList of objectsText and files in display order.
metadata.conversation_idText (UUID)Conversation ID for subsequent messages.
metadata.user_message_idText (UUID)MuChat's ID for the incoming message.
metadata.external_message_idTextYour supplied message ID, or the generated one.
metadata.contact_idText (UUID)MuChat's contact ID; distinct from your contact.identifier.
metadata.finish_reasonTextcompleted: finished; suppressed: no AI reply; failed: failed; cancelled: interrupted.
metadata.conversation_statusTextopen: active; pending: awaiting handling; snoozed: postponed; resolved: closed.
metadata.bot_activetrue or falseWhether the bot is enabled for this conversation.
metadata.handoff_statusTextnot_requested: no handoff; pending: awaiting an operator; operator_owned: assigned.
metadata.usage.creditsIntegerCredits used by this reply. Reports 0 if no reply is generated or generation fails.

If generation fails or is cancelled, the JSON response returns 503 with the result in data. A retry returns information from when the original request ended. Fetch conversation details for the current state.

Message Parts

Each text part has:

FieldData typeMeaning
idText (UUID)Content-part ID.
typeText"text".
textTextText to display.

Upload Files

Send the file in the file field using multipart/form-data. A successful 201 response returns the file ID in blob_id.

Upload a file
curl 'https://api.mu.chat/v2/chat/uploads' \
  --header "Authorization: Bearer $MUCHAT_API_KEY" \
  --form 'file=@./screenshot.png;type=image/png'

If the response is {"blob_id":187}, send it in a chat request:

request-with-attachment.json
{
  "query": "What is shown in this image?",
  "external_message_id": "message-002",
  "attachments": [{ "blob_id": 187 }]
}
  • Attach the upload within 24 hours, in the same channel, to one new message. Retries of that message can reuse it.
  • Maximum 5 files per message. Upload limit: 30 per 15 minutes; size depends on the plan and server cap (default 100 MiB).
  • Supported vision models read static images. PDFs and other files are stored without reading their contents; audio uploads are not transcribed.

Chat API Streaming

Send stream: true to receive the reply as it is generated, using text/event-stream. The event name is in event, and its JSON is in data. The data.type matches the event name. Save received id values to resume after a disconnect. Ignore heartbeat comments.

EventFields and purpose
CUSTOMConfirms the message was received. name is "muchat.api.message.accepted.v1", and value contains the message's IDs.
RUN_STARTEDGeneration has started. threadId identifies the thread, and runId identifies this generation.
TEXT_MESSAGE_STARTReply text is starting. messageId identifies the message, and role is assistant. When present, partId identifies the text part, and position gives its order.
TEXT_MESSAGE_CONTENTNew text is in delta. Add it to messageId's text, using partId to choose the part when present.
TEXT_MESSAGE_ENDText for this messageId has ended, or for its partId when present.
RUN_ERRORcode identifies the error; message explains it.
RUN_FINISHEDThe reply has ended. threadId and runId identify the thread and generation. Use the final response in result for display.

The value contains conversation_id, user_message_id, external_message_id, contact_id, and run_id. All are UUIDs except your external_message_id. The run_id can be null. In that case, the final event's runId is user_message_id. Use conversation_id for the next message.

After a disconnect, retry the same request with the last SSE id in the Last-Event-ID header. Text chunks may not be sent again, so use the final result. Without that result, the response is incomplete. A stream failure may return result.status as "failed" and the message's IDs in result.metadata, without result.data.

Conversation History

GET /v2/chat/conversations returns data[], newest activity first. GET /v2/chat/conversations/{conversation_id} returns one data object with the same fields. conversation_id is a required UUID in the path.

Conversation fieldData typeMeaning
idText (UUID)Conversation ID.
contact_idText (UUID)MuChat's contact ID.
contact_identifierText or nullYour user's identifier.
created_atDate and timeCreation time, in ISO 8601 format.
last_activity_atDate and timeMost recent activity.
conversation_statusTextCurrent status, as defined in the chat response.
bot_activetrue or falseWhether the bot is currently enabled.
handoff_statusTextCurrent operator handoff state.

GET /v2/chat/conversations/{conversation_id}/messages returns public messages in data[], oldest to newest within each page. Messages use id, role, and parts from the response reference, plus ISO 8601 created_at. Private notes and unfinished replies are excluded.

Query parameterApplies toPurpose
contact_identifierConversationsSend the user's contact.identifier to get their conversations.
cursorConversationsSend pagination.next_cursor from the previous response to get the next page.
beforeMessagesSend before_cursor to get older messages.
afterMessagesSend after_cursor to get newer messages. Do not combine with before.
limitBothNumber of results per page, from 1–100. Defaults to 50.

These parameters are optional. Without before or after, you get the latest messages. Use pagination values only with the same channel, conversation, and filters. Your server must give each user access only to their own history.

pagination fieldData typeMeaning
has_moretrue or falseIf true, more results are available in the selected direction.
next_cursorText or nullValue for the next page. Send it in the same cursor, before, or after parameter. The default direction for messages is before.
before_cursorText or nullSend in before to get messages older than this page. Only included in message lists.
after_cursorText or nullSend in after to get messages newer than this page. Only included in message lists. Keep your previous value when a page is empty.

Error Handling

HTTP errors use application/problem+json:

error.json
{
  "type": "about:blank",
  "title": "Invalid API Key",
  "status": 401,
  "detail": "The provided API key is invalid or expired.",
  "instance": "/v2/chat",
  "code": "INVALID_API_KEY",
  "trace_id": "f6a7b8c9-d0e1-4f2a-8b3c-4d5e6f7a8b9c"
}
FieldData typeMeaning
typeTextProblem type; currently about:blank.
titleTextShort error title.
statusIntegerHTTP status code.
detailTextError explanation.
instanceTextRequest path.
codeTextError identifier for program logic.
trace_idTextSupport tracing ID; also in X-Request-ID.
dataJSON object (optional)Saved message and metadata for generation failures.
errorsList of objects (optional)Field errors for VALIDATION_ERROR.
errors[].locListInvalid field's location, e.g. ["body","contact","email"].
errors[].msgTextWhat is wrong with the field.
errors[].typeTextThe kind of problem with the field.
HTTP / codeAction
401 INVALID_API_KEYCheck the API channel key.
403 API_CHANNEL_INACTIVE / API_ACCESS_NOT_AVAILABLECheck channel activation and plan access.
403 API_CONTACT_UNAVAILABLECheck whether the contact is blocked.
403 CHAT_FILE_ACCESS_DENIEDUse an unused upload from this channel.
404 CONVERSATION_NOT_FOUNDCheck the conversation ID and channel.
409 API_MESSAGE_CONFLICTRetry the original body, or use a new message ID.
409 API_CONVERSATION_BUSY / API_CONVERSATION_CLOSEDWait for the reply, or start a new conversation.
409 API_CONTACT_MISMATCHKeep the conversation's original identity.
409 CHAT_UPLOAD_NOT_READY / 410 CHAT_UPLOAD_EXPIREDComplete or repeat the upload.
413 CHAT_FILE_TOO_LARGEReduce file size.
422 VALIDATION_ERROR / API_CURSOR_INVALIDCheck fields, UUIDs, and cursors.
422 API_KNOWLEDGE_UNAVAILABLEUse active knowledge assigned to this agent.
422 CHAT_FILE_INVALID / CHAT_MEDIA_PROCESSING_FAILEDCheck the file; retry processing if needed.
422 CHAT_ATTACHMENT_LIMIT_EXCEEDEDSend at most 5 files.
429 MESSAGE_RATE_LIMIT_EXCEEDEDWait for Retry-After when present; otherwise retry with a delay.
503 API_GENERATION_FAILEDRead data.metadata.finish_reason; partial text may exist.

For SSE, check RUN_ERROR and the final result: failed, cancelled, or missing result.data means failure even after HTTP 200.

MuChat documentation

On this page