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

# Write your first extension

> Go from init to install and write an extension that shows tool call counts in the status band.

This page walks you through writing an extension from scratch. It shows how many times the Agent has called tools in this session in the status band, plus a button that fills that count into the message box. You write the code in your editor, and the Agent handles init, testing, preview, and install.

An extension can display content in two places:

* **Status band**: 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`. This page's example draws here.
* **Panel**: 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`.

## Before you start

You develop extensions through the Agent's `extension` tool. The tool has 5 actions:

| Action | What it does |
| - | - |
| `init` | Generates a template package and returns the development folder. If the folder already exists, it only refreshes the type files |
| `test` | Validates the package with the same rules as preview, then runs `hooks/*.test.tsx` in the real extension host |
| `preview` | Validates the package and loads it into the current session. Needs your permission |
| `inspect` | Shows validation results, the version currently in preview, and runtime diagnostics |
| `withdraw` | Withdraws the preview from the current session. Files are kept |

The Agent runs validation and tests for you. Each step is one sentence to the Agent.

You need:

* MiniMax Code Desktop, working in a **local session in the main window**. See [Where it runs](https://agent.minimax.io/docs/extension/overview.md#where-it-runs).
* An editor that supports TypeScript, for type hints.

## Generate the template

Tell the Agent (start with `/extension-creator` so the Agent follows the extension workflow):

```text theme={null}
/extension-creator Use the extension tool to init an extension called tool-counter. I'll write the code myself.
```

The plugin name must start with a lowercase letter and contain only lowercase letters and digits, joined by single `-`, `_`, or `.` characters. It can be up to 80 characters long.

The Agent returns the development folder, `packagePath`, at:

```text theme={null}
<dataDir>/v2/plugin-dev/extensions/<session ID>/tool-counter/
```

Each session has its own development folder. `init` generates these files:

```text theme={null}
tool-counter/
├── .minimax-plugin/plugin.json   # name is tool-counter, "hooks": ["hooks/hooks.json"]
├── .minimax-plugin/types/        # Type files for your editor
├── hooks/hooks.json              # { "modules": ["./register.tsx"] }
├── hooks/register.tsx            # Template: a counter button
├── hooks/state.ts
├── hooks/register.test.tsx       # Tests for the template
├── tsconfig.json                 # Only extends ./.minimax-plugin/types/tsconfig.json
└── icon.png
```

> [!WARNING]
>
> The host manages `.minimax-plugin/types/`. It's refreshed on every `preview` and isn't part of the package. Don't edit the files in it. The `tsconfig.json` at the root is yours, and the host doesn't read it.

The template runs as is. See [A minimal extension](https://agent.minimax.io/docs/extension/overview.md#minimal-example) for its contents.

## Write the code

Open the development folder in your editor. With `.minimax-plugin/types/` in place, the editor shows type hints and errors. Replace the two files below.

First, declare the session state: a count that starts at 0.

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

// How many times the main Agent has called tools in this session. Starts at 0 in each session.
export const state = defineState({ toolCalls: { default: 0 } });

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

Then write the extension module: a `tool.call` observe event does the counting, and a `ui.render` hook draws the status band.

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

export { state } from './state';

export const register: Register = (on) => {
  // Observe event: runs once each time the Agent calls a tool. It runs alongside the conversation and doesn't slow it down.
  on('tool.call', async (ctx, e) => {
    // Subagent tool calls also arrive here (with agentId). Only count the main Agent's.
    if (e.agentId !== undefined) return;
    // Drawing reads toolCalls, so writing it redraws the status band automatically.
    await ctx.state.update('toolCalls', (count) => count + 1);
  });

  // Status band: one row above the message box.
  on('ui.render', { site: 'above-prompt' }, async (ctx, e, next) => (
    <Box direction="column" gap="1">
      <Box direction="row" wrap gap="2" align="center">
        <Text size="sm" tone="secondary">{`${ctx.state.get('toolCalls')} tool calls in this session`}</Text>
        {/* A count change redraws the status band. With a key, the button still receives presses after a redraw. */}
        <Button
          key="fill-count"
          label="Fill message box"
          icon="edit"
          variant="plain"
          onPress={async () => {
            const result = await ctx.prompt.fill({
              text: `So far this session has made ${ctx.state.get('toolCalls')} tool calls.`,
            });
            if (result.written) return;
            // If nothing was written, reason says why.
            if (result.reason === 'draft') {
              await ctx.ui.toast('The message box already has text, so it was left as is', { tone: 'warning' });
            } else if (result.reason === 'modal') {
              await ctx.ui.toast('Close the open dialog first', { tone: 'warning' });
            } else {
              await ctx.ui.toast('No message box found', { tone: 'warning' });
            }
          }}
        />
      </Box>
      {/* Keep what the plugins after you drew. Don't leave this out. */}
      {await next()}
    </Box>
  ));
};
```

Key points:

* **Keep the count in `ctx.state`.** It's session state, and each session has its own copy. Don't store session data in module-level variables, because all sessions share them.
* **Observe events don't need a manual redraw.** Drawing reads `toolCalls`, so when the hook writes it, the host redraws the status band.
* **`ctx.prompt.fill` never sends for you.** The default `replace` mode only writes when the message box is empty. If there's already text, it leaves it alone and returns `{ written: false, reason: 'draft' }`. The other two `reason` values are `modal` (a dialog is open) and `no-composer` (no message box responded). To add after existing text, pass `mode: 'append'`.
* **A button's `onPress` uses the enclosing hook's `ctx` through a closure.** Write `ctx` out in full and don't destructure it.
* **Don't leave out `await next()`.** Without it, the plugins after you can't draw (`EXTENSION_SHADOWING`).

> [!NOTE]
>
> Preview only transpiles the code and runs static checks. It doesn't type-check. Look for type errors in your editor. If you have TypeScript installed, you can also run `npx tsc -p .minimax-plugin/types` in the development folder yourself.

### Add a test while you're at it

`test` runs every `*.test.tsx` under `hooks/`. The template's `hooks/register.test.tsx` checks the template button, so it fails once you change the code. Replace it with this:

```tsx hooks/register.test.tsx theme={null}
import { expect, find, mount, press, test } from '@minimax/mcode-plugin-extension/testing';

import { register } from './register';

test('shows the call count, and the button fills it into an empty message box', async () => {
  // state overrides the defaults in defineState.
  const site = await mount({ register, site: 'above-prompt', state: { toolCalls: 3 } });
  expect(find(site, { text: '3 tool calls in this session' })).toBeDefined();

  await press(site, { label: 'Fill message box' });

  expect(
    site.effects.map((effect) => (effect.type === 'prompt.fill' ? effect.text : effect.type)),
  ).toEqual(['So far this session has made 3 tool calls.']);
});

test('does not overwrite existing text and tells the user', async () => {
  // composer.draft simulates a draft the user has half written.
  const site = await mount({
    register,
    site: 'above-prompt',
    composer: { draft: "I'm not done yet" },
  });

  await press(site, { label: 'Fill message box' });

  expect(
    site.effects.map((effect) => (effect.type === 'ui.toast' ? effect.text : effect.type)),
  ).toEqual(['The message box already has text, so it was left as is']);
});
```

The test sets the count directly through `state` and checks what the status band shows and what the button does. See [Test and troubleshoot](https://agent.minimax.io/docs/extension/testing.md) for more.

## Test

Tell the Agent:

```text theme={null}
Use the extension tool to test tool-counter
```

`test` first validates the package with the same rules as preview, then runs all tests. If a test fails or there are diagnostics, fix the code using the `fix` in each diagnostic and ask the Agent to test again until everything passes. See [Diagnostic codes](https://agent.minimax.io/docs/extension/errors.md) for what each code means.

## Preview

Tell the Agent:

```text theme={null}
Use the extension tool to preview tool-counter
```

The first preview shows a permission card:

* **Only this chat**: later previews in this session (including other plugins) won't ask again.
* **Always allow**: previews in all sessions won't ask again.

If you deny it, the conversation keeps a deny rule, so every later preview in this conversation is denied right away and the Agent won't try again. To preview, start a new conversation and ask the Agent to preview there.

Once you allow it, the extension loads into the current session right away and only works in that session.

## Try it

Ask the Agent to do something that calls tools, such as "show me which files are in the current folder". Each tool call in that turn adds one to the count in the status band.

Click "Fill message box" and the count appears in the message box. If the message box already has text, you see "The message box already has text, so it was left as is".

## Make changes

Once the preview is active, changes reload automatically and silently **at the end of each turn**, including newly added MCP servers, and you won't be asked again. File changes don't take effect in the middle of a turn.

* If the Agent changes the code, it loads when the turn ends.
* If you change files in your editor yourself, send a message and wait for that turn to end, or ask the Agent to `preview` again.

Session state survives a reload, so the count doesn't reset.

## Check diagnostics

When the extension doesn't behave as expected, tell the Agent:

```text theme={null}
Use the extension tool to inspect tool-counter and see what diagnostics there are
```

`inspect` returns three parts:

| Part | Contents |
| - | - |
| `source` | What validation saw, including registered observe events and the MCP servers used in `calls:` |
| `preview` | The version currently active. `stale` means files changed after it. `keptReload` means a reload was rejected and your changes didn't take effect, so fix its diagnostics first. `editorTypesFinding` means `.minimax-plugin/types/` couldn't be refreshed |
| `runtime` | Runtime diagnostics, `console` output, and disabled hooks |

A hook that fails or times out 3 times in a row is paused in this session. If the paused hook is a drawing and no other plugin still draws in the same place, the status band shows "Paused · this session" and "Retry". A paused observe hook shows no notice: in this example, if the `tool.call` hook is paused, the count just stops going up. Ask the Agent to `inspect` and look for disabled hooks under `runtime`. Once you've fixed it, preview again. See [Test and troubleshoot](https://agent.minimax.io/docs/extension/testing.md) to troubleshoot by symptom.

## Install

A preview only works in the current session. To run the extension in all sessions, tell the Agent:

```text theme={null}
Install tool-counter for all sessions
```

Installing copies the development folder to `<dataDir>/plugins/tool-counter/`, without `.minimax-plugin/types/`. Before copying, the Agent sends you a message listing what the extension will add: the sites it draws, the MCP servers in `calls:`, the commands for bundled MCP servers that will start as processes, and the registered observe events.

After install, the extension runs in all local sessions. Once the current session's preview matches the installed version, the preview steps aside for the installed version. Like other plugins, you disable or uninstall an installed extension in plugin management.

> [!NOTE]
>
> Installing means you trust the package, including any later changes to the installed copy. For day-to-day development, make changes in the development folder, check them with a preview, then install.

## Withdraw a preview

When you no longer want the preview, tell the Agent:

```text theme={null}
Use the extension tool to withdraw tool-counter
```

The status band and panel disappear right away, the module unloads, and bundled MCP servers stop. Your files and saved data stay, and you can bring it back with another `preview`. `withdraw` only handles previews. To disable or uninstall an installed extension, go to plugin management.

## Preview a package in another folder

`test` and `preview` read the development folder returned by `init` by default. To preview a package somewhere else, such as a folder you got from someone else, ask the Agent to pass `sourcePath` (an absolute path):

```text theme={null}
Use the extension tool to test tool-counter with sourcePath /Users/me/projects/tool-counter
```

The code in that folder wasn't written in this session, so:

* `test` shows a separate permission card asking whether to run the code in that folder. Once you allow it, this session stops asking about any extension test.
* `preview` needs permission as usual.

The Agent only writes files in the development folder and never changes the folder `sourcePath` points to.

## Next steps

> [card] [Interface: sites and elements](https://agent.minimax.io/docs/extension/interface.md)
>
> The status band height limit, opening and closing the panel, and the elements you can use.

> [card] [Events (hooks)](https://agent.minimax.io/docs/extension/events.md)
>
> What's in `tool.call`, `turn.complete`, and other events.

> [card] [Extension API](https://agent.minimax.io/docs/extension/api.md)
>
> Fill text into the message box, call MCP, and call the model.

> [card] [Test and troubleshoot](https://agent.minimax.io/docs/extension/testing.md)
>
> The test API and troubleshooting by symptom.
