Developers

The Merlin API

Run your workspace's agents from your own systems: start a run and wait for the answer or stream every step, continue conversations, send files, approve what an agent asks to do, and hear back by webhook.

Getting started

  1. In Merlin, open Settings → Developers and create an API client for the system that will call Merlin. Each client has its own keys, the agents it may run, what it may do (its scopes) and a monthly spending limit.
  2. In the Builder, switch on Available through the API for each agent the client should reach. It is off by default.
  3. Copy a key and your API address from the same page. The examples below use them as $MERLIN_KEY and $MERLIN_API.
A key acts as its client's own service account, in the client's workspace. Runs, conversations and files it creates belong to that account, and a conversation can only be continued by the client that started it.

Authentication

Send the key as a bearer token on every request. Keys start with nx_live_. The API answers any origin and uses no cookies, so it can be called from a server or a browser.

curl "$MERLIN_API/agents" -H "Authorization: Bearer $MERLIN_KEY"

Scopes

ScopeAllows
agents:readListing the agents the client can reach
agents:runRunning them
conversations:readReading conversations and their messages
files:read, files:writeDownloading and uploading files
approvals:writeApproving or rejecting what an agent asks to do
webhooks:manageAdding, testing and removing webhook endpoints
usage:readReading what the client's runs cost

Run an agent

List the agents your client can reach, then start a run with the message for the agent.

curl -X POST "$MERLIN_API/agents/$AGENT_ID/runs" \
  -H "Authorization: Bearer $MERLIN_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1042-summary" \
  -d '{
    "input": "Summarise yesterday’s orders",
    "mode": "wait",
    "wait_seconds": 30,
    "end_user": "customer-381",
    "metadata": {"source": "crm"}
  }'
FieldWhat it is
inputThe message for the agent. Required.
modewait (the default), detached or stream.
wait_secondsHow long wait waits for the run to finish, up to 60.
conversation_idContinue a conversation this client started with this agent.
file_idsFiles uploaded with POST /files.
end_userYour own id for the person the run is for. Conversations and usage can be filtered by it.
metadataAnything you want kept with the run; it is given back as it is.
client_timezoneThe person's IANA time zone, such as Europe/London.

Modes

  • wait answers 200 with the finished run, or 202 if it is still going after wait_seconds.
  • detached answers 202 at once.
  • stream answers with server-sent events as the run happens (see Streaming).

A 202 carries a Location header with the run's address. Read it with GET /runs/{id}: it gives the status, and once the run has finished, the answer as output.text and any files the agent made as output.files. While it is running, the answer carries Retry-After: 2. Waiting or detaching never cancels a run; POST /runs/{id}/cancel stops one.

The same Idempotency-Key sent twice starts one run. Reusing a key for a different request answers 409 idempotency_conflict.

To make the first answer faster, call POST /agents/{id}/prepare while the person is still typing.

Streaming

With "mode": "stream", or later with GET /runs/{id}/events, the run arrives as server-sent events. Each event has its type and a sequence number as its id; send Last-Event-ID (or ?after=) to resume where you left off.

event: message.delta
id: 12
data: {"type": "message.delta", "sequence": 12, …}
EventWhen
run.startedThe run has started, with its run and conversation ids.
message.deltaThe next piece of the answer's text.
message.resetA step is being retried: drop the answer's text after the given sequence.
tool.started, tool.completed, tool.progressThe agent's steps, with a label you can show.
approval.requiredThe agent is waiting for an approval (see Approvals).
artifact.created, artifact.updatedA file the agent made, with its download address.
element.shown, card.shownAn interactive element or a card the agent showed.
memory.saved, memory.recalledThe agent remembered something, or used what it remembered.
run.statusThe run is retrying or tidying its context.
run.completed, run.failed, run.cancelledHow the run ended; a failure carries a code, a message and whether it can be retried.

Long steps send : keepalive comments so the connection stays open. The model's own reasoning is never sent.

Conversations

Every run belongs to a conversation. Pass its conversation_id on the next run to continue it.

  • GET /conversations?end_user=&agent_id=&limit=&offset=: the client's conversations.
  • GET /conversations/{id} and GET /conversations/{id}/messages: one conversation and its turns, each answer with its steps.
  • PATCH /conversations/{id} with {"title": …} renames it; DELETE deletes it.
  • POST /conversations/{id}/cancel stops every unfinished run in it.

Files

Upload a file (multipart, field file, up to 50 MB), then pass its id on a run.

curl -X POST "$MERLIN_API/files" \
  -H "Authorization: Bearer $MERLIN_KEY" \
  -F "file=@invoices-october.pdf"
# → {"id": "…"}, then "file_ids": ["…"] on the run

Files an agent makes come back in output.files and in artifact.created events, each with a download_url you fetch with your key.

Approvals

Anything an agent is set to ask about first waits for a decision: the run ends with status requires_approval and the stream sends approval.required. Read what it wants to do, then approve or reject it.

