> ## Documentation Index
> Fetch the complete documentation index at: https://agent.minimax.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Extension API

> Use ctx in hooks and callbacks to save state, call MCP, notify the user, fill the message box, call models, start background subagents, add slash commands, and set themes.

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`](#clock). To reach files or the network, go through the plugin's MCP tools. See [Call MCP tools](#mcp-call).

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](https://agent.minimax.io/docs/extension/interface.md#sites).

> [!NOTE]
>
> 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](https://agent.minimax.io/docs/extension/events.md#register).
* **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`](https://agent.minimax.io/docs/extension/errors).
* **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`](https://agent.minimax.io/docs/extension/errors). The same goes for calls such as `ctx.command.register` and `ctx.theme.set`. `await` every operation you need.

```tsx theme={null}
// Wrong: no await, so onPress has already ended and the toast throws INVOCATION_SETTLED
onPress={() => {
  ctx.mcp.call('notes', 'sync').then(() => ctx.ui.toast('Synced'));
}}

// Right: await every step
onPress={async () => {
  await ctx.mcp.call('notes', 'sync');
  await ctx.ui.toast('Synced');
}}
```

### 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`](https://agent.minimax.io/docs/extension/errors). 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:

| | `ctx.state` | `ctx.store` |
| - | - | - |
| Scope | One copy per plugin per session | One copy per plugin, shared by all sessions |
| Must be declared first | Yes, with `defineState` | No |
| Read | Synchronous, `ctx.state.get(key)` | Asynchronous, `await ctx.store.get(key)` |
| Redraws after a write | Yes, drawings that read the key redraw | No, call `ctx.ui.invalidate()` yourself |
| After a reload | Kept | Kept |
| After a Runtime restart | Lost, back to defaults | Kept |
| Max size per value | 64 KB | 256 KB |
| Max total size | 1 MB per plugin per session | 8 MB per plugin |

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:

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({ turns: { default: 0 } });

// Tell the editor which keys ctx.state has and what type each value is
declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
export { state } from './state';
```

* The argument to `defineState` must be an object literal, or you get [`EXTENSION_STATE_SHAPE_INVALID`](https://agent.minimax.io/docs/extension/errors). 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`](https://agent.minimax.io/docs/extension/errors), and at run time you get [`STATE_WRITE_IN_RENDER`](https://agent.minimax.io/docs/extension/errors).
* 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:

| Method | Notes |
| - | - |
| `await ctx.store.get(key)` | Read. Returns `undefined` if the key is missing |
| `await ctx.store.set(key, value)` | Write |
| `await ctx.store.delete(key)` | Delete |
| `await ctx.store.keys()` | List all keys |
| `ctx.store.onDidChange((change) => …)` | Listen for changes. `change` is `{ key, value }`. Returns `{ dispose() }` |

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

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  // When another session changes total, redraw here too.
  // The listener is removed when this Activation ends (reload or withdraw). session.start fires once per Activation, so listeners don't pile up.
  on('session.start', (ctx, e) => {
    ctx.store.onDidChange((change) => {
      if (change.key === 'total') ctx.ui.invalidate();
    });
  });

  on('turn.complete', async (ctx, e) => {
    if (e.agentId !== undefined) return;
    // ctx.state: belongs only to this session; the drawing reads it, so writes redraw automatically
    await ctx.state.update('turns', (n) => n + 1);
    // ctx.store: shared by all sessions of this plugin; writes don't trigger a redraw
    const total = await ctx.store.get('total');
    await ctx.store.set('total', (typeof total === 'number' ? total : 0) + 1);
    ctx.ui.invalidate();
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const total = await ctx.store.get('total');
    return (
      <Box direction="column" gap="1">
        <Text size="sm" tone="secondary">
          {`${ctx.state.get('turns')} turns this session, ${typeof total === 'number' ? total : 0} in total`}
        </Text>
        {await next()}
      </Box>
    );
  });
};
```

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

## Call MCP tools

```ts theme={null}
const result = await ctx.mcp.call(server, tool, args, { signal });
```

| Parameter | Notes |
| - | - |
| `server` | MCP server name. **Must be a string literal** |
| `tool` | Tool name |
| `args` | Optional. Arguments for the tool, any JSON |
| `signal` | Optional. An `AbortSignal` for cancelling. See [Cancel](#cancel) |

### 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`](https://agent.minimax.io/docs/extension/errors) 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`](https://agent.minimax.io/docs/extension/errors).
* 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`](https://agent.minimax.io/docs/extension/errors) 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](https://agent.minimax.io/docs/extension/events.md#queue).

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`.

| Situation | Result |
| - | - |
| The user denies, closes the card, or stops the turn | `PERMISSION_DENIED` |
| The preview is withdrawn or reloaded, or `signal` is aborted | `CANCELLED` |
| The permission check or the permission request itself fails | `PERMISSION_REQUIRED` |

### Rate limit

Each plugin can make at most 60 calls per minute. Going over reports [`MCP_CALL_RATE_LIMITED`](https://agent.minimax.io/docs/extension/errors).

### What it returns

On success it returns the MCP result:

| Field | Type | Notes |
| - | - | - |
| `content` | `{ type, ... }[]` | List of content blocks. A text block is `{ type: 'text', text }` |
| `isError` | `boolean`, may be absent | `true` when the tool itself reports an error. In this case nothing is thrown, and the call returns normally |

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:

| Value | Meaning |
| - | - |
| `not_dispatched` | The request never reached the MCP server. The tool definitely didn't run |
| `provider_reported` | The server returned a result but marked it as an error (that is, `isError: true`) |
| `unknown_after_dispatch` | The request was sent, but the result is unknown. The tool may have run |

> [!NOTE]
>
> 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.

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button } from '@minimax/mcode-plugin-extension/ui';

export const register: Register = (on) => {
  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      <Button
        key="sync"
        label="Sync notes"
        icon="refresh"
        onPress={async () => {
          // Wait up to 30 seconds (including time the user spends on the permission card), then cancel
          const controller = new AbortController();
          const timer = ctx.clock.after(30_000, () => controller.abort());
          try {
            // The server name is a literal: the notes server bundled with this plugin
            const result = await ctx.mcp.call('notes', 'sync', { scope: 'session' }, {
              signal: controller.signal,
            });
            const first = result.content[0];
            const text = first?.type === 'text' ? String(first.text) : 'Synced';
            await ctx.ui.toast(text, { tone: result.isError ? 'danger' : 'success' });
          } catch (error) {
            const code = (error as { code?: string }).code;
            await ctx.ui.toast(
              code === 'PERMISSION_DENIED' ? 'Permission not granted' : code === 'CANCELLED' ? 'Cancelled' : 'Sync failed',
              { tone: 'warning' },
            );
          } finally {
            timer.dispose();
          }
        }}
      />
      {await next()}
    </Box>
  ));
};
```

## Notify the user and control the interface

| Method | Notes |
| - | - |
| `await ctx.ui.toast(text, { tone? })` | Show a toast. `tone` can be `secondary`, `success`, `warning`, or `danger` |
| `ctx.ui.invalidate()` | Ask for this plugin's drawings to redraw. Call it after writing `ctx.store` or when new data arrives |
| `await ctx.ui.open({ id, title, focus? })` | Open this plugin's panel `id` in the session side panel. If it's already open, only the title updates |
| `await ctx.ui.close(id)` | Close this plugin's panel `id`. Does nothing if it isn't open |

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.

```tsx theme={null}
await ctx.ui.toast('Saved', { tone: 'success' });
```

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](https://agent.minimax.io/docs/extension/interface.md).

## Fill text into the message box

```ts theme={null}
const filled = await ctx.prompt.fill({ text, mode });
```

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.

| `mode` | Behavior |
| - | - |
| `replace` (default) | Replaces the whole draft, including @ references. **Writes only when the draft is empty** and leaves a non-empty draft alone |
| `append` | Appends text to the end of the draft, keeping what the user wrote and any @ references. Works even when the draft isn't empty |

Return value:

| Returns | Meaning |
| - | - |
| `{ written: true }` | The message box accepted the write |
| `{ written: false, reason: 'draft' }` | You used `replace`, but the draft isn't empty |
| `{ written: false, reason: 'modal' }` | A dialog is open |
| `{ written: false, reason: 'no-composer' }` | No message box is available right now |

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.

```tsx theme={null}
const filled = await ctx.prompt.fill({ text: 'Check the risks in this change.' });
if (!filled.written && filled.reason === 'draft') {
  await ctx.ui.toast('The message box already has text');
}
```

## Show a gray suggestion

```ts theme={null}
const shown = await ctx.prompt.suggest({ text });
```

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:

| Returns | Meaning |
| - | - |
| `{ isShown: true }` | The text took the suggestion slot. This doesn't mean the user saw it |
| `{ isShown: false, reason: 'draft-not-empty' }` | The draft isn't empty |
| `{ isShown: false, reason: 'turn-running' }` | A turn is in progress |
| `{ isShown: false, reason: 'dismissed' }` | The user dismissed the suggestion, another session's message box is in front, suggestions are turned off, or the slot rejected this write |
| `{ isShown: false, reason: 'no-turn' }` | The slot has no turn to attach to yet, for example when the session hasn't had a turn |
| `{ isShown: false, reason: 'no-composer' }` | No message box is available right now (none responded within 2 seconds) |

```tsx theme={null}
on('turn.start', async (ctx, e) => {
  if (e.prompt?.text.includes('release')) {
    const shown = await ctx.prompt.suggest({ text: 'Remember to run the tests first' });
    if (!shown.isShown) console.log(shown.reason);
  }
});
```

## Read the draft

```ts theme={null}
const draft = await ctx.prompt.read(); // { text }
```

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:`](#calls). Otherwise you get `CALL_NOT_DECLARED` at run time.
* If no message box responds within 2 seconds, it throws [`PROMPT_READ_UNAVAILABLE`](https://agent.minimax.io/docs/extension/errors).
* Any Invocation can use it.

See the example in the next section.

## Call a model

```ts theme={null}
const reply = await ctx.model.complete({ model, prompt, system, maxTokens, timeoutMs, signal });
```

Runs one inference on the input you give, without asking for confirmation.

| Parameter | Notes |
| - | - |
| `model` | Required, in `provider/model` form. You can pass `ctx.session.model`, the model this session will use for the next turn |
| `prompt` | Required. The user message |
| `system` | Optional. The system prompt |
| `maxTokens` | Optional. Defaults to 1024 and can't exceed the model's output limit (at most 64000) |
| `timeoutMs` | Optional. No default, max 2147483647 |
| `signal` | Optional. For cancelling |

* **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:

| Returns | Meaning |
| - | - |
| `{ isAnswered: true, text, usage? }` | Got a reply |
| `{ isAnswered: false, reason: 'empty-reply' }` | The model's reply was empty |
| `{ isAnswered: false, reason: 'timeout' }` | Exceeded `timeoutMs` |
| `{ isAnswered: false, reason: 'aborted' }` | `signal` was aborted, or the Invocation already ended |
| `{ isAnswered: false, reason: 'model-unavailable' }` | The model isn't available |
| `{ isAnswered: false, reason: 'provider-error' }` | The model service returned an error |

`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.

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  title: { default: '' },
  busy: { default: false },
});

declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button, Spinner, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const title = ctx.state.get('title');
    return (
      <Box direction="column" gap="1">
        <Box direction="row" gap="2" align="center" wrap>
          {ctx.state.get('busy') ? (
            <Spinner label="Writing a title" />
          ) : (
            <Button
              key="make-title"
              label="Title the draft"
              icon="edit"
              variant="plain"
              onPress={async () => {
                // Read the draft: because the module writes ctx.prompt.read(), it ends up in calls:
                const draft = await ctx.prompt.read();
                if (draft.text.trim() === '') {
                  await ctx.ui.toast('The message box is empty');
                  return;
                }
                await ctx.state.set('busy', true);
                try {
                  // Use the model this session will use next turn; no conversation history or tools
                  const reply = await ctx.model.complete({
                    model: ctx.session.model,
                    system: 'Output only a title of at most 8 words, with no punctuation.',
                    prompt: draft.text,
                    maxTokens: 64,
                    timeoutMs: 20_000,
                  });
                  if (reply.isAnswered) {
                    await ctx.state.set('title', reply.text.trim());
                  } else {
                    await ctx.ui.toast(`No reply: ${reply.reason}`, { tone: 'warning' });
                  }
                } finally {
                  await ctx.state.set('busy', false);
                }
              }}
            />
          )}
          {title ? <Text size="sm" truncate>{title}</Text> : undefined}
          {title ? (
            <Button
              key="append-title"
              label="Add to end of draft"
              variant="plain"
              onPress={async () => {
                // append works on a non-empty draft and doesn't send
                const filled = await ctx.prompt.fill({ text: `\nTitle: ${ctx.state.get('title')}`, mode: 'append' });
                if (!filled.written) await ctx.ui.toast(`Not written: ${filled.reason}`);
              }}
            />
          ) : undefined}
        </Box>
        {await next()}
      </Box>
    );
  });
};
```

## Start a background subagent

```ts theme={null}
const started = await ctx.agent.spawn({ prompt, description, agentType, model });
// started is { agentId, model }
```

Starts a background subagent in this session and returns right away without waiting for it to finish.

| Parameter | Notes |
| - | - |
| `prompt` | Required. The task for the subagent |
| `description` | Optional. Up to 50 characters. Defaults to the first five words of `prompt` |
| `agentType` | Optional. Defaults to `worker`. Use `explore` for read-only investigation. It can also be the name of another built-in or plugin-provided Agent |
| `model` | Optional, `provider/model`. Defaults to the Agent's own model, then falls back to this session's model |

* **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`](https://agent.minimax.io/docs/extension/events#turn-events) 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`](https://agent.minimax.io/docs/extension/errors) (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:

| Field | Notes |
| - | - |
| `id` | Child session id, same as `agentId` in `turn.complete` |
| `description` | Task description or session title |
| `type` | Agent name |
| `status` | `pending`, `running`, `waiting`, `idle`, `completed`, `failed`, `killed` |
| `parentId` | May be absent. The parent of a nested subagent |
| `spawnedBy` | May be absent. The id of the plugin that started it |
| `name` | May be absent. Display name |

Prompts, results, models, and token counts aren't returned.

### Example: find TODOs in the background

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  agentId: { default: '' },
  summary: { default: '' },
});

declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button, Spinner, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  // When the subagent ends, this plugin receives a turn.complete with the same agentId
  on('turn.complete', async (ctx, e) => {
    if (e.agentId === undefined || e.agentId !== ctx.state.get('agentId')) return;
    await ctx.state.set('agentId', '');
    // answer can be missing even when reason is answer, so check answer itself
    if (e.answer !== undefined && e.answer !== '') {
      await ctx.state.set('summary', e.answer.split('\n')[0] ?? '');
      await ctx.ui.toast('Search finished', { tone: 'success' });
    } else {
      await ctx.ui.toast(`The subagent returned no result (${e.reason ?? e.status})`, { tone: 'warning' });
    }
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const running = ctx.state.get('agentId') !== '';
    const summary = ctx.state.get('summary');
    return (
      <Box direction="column" gap="1">
        <Box direction="row" gap="2" align="center">
          {running ? (
            <Spinner label="Searching in the background" />
          ) : (
            <Button
              key="spawn"
              label="Find TODOs in background"
              icon="search"
              variant="plain"
              onPress={async () => {
                // No confirmation; returns right away without waiting for the subagent to finish
                const started = await ctx.agent.spawn({
                  prompt: 'List every TODO comment in the workspace. Put the total count on the first line.',
                  description: 'Find TODOs',
                  agentType: 'explore',
                });
                await ctx.state.set('agentId', started.agentId);
              }}
            />
          )}
          {summary ? <Text size="sm" tone="secondary" truncate>{summary}</Text> : undefined}
        </Box>
        {await next()}
      </Box>
    );
  });
};
```

`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 soon

