Skip to main content
The first parameter of every hook is ctx. Everything an extension can do goes through it: save data, call the plugin’s MCP tools, show toasts, fill text into the message box, call a model, start a background subagent, add slash commands, set a theme, and read session info. This page walks through each part of ctx by task, with an example in each section.For timers, use ctx.clock. To reach files or the network, go through the plugin’s MCP tools. See Call MCP tools.Most examples on this page draw on the status band. The status band is the strip above the message box, inside its border. All plugins share one band, and each draws a line or two in it. Its site name in code is above-prompt. A panel is a tab in the conversation’s side panel on the right, next to tabs such as Files and Browser. Its site name in code is pane. See Interface.
The type files are the source of truth for method signatures. If .minimax-plugin/types/ in your development folder disagrees with this page, trust the type files.

Rules for using ctx

  • Only hooks receive ctx. Callbacks for buttons, inputs, timers, and ctx.store.onDidChange use the ctx of the enclosing hook. See Register hooks.
  • Write it out in full. Write ctx.state.set(…) and ctx.mcp.call('notes', 'sync'). Don’t destructure or alias it, and don’t pass ctx to another function, or you get EXTENSION_CALL_SHAPE_INVALID.
  • Identity follows the call. Each ctx call takes its identity and permissions from the Invocation that is running right now. A button callback uses the ctx from the drawing, but it runs as a “button action”, not as a “drawing”.
  • No use after an Invocation ends. Calling ctx at the top level of the module, or from leftover async code after an Invocation has ended, throws INVOCATION_SETTLED. The same goes for calls such as ctx.command.register and ctx.theme.set. await every operation you need.

Where calls: comes from

Preview and test scan the whole module statically and record every fully written ctx.<group>.<method>(…). The result is the extension’s calls: list. ctx.mcp.call is recorded separately for each server name, and ctx.command.register, ctx.command.list, ctx.theme.set, and ctx.theme.clear are recorded the same way. You don’t write calls: by hand. Ask the Agent to run inspect and you can see it in the source section.At run time, only the methods and MCP servers in calls: are allowed. Any other call reports CALL_NOT_DECLARED. So when the docs say a call “must be declared in calls:”, they mean you write that call out in full somewhere in the module.

Save state

Extensions have two ways to save data:As a rule of thumb, put data that you show in the interface and that only concerns the current session in ctx.state. Put data that must survive across sessions and restarts in ctx.store.

ctx.state

First declare the keys and their defaults with defineState in hooks/state.ts, then re-export state from the module:
hooks/state.ts
hooks/register.tsx
  • The argument to defineState must be an object literal, or you get EXTENSION_STATE_SHAPE_INVALID. You can have up to 256 keys. Key names use letters, digits, and _ $ . -, up to 128 characters.
  • ctx.state.get(key) returns the value synchronously.
  • await ctx.state.set(key, value) writes a new value.
  • await ctx.state.update(key, (value) => newValue) computes a new value from the current one.
  • A written value must be the same JSON type as the default (if the default is a number, you can only write numbers), or you get ARGUMENT_INVALID. If the default is null, you can write any JSON. For arrays and objects, only the type is checked, not what’s inside.
  • A single value can’t exceed 64 KB once serialized, and this plugin’s state in one session can’t exceed 1 MB in total. Going over also reports ARGUMENT_INVALID.
  • Write only keys declared in defineState. Writing any other key throws EXTENSION_SERVICE_FAILED.
  • Drawings can’t write ctx.state. The static scan reports EXTENSION_RENDER_SIDE_EFFECT, and at run time you get STATE_WRITE_IN_RENDER.
  • When you change defineState and reload, removed keys are dropped. Keys whose type changed go back to their default, and MCode records an EXTENSION_STATE_SHAPE_INVALID diagnostic.

ctx.store