curl "$MERLIN_API/runs/$RUN_ID/approval" -H "Authorization: Bearer $MERLIN_KEY"

curl -X POST "$MERLIN_API/runs/$RUN_ID/approval" \
  -H "Authorization: Bearer $MERLIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"decision": "approve", "mode": "wait"}'

The decision continues the conversation as a new run, answered in the mode you ask for. A rejection can carry a message for the agent. Send the interrupt_id you were shown to be refused with 409 if the pending decision has changed.

Webhooks

Hear that a run ended without polling. Add an endpoint with the events it wants: run.completed, run.requires_approval, run.failed and run.cancelled. The answer carries the endpoint's signing secret, shown only then. A client can have up to 10 endpoints.

curl -X POST "$MERLIN_API/webhooks" \
  -H "Authorization: Bearer $MERLIN_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://example.com/merlin", "events": ["run.completed", "run.requires_approval"]}'

An event says which run ended and how, but never carries the answer: read that with your key, so nothing a run produced is pushed to an address. Each run is announced once per endpoint. POST /webhooks/{id}/test sends a signed ping, and GET /webhooks/{id}/deliveries shows the delivery log.

Checking the signature

Every request carries NextAI-Signature: t=<unix seconds>,v1=<hex>: the HMAC-SHA256 of "<t>.<raw body>" with your endpoint's secret. Recompute it and refuse a timestamp more than five minutes old.

import crypto from 'node:crypto';

export function verify(rawBody, header, secret) {
  const f = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  if (Math.abs(Date.now() / 1000 - Number(f.t)) > 300) return false;
  const mac = crypto.createHmac('sha256', secret).update(`${f.t}.${rawBody}`).digest('hex');
  return f.v1?.length === mac.length && crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(f.v1));
}

Usage

GET /usage?from=&to=&group_by= gives what the client's runs cost: runs, US dollars and tokens, this month by default. Group by agent, end_user or day.

OpenAI libraries

Any OpenAI library can call an agent: point it at $MERLIN_API/openai with your key, and name the agent as the model.

from openai import OpenAI

client = OpenAI(base_url=f"{MERLIN_API}/openai", api_key=MERLIN_KEY)
reply = client.chat.completions.create(
    model=f"agent:{AGENT_ID}",
    messages=[{"role": "user", "content": "Which region grew fastest this month?"}],
)
print(reply.choices[0].message.content)

Pass stream=True to receive the answer as it is written. GET /openai/models lists the agents as models.

ChatGPT and Claude

Merlin is also an MCP server, so ChatGPT, Claude and other MCP clients can use your workspace's agents. Add Merlin's MCP address as a connector; the person signs in to Merlin and agrees to what the app may do, and the app then works with the agents that person can use, under the same scopes as a key. The MCP address is shown with your API address in Settings → Developers.

Errors

Every error has one shape, with a Retry-After header when it is worth trying again later:

{"error": {"code": "conversation_busy", "message": "…", "retry_after": 5}}
Status and codeMeaning
403 insufficient_scopeThe key's client lacks the scope the request needs.
404 agent_not_found, 404 run_not_foundNot there, or not reachable by this client.
409 conversation_busyThe conversation already has a run going.
409 conversation_agent_mismatchThe conversation belongs to another agent.
409 idempotency_conflictThe idempotency key was used for a different request.
429 over_capacity, 429 usage_cap_exceededToo busy right now, or the client's monthly limit is reached.
503 circuit_openTemporarily unavailable; try again after retry_after.

Reference

Paths are relative to your API address. The full OpenAPI document is at $MERLIN_API/openapi.json.

Method and pathWhat it does
GET /agentsThe agents the client can reach
GET /agents/{id}One agent
POST /agents/{id}/prepareWarm the agent before a run
POST /agents/{id}/runsRun the agent
GET /runs/{id}A run's status and answer
GET /runs/{id}/eventsA run's events, stored then live
POST /runs/{id}/cancelStop a run
GET · POST /runs/{id}/approvalWhat a run waits on, and the decision
GET /conversationsThe client's conversations
GET · PATCH · DELETE /conversations/{id}One conversation: read, rename, delete
GET /conversations/{id}/messagesIts turns
POST /conversations/{id}/cancelStop its unfinished runs
GET · POST /conversations/{id}/approvalWhat it waits on, and the decision
POST /filesUpload a file
GET /files/{id}/contentAn uploaded file
GET /artifacts/{id}/versions/{v}/contentA file an agent made
GET · POST /webhooksList and add webhook endpoints
DELETE /webhooks/{id}Remove one
POST /webhooks/{id}/testSend a signed ping
GET /webhooks/{id}/deliveriesThe delivery log
GET /usageWhat the client's runs cost
GET /openai/modelsThe agents, as models
POST /openai/chat/completionsCall an agent with any OpenAI library