A 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`](https://agent.minimax.io/docs/extension/events#command-run) hook runs. The command's content isn't sent to the model.

```ts theme={null}
const registered = await ctx.command.register({ name, description, argumentHint });
// registered is { command }, the registered command name
```

| Parameter | Notes |
| - | - |
| `name` | Required. The command name, without the `/`. It must be a string literal, match `^[A-Za-z0-9_-]{1,64}$`, and not be the name of a built-in command |
| `description` | Required. 1 to 200 characters, shown in the menu |
| `argumentHint` | Optional. 1 to 64 characters, such as `<text>` or `[name]`, shown after the command name |

Write the argument as an object literal with only these three keys. For the rules and their diagnostics, see [Static rules](https://agent.minimax.io/docs/extension/events.md#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](https://agent.minimax.io/docs/extension/events.md#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

| Code | When |
| - | - |
| `COMMAND_NAME_RESERVED` | The name is a built-in command, or a skill used the name when this Activation started: either the skill's run name, or the name shown in the `/` menu (built-in skills starting with `mavis-` don't show that prefix in the menu). The error message doesn't say which skill |
| `COMMAND_NAME_TAKEN` | Another plugin in this session registered the name first. The error message names that plugin |

* 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

| Limit | When exceeded |
| - | - |
| At most 32 commands in total from all plugins in a session | `register` reports `COMMAND_LIMIT_REACHED` |
| At most 64 `register` calls that change commands per Activation | `register` reports `COMMAND_LIMIT_REACHED` |

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:

| Message | When |
| - | - |
| /note no longer exists | The command that ran is gone |
| The arguments of /note are too long | `e.args` is longer than 4096 characters |
| /note did not run: the plugin is busy, try again | `COMMAND_BUSY`, this plugin's action queue is full |
| /note didn't respond | `COMMAND_UNHANDLED` |
| /note failed | `COMMAND_FAILED` |
| /note is unavailable: the plugin is paused | `COMMAND_PAUSED` |
| /note is unavailable: the plugin is reloading or disabled | `COMMAND_RETIRED` |
| /note timed out and may have run already | `COMMAND_TIMEOUT` |
| /note didn't run: this conversation no longer exists | The session was deleted |
| /note didn't run. Try again | Any other reason |

For what each code means, see [command.run](https://agent.minimax.io/docs/extension/events.md#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.

```ts hooks/state.ts theme={null}
import { defineState } from '@minimax/mcode-plugin-extension';