ctx.store is a key-value store. Values can be any JSON:Keys must match ^[A-Za-z0-9._-]{1,128}$ and can’t be . or ... A single value can be up to 256 KB, and each plugin can store up to 8 MB in total. An invalid key or a value over a limit makes the call throw EXTENSION_SERVICE_FAILED, with the reason in message.Data is written to a file on this machine. It survives a Runtime restart, and withdrawing a preview doesn’t delete it.An extension in preview can read the installed version’s data, but its writes go only to a preview copy for this session and don’t change the installed version’s data. onDidChange receives only the writes the listener can see. Writes to the preview copy notify only the preview in the same session. Writes to installed data notify all sessions, except previews that have already changed the same key.After writing ctx.store, call ctx.ui.invalidate() to redraw.

Example: turns this session and in total

hooks/register.tsx
hooks/state.ts is the one above that declares turns.

Call MCP tools

Which server is used

server is looked up in this order:
  1. An MCP server with that name declared in this plugin’s package (*.mcp.json, listed under mcpServers in the manifest). This plugin’s servers always win.
  2. An MCP server with that name that the user configured, or one from another plugin.
To call another plugin’s server, write '<plugin-name>/<server-name>'. When only one server matches the name, the bare server name works too. If this plugin has no server with that name and the name matches more than one server (user-configured or from other plugins), you get MCP_SERVER_AMBIGUOUS and need to switch to '<plugin-name>/<server-name>'.

Permissions

ctx.mcp.call follows the Agent’s permission rules:
  • An allow rule exists: the call goes through.
  • A deny rule exists: throws PERMISSION_DENIED.
  • Ask is needed: the standard permission card appears, labeled with the plugin that made the call. The card’s allow option, “Only this chat”, allows only this one call, and the next call asks again. Whatever the user answers, no permission rule is saved.
  • An extension in preview doesn’t inherit the installed version’s allow rules.
  • The card waits until the user handles it. To cap the wait, pass a signal.
Each plugin has two queues in each session: one shared by button actions and slash commands, and one for observe events. While an earlier hook is still running, later ones in the same queue wait. A call waiting on the card holds up the queue it’s in. When it started from a button action or a command, later button actions and commands queue behind it, up to 10 combined (including the one running). Beyond that, a button action reports GESTURE_QUEUE_FULL and a command reports COMMAND_BUSY. When it started from an observe event, later observe events queue behind it, up to 32, and more are dropped, with a GESTURE_QUEUE_FULL entry in inspect.runtime.diagnostics. See Queue limits.Calling ctx.mcp.call from a drawing asks in the same way, but the wait ends with the drawing. When the drawing’s deadline arrives, or a newer drawing for that location starts, the card is withdrawn and the call throws CANCELLED.

Rate limit

Each plugin can make at most 60 calls per minute. Going over reports MCP_CALL_RATE_LIMITED.

What it returns

On success it returns the MCP result:A missing server or tool, a failure partway through the call, and similar cases throw. The error’s message explains why.The type files also have a McpCallOutcome type that describes how far a failed call got:
In the current version, MCode records this value in its own call log. The error your extension receives carries only code and message. For operations that may already have run (such as writes or sends), don’t retry just because the call threw.

Example: a sync button

The plugin package bundles a notes MCP server. Pressing the button calls its sync tool and waits up to 30 seconds.
hooks/register.tsx

Notify the user and control the interface

Toast text can be at most 500 characters, and the rest is cut off. Each plugin can show at most 6 toasts per minute. Extra toasts are dropped. The call itself doesn’t fail, and inspect records a toast.dropped entry.
Save focus: true for when the user presses a button, and open panels from observe events without focus. Each plugin can have at most 16 panels open at once in a session. For the rules on opening, closing, focus, and redraw timing, see Interface.

Fill text into the message box

Writes text into this session’s message box draft. It doesn’t send automatically. The user reads it and decides whether to send. Any Invocation can use it: buttons, inputs, timers, observe events, even drawings.Return value:Even written: true doesn’t guarantee the text landed. If replace runs while the user is typing, the write is dropped to keep the user’s text. If a dialog opens at the moment of writing, both modes drop the write.

Show a gray suggestion

Shows one line of text as a gray suggestion in the message box. The user accepts it with Tab or the Right arrow key. It isn’t written into the draft, and it isn’t sent.
  • text must be a single line, non-empty after trimming whitespace, and at most 120 characters, or you get ARGUMENT_INVALID.
  • There’s only one suggestion slot. The last valid write wins, including MCode’s own suggestions that arrive later. Nobody has priority.
  • The suggestion is cleared when the next turn starts.
  • Any Invocation can use it.
