The first parameter of every hook is Save 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.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.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.Runs one inference on the input you give, without asking for confirmation.Starts a background subagent in this session and returns right away without waiting for it to finish.
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, andctx.store.onDidChangeuse thectxof the enclosing hook. See Register hooks. - Write it out in full. Write
ctx.state.set(…)andctx.mcp.call('notes', 'sync'). Don’t destructure or alias it, and don’t passctxto another function, or you getEXTENSION_CALL_SHAPE_INVALID. - Identity follows the call. Each
ctxcall takes its identity and permissions from the Invocation that is running right now. A button callback uses thectxfrom the drawing, but it runs as a “button action”, not as a “drawing”. - No use after an Invocation ends. Calling
ctxat the top level of the module, or from leftover async code after an Invocation has ended, throwsINVOCATION_SETTLED. The same goes for calls such asctx.command.registerandctx.theme.set.awaitevery operation you need.
Where calls: comes from
Preview andtest 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 withdefineState in hooks/state.ts, then re-export state from the module:hooks/state.ts
hooks/register.tsx
- The argument to
defineStatemust be an object literal, or you getEXTENSION_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 isnull, 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 throwsEXTENSION_SERVICE_FAILED. - Drawings can’t write
ctx.state. The static scan reportsEXTENSION_RENDER_SIDE_EFFECT, and at run time you getSTATE_WRITE_IN_RENDER. - When you change
defineStateand reload, removed keys are dropped. Keys whose type changed go back to their default, and MCode records anEXTENSION_STATE_SHAPE_INVALIDdiagnostic.
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:- An MCP server with that name declared in this plugin’s package (
*.mcp.json, listed undermcpServersin the manifest). This plugin’s servers always win. - An MCP server with that name that the user configured, or one from another plugin.
'<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.
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 reportsMCP_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 anotes 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.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
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
textmust be a single line, non-empty after trimming whitespace, and at most 120 characters, or you getARGUMENT_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.
Read the draft
- Write
ctx.prompt.read()out in full in the module so it ends up incalls:. Otherwise you getCALL_NOT_DECLAREDat run time. - If no message box responds within 2 seconds, it throws
PROMPT_READ_UNAVAILABLE. - Any Invocation can use it.
Call a model
- 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.
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
- 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.completewith the sameagentId. In it,answeris the final reply (up to 32 KB, withanswerTruncated: truewhen truncated), andreasonisanswer,aborted,refusal, orerror. With no reply,answeris an empty string. If MCode didn’t manage to read the reply, there’s noanswerfield, andreasonmay still beanswer, so checkansweritself before using it. This event can arrive up to 10 seconds after the subagent ends. - Remember the
agentId. Save it inctx.stateso you can recognize the matchingturn.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 unknownagentTypereportsAGENT_UNKNOWN_TYPE, and other start failures reportAGENT_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), andreasonisaborted. - 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 thenregisterthrows. 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.startruns. Acommand.runcan arrive beforesession.startfinishes, so ifsession.startrestores 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 theargumentHintupdates that item in the menu.
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
/Noteand/noteare 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 insession.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, andinspectrecords anEXTENSION_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 theargumentHintif 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
argumentHintruns as soon as it’s picked, ande.argsis an empty string. For a command with anargumentHint, 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, thetext 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 isbackdrop. See Interface: backdrop.- Give at least one.
setneeds at least one ofbackdropandcolors. An empty argument, or a field MCode doesn’t recognize at the top level or inbackdroporglass, reportsARGUMENT_INVALID, and the message names the field. On an error, the session’s theme stays as it was. - One theme per session.
setreplaces the whole current theme, and any field you leave out is gone. Your secondsetreplaces your first. When another plugin callsset, it replaces yours outright. Themes don’t stack, and the previous one doesn’t come back. clearclears 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
setagain with exactly the same argument does nothing. ctx.theme.setandctx.theme.clearentercalls: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 withctx.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 inctx.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, usectx.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.