export const state = defineState({
  notes: { default: [] as string[] },
});

// Tell the editor which keys ctx.state has and what type each value is
declare module '@minimax/mcode-plugin-extension' {
  interface ExtensionStateRegistry {
    readonly spec: typeof state.spec;
  }
}
```

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Text } from '@minimax/mcode-plugin-extension/ui';

export { state } from './state';

export const register: Register = (on) => {
  // Register commands in session.start. A built-in command, a skill, or another plugin may hold the name, so use try/catch
  on('session.start', async (ctx, e) => {
    try {
      await ctx.command.register({
        name: 'note',
        description: 'Add a note to the status band',
        argumentHint: '<text>',
      });
    } catch (error) {
      console.warn(String(error));
    }
    try {
      await ctx.command.register({ name: 'note-clear', description: 'Clear the notes on the status band' });
    } catch (error) {
      console.warn(String(error));
    }
  });

  // The matcher is required, and command must be a name registered above
  on('command.run', { command: 'note' }, async (ctx, e) => {
    // e.args is the text the user typed after the command name, with leading and trailing whitespace removed
    const text = e.args.slice(0, 80);
    if (text === '') return { text: 'Usage: /note <text>' };
    // Keep only the 3 most recent
    await ctx.state.update('notes', (notes) => [...notes, text].slice(-3));
    // The returned text shows to the user as a toast and isn't sent to the model
    return { text: `Noted: ${text}` };
  });

  on('command.run', { command: 'note-clear' }, async (ctx, e) => {
    await ctx.state.set('notes', []);
    return { text: 'Notes cleared' };
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const notes = ctx.state.get('notes');
    return (
      <Box direction="column" gap="1">
        {notes.length > 0 ? (
          <Text size="sm" tone="secondary" truncate>{`Notes: ${notes.join(' · ')}`}</Text>
        ) : undefined}
        {await next()}
      </Box>
    );
  });
};
```