Return value:

Read the draft

Returns the plain text of this session’s message box draft, with @ references as text. Content on the status band above the message box isn’t part of the draft.
  • Write ctx.prompt.read() out in full in the module so it ends up in calls:. Otherwise you get CALL_NOT_DECLARED at run time.
  • If no message box responds within 2 seconds, it throws PROMPT_READ_UNAVAILABLE.
  • Any Invocation can use it.
See the example in the next section.

Call a model

Runs one inference on the input you give, without asking for confirmation.
  • Only what you pass is sent. Conversation history, tools, the Agent’s system prompt, and thinking settings stay out.
  • It uses this session’s account and quota, and you can call it while the main conversation is running. Usage is recorded separately and doesn’t count toward the main conversation’s turn.
  • The result goes only to the caller and never enters the conversation. To show it, fill it into the message box, or save it, do that yourself.
  • It throws on bad arguments or when the Invocation has already ended. Model service errors don’t throw. Check the return value instead.
Check isAnswered first:usage ({ inputTokens, outputTokens }) may be present even on failure.

Example: title the draft

Pressing the button reads the draft, asks the model for a title, and shows it on the status band. Pressing again appends the title to the end of the draft.
hooks/state.ts
hooks/register.tsx

Start a background subagent

Starts a background subagent in this session and returns right away without waiting for it to finish.
  • No confirmation. Starting it doesn’t ask the user. When the subagent calls tools, the usual permission rules apply.
  • Results go only to this plugin. The subagent’s result isn’t handed to the main Agent, and compaction summaries don’t mention it. When it ends, this plugin receives a turn.complete with the same agentId. In it, answer is the final reply (up to 32 KB, with answerTruncated: true when truncated), and reason is answer, aborted, refusal, or error. With no reply, answer is an empty string. If MCode didn’t manage to read the reply, there’s no answer field, and reason may still be answer, so check answer itself before using it. This event can arrive up to 10 seconds after the subagent ends.
  • Remember the agentId. Save it in ctx.state so you can recognize the matching turn.complete. Results that arrive while no plugin is listening aren’t sent again.
  • Concurrency limit. The number of subagents one plugin runs at once in a session can’t exceed the session’s subagent limit. Going over reports AGENT_CONCURRENCY_LIMIT (the message includes the current count and the limit). A full session reports the same error. An unknown agentType reports AGENT_UNKNOWN_TYPE, and other start failures report AGENT_START_FAILED.
  • The subagent belongs to the session. It keeps running after you reload or withdraw the plugin. Deleting the session ends it. When the user clicks stop in the conversation, it stops like any other background subagent in the session (unless the user turned off conversation.stopSubAgent), and reason is aborted.
  • It shows up in the Subagents column of the workspace panel, where the user can open its conversation. It’s not a background task.
await ctx.agent.list() lists this session’s subagents (including finished ones). The data matches the Subagents column and excludes the main session, Bash tasks, and subagents from other sessions. Each item has:Prompts, results, models, and token counts aren’t returned.

Example: find TODOs in the background

hooks/state.ts
hooks/register.tsx
ctx.state is lost on a Runtime restart, and so is the agentId of a running subagent. To track it across restarts, save the agentId in ctx.store.

Add slash commands

Coming soonA plugin can add commands to the / menu in the message box. When the user picks one in the menu, or types /<command name> arguments and presses Enter, your command.run hook runs. The command’s content isn’t sent to the model.
Write the argument as an object literal with only these three keys. For the rules and their diagnostics, see Static rules. If an argument is invalid at run time, or name isn’t one of the commands found by the scan at preview, MCode reports ARGUMENT_INVALID.After registering, handle the command with on('command.run', { command: '<command name>' }, …). For e.args, return values, and when it runs, see command.run.

