Agent code
An agent's custom tools and hooks can reach Minded from code, with the Minded SDK: start a chat or send to one, read it, start another agent's run, and read usage.
Your code acts as the run
- Code reaches Minded as the run it belongs to. The run acts as the member whose prompt it answers, with that member's role, never more.
- There is no key in code and nothing to sign in. Never paste an API key into an agent's code.
- The actions are the ones outside agents call with a key, with the same names, inputs and rules (Prompts and replies).
- A run's token works only while its turn runs. Once the turn ends or someone presses Stop, its calls are refused.
The run's environment holds what the code needs:
| Variable | What it holds |
|---|---|
MINDED_API_URL | Where the code calls Minded. The Minded SDK's routes are under /v1 there |
MINDED_RUN_TOKEN | The run's token. Send it as Authorization: Bearer |
MINDED_CHAT_ID | The run's own chat |
| Action | Route | What it does |
|---|---|---|
chats.start | POST /v1/chats | Starts a chat, the prompt its first message |
chats.send | POST /v1/chats/{chatId}/messages | Sends a prompt in the run's own chat or a chat it started |
chats.read | GET /v1/chats/{chatId}/frames | Reads that chat after afterSeq, waiting up to waitSeconds |
chats.stream | GET /v1/chats/{chatId}/stream | The chat's frames as they land, as server-sent events |
agents.run | POST /v1/agents/{agent}/runs | Starts a run of an agent, by its id, in a chat of its own |
usage.read | GET /v1/usage | Usage left and spend. Leave out chatId for the run's own chat |
A prompt the code sends shows in that chat with the run's chat as its source.
Start a chat and read its reply
// Custom tool: hand a summary to a chat of its own, and return the reply.
const base = `${process.env.MINDED_API_URL}/v1`;
const headers = { Authorization: `Bearer ${process.env.MINDED_RUN_TOKEN}`, 'Content-Type': 'application/json' };
export default async function summarize({ tickets }) {
const started = await fetch(`${base}/chats`, {
method: 'POST',
headers,
body: JSON.stringify({ text: `Summarize these tickets: ${tickets.join(', ')}`, clientId: crypto.randomUUID() }),
});
if (!started.ok) return (await started.json()).message;
const { chatId } = await started.json();
const words = [];
let afterSeq = 0;
for (;;) {
const read = await (await fetch(`${base}/chats/${chatId}/frames?afterSeq=${afterSeq}&waitSeconds=50`, { headers })).json();
for (const frame of read.frames) if (frame.type === 'item' && frame.role !== 'user' && frame.text) words.push(frame.text);
afterSeq = read.lastSeq;
if (read.status !== 'working') return words.join('\n');
}
}Start another agent's run
agents.run starts the agent's run in a chat of its own and returns its chatId. Read the run's chat as above. Only agent code starts runs: starting runs with an API key comes later.
- They spend like any run. Each run spends usage, like any chat.
- A run asks as often as yours. A chat your code starts or sends to asks for approval at least as often as the run's own chat.
Hooks
A hook is code that runs at a named moment of an agent's run. hooks.json, beside AGENT.md, names each hook; its code is a file under hooks/. Both are files of the agent, so History keeps every version, and a Builder or an Admin changes them; a User reads them.
{ "hooks": [
{ "event": "SessionStart", "name": "Skip runs with no payout", "file": "hooks/payout.py" },
{ "event": "PreToolUse", "matcher": "send_email", "file": "hooks/outside_email.py" }
] }event: when it runs (the table below).matcher: optional. A tool's name before or after a tool call and at an approval, a trigger's id before a run, or a Minded SDK action's name (chats.send,agents.run) around one. Names joined by|, with*for any run of characters. Left out, it matches every one.name: optional. What people read in the agent's Hooks list; left out, the event's words.file:hooks/<name>. A.pyfile runs withpython3,.jsand.mjswithnode,.shwithbash.
| Event | When | What its answer does |
|---|---|---|
SessionStart | Before a run (Preflight) | continue: false skips the run with reason; additionalContext is added to the run's first prompt |
UserPromptSubmit | A prompt arrives | additionalContext is added; continue: false ends the turn with no model call |
PreToolUse | Before a tool call | permissionDecision allow, deny or ask, with permissionDecisionReason; updatedInput changes the call's input |
PermissionRequest | Minded asks for approval | deny refuses the call |
PostToolUse | After a tool call, a failed one too | updatedToolOutput changes what Minded reads; additionalContext is added |
Stop | A turn ends | decision: "block" keeps the turn going, 8 times in a row at most |
StopFailure | A turn fails | Nothing: it runs after the fact. Its event holds error and chat_url, the chat's link in Minded |
SubagentStart | A subagent starts | additionalContext is added |
SubagentStop | A subagent finishes | decision: "block" keeps the subagent going, 8 times in a row at most |
RunEnd | The run's status is set | Nothing: it reads status and reason after the fact |
TaskStatus | A task's status changes | Nothing: it runs after the fact. matcher names the task's agent |
PreSdkAction | Before a Minded SDK action (below) | permissionDecision deny refuses the action, with permissionDecisionReason |
PostSdkAction | After a Minded SDK action | Nothing: it runs after the fact |
The event arrives as JSON on the hook's standard input, with hook_event_name and what the moment holds (before a run: prompt and run; around a tool call: tool_name and tool_input). The hook answers by printing JSON and ending with exit code 0. Printing nothing lets the action go on.
# hooks/payout.py, before a run: a run with no payout is skipped.
import json, sys
event = json.load(sys.stdin)
if "payout" not in event["prompt"]:
print(json.dumps({"continue": False, "reason": "No payout in this event"}))A hook of the agent's own that runs inside a turn calls a connected integration as the agent: it posts the call to /mcp at the address in MINDED_API_URL, with MINDED_RUN_TOKEN as its bearer token. The call meets the same permissions as the agent's own call and opens no approval card: one that would ask a person does not run, and its answer says so.
# hooks/zendesk_ticket.py, when a turn fails: opens a Zendesk ticket with the error and the chat's link.
import json, os, sys, urllib.request
event = json.load(sys.stdin)
call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "zendesk__create_ticket", "arguments": {
"subject": "Minded's turn failed: " + str(event.get("error")),
"body": "The chat: " + str(event.get("chat_url")),
}}}
request = urllib.request.Request(os.environ["MINDED_API_URL"] + "/mcp", data=json.dumps(call).encode(), headers={
"Authorization": "Bearer " + os.environ["MINDED_RUN_TOKEN"],
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
})
urllib.request.urlopen(request, timeout=8).read()- Exit code 2 denies, skips or blocks, with what the hook wrote to standard error as the reason.
- Any other exit code, an answer Minded cannot read, or more than 10 seconds: the hook failed. A run starts all the same; a tool call the hook guards does not run on its own. A Minded SDK action the hook guards is refused. Minded reads that the hook failed and decides how to carry on. The trace's hook step reads failed, and Monitoring counts it.
When a call is refused
A refused call answers with an HTTP status and a JSON body with code and message that name what refused it (Errors). Your run carries on, and Minded decides what to do next.