## Set a theme

Coming soon

A 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](https://agent.minimax.io/docs/extension/interface.md#backdrop).

```ts theme={null}
await ctx.theme.set({ backdrop, colors });
await ctx.theme.clear();
```

* **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:`](#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>`.

| Field | Notes |
| - | - |
| `scene` | Required, 1 to 64 characters. A name you give this picture, read back from `e.props.scene` when drawing. A plugin can have several scenes and pick which one to draw by name |
| `blur` | Optional, 0 to 30, default 0. Blurs the layer you draw |
| `dim` | Optional, 0 to 100, default 22. Darkens the layer you draw |
| `glass` | Optional. The reading surface under the reply rows: `{ blur?, tint?, opacity? }`, or `false` for no reading surface |

`glass` fields:

| Field | Notes |
| - | - |
| `blur` | 0 to 30 pixels, default 8 |
| `tint` | A hex color. Defaults to the panel color (derived from `surface-1` when `colors` sets it, otherwise from `surface-0`) |
| `opacity` | 0 to 1. Defaults to the color's own opacity |

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](https://agent.minimax.io/docs/extension/interface.md#backdrop).

### colors

`colors` gives 2 to 7 anchor colors, and MCode derives the full interface palette from them.

| Anchor | Required |
| - | - |
| `surface-0` | Required |
| `text-primary` | Required |
| `surface-1` | Optional |
| `text-secondary` | Optional |
| `text-tertiary` | Optional |
| `accent` | Optional |
| `border` | Optional |

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:

| Contrast | Result |
| - | - |
| Any pair below 3:1 | The whole palette is rejected, and `set` throws `THEME_PALETTE_REJECTED`. The `message` names the text color, the surface color, and their contrast. Change one of those two colors |
| No pair below 3:1 | The palette is accepted. Text colors below 4.5:1 are darkened or lightened to get as close as possible to 4.5:1 on their surface |

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 }`:

| Form | Effect |
| - | - |
| `{ light, dark }` | Each mode uses its own palette. Light or dark stays the user's own setting: the mode they chose, or their theme pack's lock when it has only one mode |
| One set of anchors, or only `light` or only `dark` | A single mode: one palette, and while your theme is set it also decides whether the main window is light or dark, whatever the user chose. A light `surface-0` (or `surface-1` when you set it) makes the window light, a dark one makes it dark. Other windows and the operating system's theme aren't affected; the light/dark switch in Settings → Appearance is disabled and says it follows the plugin |

`{ 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`](#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:

| Where | What it shows |
| - | - |
| The "Theme" row, when the theme sets `colors` | "Colors come from the theme set by X, which also lifts any light/dark limit of this theme; clear that plugin's theme to exit" (X is the plugin name) |
| The "Page colors" row, when the theme sets `colors` | "Colors come from the theme set by X. To adjust them yourself, clear its theme in that plugin first." (X is the plugin name), with "Matches plugin theme" on the right |
| The same row, when `colors` doesn't set both `light` and `dark` | Also shows "Light and dark follow the plugin theme while it is set" |
| The wallpaper setting, when the plugin draws a backdrop | "Wallpaper is currently replaced by the X plugin's backdrop" (X is the plugin name). When the plugin name isn't available, it shows "Wallpaper is currently replaced by a plugin backdrop" |

### 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.

```tsx hooks/register.tsx theme={null}
import type { Register } from '@minimax/mcode-plugin-extension';
import { Box, Button, Svg } from '@minimax/mcode-plugin-extension/ui';

// The night sky drawn on the backdrop. It only references its own elements (url(#sky)), nothing external
const NIGHT_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 900" preserveAspectRatio="xMidYMid slice">
  <defs>
    <linearGradient id="sky" x1="0" y1="0" x2="0" y2="1">
      <stop offset="0" stop-color="#0b1026"/>
      <stop offset="1" stop-color="#26315c"/>
    </linearGradient>
  </defs>
  <rect width="1600" height="900" fill="url(#sky)"/>
  <circle cx="1280" cy="180" r="70" fill="#f4f1d0" opacity="0.9"/>
  <circle cx="300" cy="120" r="2" fill="#ffffff"/>
  <circle cx="640" cy="260" r="1.5" fill="#ffffff"/>
  <circle cx="980" cy="90" r="2" fill="#ffffff"/>
</svg>`;

// Each session has one theme, and set replaces the whole previous setting, so always pass the full theme
const NIGHT_THEME = {
  backdrop: { scene: 'night', blur: 0, dim: 30, glass: { blur: 12, opacity: 0.7 } },
  colors: {
    light: { 'surface-0': '#f5f6fb', 'text-primary': '#1b2133', accent: '#4b5bd6' },
    dark: { 'surface-0': '#10142a', 'text-primary': '#e8eaf6', accent: '#8f9cff' },
  },
} as const;

export const register: Register = (on) => {
  // MCode doesn't save the theme. The plugin keeps it in ctx.store and sets it again on each Activation
  on('session.start', async (ctx, e) => {
    if ((await ctx.store.get('night')) === true) await ctx.theme.set(NIGHT_THEME);
  });

  // Every plugin's backdrop layer runs, so draw only your own scene and hand everything else to the next layer
  on('ui.render', { site: 'backdrop' }, async (ctx, e, next) => {
    if (e.props.plugin !== ctx.plugin.id || e.props.scene !== 'night') return next();
    return <Svg source={NIGHT_SVG} alt="" />;
  });

  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
    const night = (await ctx.store.get('night')) === true;
    return (
      <Box direction="column" gap="1">
        <Button
          key="toggle-theme"
          label={night ? 'Restore the original look' : 'Use the night sky theme'}
          icon="refresh"
          variant="plain"
          onPress={async () => {
            if (night) {
              await ctx.theme.clear();
              await ctx.store.delete('night');
            } else {
              try {
                await ctx.theme.set(NIGHT_THEME);
                await ctx.store.set('night', true);
              } catch (error) {
                // Too little color contrast reports THEME_PALETTE_REJECTED, and a bad argument reports ARGUMENT_INVALID
                await ctx.ui.toast(String(error), { tone: 'danger' });
                return;
              }
            }
            // Writing ctx.store doesn't redraw on its own, so refresh the button label by hand
            ctx.ui.invalidate();
          }}
        />
        {await next()}
      </Box>
    );
  });
};
```

## Read session info

| Property or method | Notes |
| - | - |
| `ctx.session.id` | This session's id |
| `ctx.session.cwd` | The session's working directory |
| `ctx.session.root` | Root of the git repository containing the working directory. Absent when it's not in a repository |
| `ctx.session.model` | The model the next turn will use, in `provider/model` form |
| `await ctx.session.usage()` | Read context usage. See the table below |
| `ctx.plugin` | `{ id, version }`, the name and version of the running plugin |

`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:

| Field | Notes |
| - | - |
| `startedAt` | Session creation time, Unix ms |
| `context.window` | Context window size in tokens. Always present. Before any measurement, it's the model's window size |
| `context.tokens` | Tokens used |
| `context.percent` | Percentage used, 0 to 100, rounded |
| `context.breakdown` | Usage by part, `{ kind, tokens }[]`, where `kind` is something like `MESSAGES` or `TOOLS` |
| `rateLimits` | Always an empty array for now |

`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.

```tsx theme={null}
// A fragment inside register; import Box, Tag, and Text from '@minimax/mcode-plugin-extension/ui'
on('session.measure', (ctx, e) => ctx.ui.invalidate());

on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => {
  const usage = await ctx.session.usage();
  const percent = usage.context.percent;
  // Not measured yet: draw nothing of our own and keep only other plugins' content
  if (percent === undefined) return next();
  return (
    <Box direction="row" gap="2" align="center">
      <Text size="sm" tone="secondary">{`Context ${percent}%`}</Text>
      {percent >= 80 ? <Tag label="Almost full" tone="warning" /> : undefined}
      {await next()}
    </Box>
  );
});
```

## Timers

For timers, use `ctx.clock`:

| Method | Notes |
| - | - |
| `ctx.clock.now()` | Current time on the MCode host, Unix ms |
| `ctx.clock.after(ms, () => …)` | Runs once after `ms` milliseconds. Returns `{ dispose() }` |
| `ctx.clock.every(ms, () => …)` | Runs every `ms` milliseconds. Returns `{ dispose() }` |

`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.

```tsx theme={null}
on('session.start', (ctx, e) => {
  // Redraw every minute to update the time shown on the status band
  ctx.clock.every(60_000, () => ctx.ui.invalidate());
});
```

## Cancel

`AbortController` and `AbortSignal` are available globally. Pass a `signal` to calls that support cancelling:

| Call | After abort |
| - | - |
| `ctx.mcp.call(server, tool, args, { signal })` | Throws `CANCELLED` right away and aborts the MCP request. If you pass a `signal` that's already aborted, the tool isn't called and the call throws immediately |
| `ctx.model.complete({ ..., signal })` | Returns `reason: 'aborted'` right away without throwing, and aborts the model request. If you pass a `signal` that's already aborted, it returns `aborted` immediately without calling the model |

When an Invocation ends, the model requests it started are aborted too.

```tsx theme={null}
// A fragment inside a callback: draft comes from await ctx.prompt.read()
const controller = new AbortController();
// Cancel after 15 seconds
const timer = ctx.clock.after(15_000, () => controller.abort());
const reply = await ctx.model.complete({
  model: ctx.session.model,
  prompt: 'Summarize in one sentence: ' + draft.text,
  signal: controller.signal,
});
timer.dispose();
```

## Next steps

> [card] [Events (hooks)](https://agent.minimax.io/docs/extension/events.md)
>
> When observe events fire and what fields they carry.

> [card] [Interface: sites and elements](https://agent.minimax.io/docs/extension/interface.md)
>
> The status band, panels, and elements.

> [card] [Test and troubleshoot](https://agent.minimax.io/docs/extension/testing.md)
>
> Use fakes to test MCP, models, the message box, and subagents.

> [card] [Extensions reference](https://agent.minimax.io/docs/extension/reference.md)
>
> The ctx method table and all limits.