Register in session.start

  • A command lives in the session and the Activation that registered it. It goes away when the Activation ends (see below), so register in session.start, one call per command, not in a loop. Two sessions can list different commands.
  • Wrap it in try/catch. A built-in command, a skill, or another plugin may already hold the name, and then register throws. See the next section.
  • Restore first, then register. For a plugin with commands, MCode waits up to 3 seconds to read the user’s skill list before session.start runs. A command.run can arrive before session.start finishes, so if session.start restores data (such as a theme), restore it before registering commands. Otherwise the restored old value can overwrite what a command the user just ran did.
  • Registering again costs nothing. Registering exactly the same content again does nothing. Changing the case of the name, the description, or the argumentHint updates that item in the menu.
Withdrawing, disabling, uninstalling, or reloading a plugin, and deleting the session, all remove the commands it registered. After a reload, the new version registers them again in its own session.start, so the menu may be missing them for a moment.

When the name is taken

  • Names are compared without regard to case, so /Note and /note are the same command. How you write it when registering only decides how it shows in the menu.
  • The plugin that registers first keeps the name. There’s no waiting list. After that plugin leaves, you have to register again, usually in the next session.start.
  • The check covers skills present when this Activation started. A skill installed later doesn’t take back a command you already registered.
  • The user’s own skill list only arrives at session.start, so register in session.start. Registering earlier (for example in a drawing) only checks against built-in commands and the session’s skills. The user’s skill list is read once per Activation, with a wait of up to 3 seconds. If it can’t be read or arrives late, registration goes ahead, and inspect records an EXTENSION_OBSERVE_FAILED.

Limits

Identical repeat registrations and rejected registrations don’t count.

List commands

await ctx.command.list() returns the commands registered by all plugins in this session, not including built-in commands. Each item is { pluginId, displayName?, name, description, argumentHint? }. displayName is the plugin’s display name.

How the user runs them

  • The menu. Plugin commands are listed after built-in commands and skills, in a group named “Plugin commands”. Each row shows /<command name>, followed by the argumentHint if there is one, with the plugin’s display name on the right (the plugin id when there’s no display name). While a command runs, its row shows “Running”.
  • Picking from the menu. A command without an argumentHint runs as soon as it’s picked, and e.args is an empty string. For a command with an argumentHint, picking it first fills /<command name> into the message box, and the user finishes the arguments and presses Enter.
  • Typing it. When a new one-line message the user types starts with /<command name>, pressing Enter runs the command, in any input mode, goal mode included. To send the model text that starts with a command name, put a word before the / or add a second line. A typed command runs as long as no built-in command or skill has the same name. If one does, the built-in command or skill runs instead. The same goes for a skill with the same name added after you registered: typing the command runs the skill, but picking your item in the menu still runs your command.
  • One line only. A typed command must fit on one line. If the draft contains a line break, it’s sent to the model as an ordinary message.
  • New messages only. Only a message the user newly types can run a command. When editing an earlier message or a queued message, the menu doesn’t list plugin commands, and /<command name> is saved as text. Preset prompts are sent as is. If the draft has attachments, the command still runs, and the attachments stay in the draft to go with the next message.
  • Available after the session starts. Commands are registered in session.start, so in a new conversation the menu lists plugin commands only after the first message is sent.
  • The message box clears once it’s sent. Once the user sends the command, its text is cleared from the message box and isn’t put back whatever the outcome. Only arguments that are too long (COMMAND_ARGS_TOO_LONG) are refused before sending, and then the text stays in the box.

Messages the user sees

After a command runs, the text returned by command.run shows as a toast. When there’s no result, the user sees one of the messages below, where /note is the actual command name:For what each code means, see command.run.These are MCode’s generic messages: they can’t say what went wrong in your plugin, and the user can’t get the typed text back. So for failures you expect and the user can fix (wrong arguments, a missing precondition), return { text } from command.run telling the user what to do instead of throwing.

Example: notes on the status band

/note <text> adds a note, and /note-clear clears them. The status band shows the 3 most recent notes.
hooks/state.ts
hooks/register.tsx

Set a theme

Coming soonA plugin can give the conversation its own theme: a picture drawn on the backdrop, plus a palette for the window. The backdrop is the backdrop behind the conversation in the main window, a layer under all the panels. It replaces the wallpaper while a plugin theme is active. Its site name in code is backdrop. See Interface: backdrop.
  • Give at least one. set needs at least one of backdrop and colors. An empty argument, or a field MCode doesn’t recognize at the top level or in backdrop or glass, reports ARGUMENT_INVALID, and the message names the field. On an error, the session’s theme stays as it was.
  • One theme per session. set replaces the whole current theme, and any field you leave out is gone. Your second set replaces your first. When another plugin calls set, it replaces yours outright. Themes don’t stack, and the previous one doesn’t come back.
  • clear clears this session’s theme. It clears it no matter which plugin calls it or who set the theme.
  • Call it anywhere. You can use it in any Invocation, including a drawing. If the current theme is yours, calling set again with exactly the same argument does nothing.
  • ctx.theme.set and ctx.theme.clear enter calls: only when the module writes them out.

backdrop

backdrop declares that you’ll draw the backdrop. The actual picture comes from your on('ui.render', { site: 'backdrop' }, …), which can use <Box>, <Text>, and <Svg>.glass fields:With glass: false, the reply rows show directly on the picture, and keeping them readable is up to you.Every plugin’s backdrop layer runs, no matter who set the theme. In the drawing, check e.props.plugin and e.props.scene first, and return next() when the theme isn’t yours. Otherwise you cover other plugins’ backdrops. For the rules on writing <Svg>, see Interface: backdrop.

colors

colors gives 2 to 7 anchor colors, and MCode derives the full interface palette from them.Write colors in hex: #rgb, #rgba, #rrggbb, or #rrggbbaa. Anchors you leave out use the values from MCode’s default palette. accent uses the default blue and doesn’t follow your surface.Contrast. MCode first measures the contrast of the text anchors (text-*) on the surface anchors (surface-*) exactly as you wrote them:For each text color corrected, and each anchor that used a default value, inspect records a THEME_PALETTE_ADJUSTED saying what changed.Once it applies. Your palette replaces the colors of the user’s theme pack and wallpaper. While the theme is active, the accent and background colors the user picked don’t apply. The user’s font, interface density, and contrast settings still apply. The window’s base color also becomes a solid color that follows surface-0 (or surface-1 when you set it). When there’s a wallpaper over that base and you don’t draw a backdrop, the photo shows through the translucent panels. In that case the window may adjust the colors of text, icons, code highlighting, links, and accent-colored icons to keep them readable. Panels and accent fills are drawn in the colors you gave.Light and dark. colors can be one set of anchors, or split by mode as { light, dark }:{ light, dark } needs at least one of the two. Mixing anchors with modes, unknown keys, or an empty object reports ARGUMENT_INVALID. Contrast is measured separately for each mode, and a rejection message names the mode, for example theme.set colors.dark: ….

Keep the theme

MCode keeps the theme only in memory. It doesn’t write it to disk and doesn’t restore it on its own. To keep the theme across reloads and Runtime restarts, save it yourself with ctx.store and call set again in session.start.When a plugin is withdrawn, disabled, or uninstalled, the theme it set is removed, and the user’s own wallpaper and colors come back.

What settings show

While a plugin theme is active, Settings → Appearance explains that the plugin controls the current look:

Example: a night sky theme

A button on the status band switches to a night sky theme, and pressing it again restores the original look. The choice is saved in ctx.store and restored on the next Activation.
hooks/register.tsx

Read session info

id, cwd, root, and model are snapshots taken when the Invocation starts. usage() reads at call time, and any hook, drawing, or callback can use it:context is the context of the main Agent’s most recently measured reply, and it matches the numbers in the context usage indicator. A missing field means not measured yet, not zero. In a new session, or when the model doesn’t report usage, tokens, percent, and breakdown are all absent. When usage is 0, tokens and percent are absent too.

Timers

For timers, use ctx.clock:ms must be at least 1000. Smaller values throw. The callback runs as a new Invocation and uses the ctx of the enclosing hook. Call dispose() to cancel the timer.

Cancel

AbortController and AbortSignal are available globally. Pass a signal to calls that support cancelling:When an Invocation ends, the model requests it started are aborted too.

Next steps

Events (hooks)

When observe events fire and what fields they carry.

Interface: sites and elements

The status band, panels, and elements.

Test and troubleshoot

Use fakes to test MCP, models, the message box, and subagents.

Extensions reference

The ctx method table and all limits.