# Potato Plugins for Custom Annotation and Display Types

Source: https://www.potatoannotator.com/docs/contributing/plugins

A Potato plugin is a Python package that adds annotation types or display types to Potato without changing Potato's own code. Each project turns a plugin on by naming the plugin under the top-level `plugins` key, and the plugin's types then work in `annotation_schemes` and `instance_display` like the built-in types. Plugins have been part of Potato since 2.12.0. The `counter` example in the Potato repository is a complete plugin and project, and the walkthrough on this page uses the example's code from the v2.14.0 release.

## Turning on an installed plugin

Potato finds plugins through the `potato.plugins` entry-point group of installed Python packages. `potato plugins` lists every installed plugin from package metadata, without importing any plugin code:

```bash
potato plugins
```

```text
counter              potato-plugin-example 0.1.0  (potato_plugin_example:register)

Turn one on with `plugins: [<name>]` in a config. `potato plugins <name>` loads it and lists its types.
```

Each line gives the plugin's entry-point name, the package and version that provide the plugin, and the function Potato calls to register the plugin's types. `potato plugins counter` imports one plugin and prints what the plugin registers. Use the command to check an install:

```text
counter: potato-plugin-example 0.1.0
  annotation types: counter
  display types:    word_count
  scripts:          counter.js
  styles:           counter.css
```

A config names the plugins to load as a list of entry-point names under `plugins`. The partial config below shows the blocks that involve the plugin:

```yaml
plugins:
  - counter

instance_display:
  fields:
    - key: text
      type: word_count          # a display type from the plugin
      label: Scene

annotation_schemes:
  - annotation_type: counter    # an annotation type from the plugin
    name: people
    description: How many people does the scene mention?
    min: 0
    max: 50
```

The `plugins` key takes a list of non-empty strings with no name repeated, and Potato rejects any other shape at validation. A `type: jspsych` page in `phases` has a separate `plugins` list. The jsPsych list names [jsPsych plugins](/docs/experiments/runtime-phases) for one page and is unrelated to the top-level key.

## Validation of plugin types

Plugins load at the start of config validation, before Potato checks any type name. The server, `potato validate`, and `potato preview` therefore see the same set of types. Validation applies the following rules to plugins:

- **Installed.** Each name under `plugins` must belong to an installed plugin. An unknown name fails validation with a message that lists the installed plugins.
- **Listed.** A config that uses a plugin's type must list the plugin. Potato enforces the rule because one process can load plugins for one config and then validate another. The design-time MCP server validates many configs in one process, so without the rule a config could pass there on a plugin that another config loaded, then fail when `potato start` runs the config in a fresh process. In a fresh process, the error for an unlisted plugin type in `annotation_schemes` ends with a hint. The hint names the plugin to add when the plugin's name equals the type name, and otherwise reads `If 'x' comes from a plugin, list it under plugins:; installed plugins: a, b, c`. An unlisted plugin display type gets the `Valid types are: ...` error with no hint. An unlisted plugin type in a phase file gets `'x' is not an annotation type`, also with no hint.
- **Unique names.** A plugin may not reuse the name of a built-in type or of another loaded plugin's type. A plugin that reuses a taken name registers none of the plugin's types.
- **Survey-phase files.** Questions in phase files (`phases: ... file:`) get the listed-plugin check and the scheme-key check, and each question's type must be built in or come from a listed plugin. Validation does not check a plugin's required fields in a phase file. A phase-file question of a listed plugin type therefore validates even when the question lacks a required field.
- **Scheme keys.** A scheme of a plugin type may carry the keys the plugin declares, plus the universal scheme keys. Potato logs any other key as an unrecognized config key, and `potato validate --strict` fails on the key.
- **Required fields.** In `annotation_schemes`, fields the plugin declares as required, beyond `name` and `description`, are checked at validation like the required fields of a built-in type.

Potato's checks stop short of plugin types in two places. First, Potato skips the `display_options` name check for a plugin display type. A misspelled display option on a plugin field therefore passes `--strict`. Second, editors that check configs against Potato's published JSON Schema (the `yaml-language-server` line at the top of the example configs) mark plugin types as unknown. The schema lists the built-in types only, and `potato validate` is the check that loads plugins.

The design-time MCP server (`potato mcp serve`) has a `list_plugins` tool for coding agents. With no argument, `list_plugins` reads package metadata and imports nothing, although a plugin that another config already loaded in the same process also shows its types. Given a plugin's name, the tool loads the named plugin, which runs the plugin's code inside the server process, and lists the plugin's types. A name that is not installed returns an error listing the installed plugins. The `list_annotation_types` and `list_display_types` tools give the plugin behind each type, with `null` for a built-in type.

## Plugin code and server permissions

A plugin is ordinary Python code that runs inside the Potato server process with the server's permissions. Plugin code can therefore read the data, the annotations, and the credentials the server can read. Install plugins only from sources you would trust with the same access as the Potato server itself. Potato limits what a config alone can do with two rules:

- **Only listed plugins load.** Installing a package changes nothing in a project whose config does not name the plugin.
- **Entry-point names only.** `plugins` takes entry-point names, never file paths or module names. A config cannot point Potato at code on disk, and editing a config therefore cannot run code that was never installed into the environment.

Potato serves static files only for plugins loaded in the server process, and only from each plugin's own static folder. In a normal server, the loaded plugins are the plugins the config lists. Flask's `send_from_directory` refuses any path that leaves the folder. A running server never unloads a plugin.

## Writing a plugin package

A plugin is a Python package with an entry point in the `potato.plugins` group. The entry-point name is the name a config lists under `plugins`. The example in [`examples/plugins/counter/plugin`](https://github.com/davidjurgens/potato/tree/v2.14.0/examples/plugins/counter/plugin) is laid out as follows:

```text
plugin/
├── pyproject.toml
└── potato_plugin_example/
    ├── __init__.py          # register(api)
    └── static/
        ├── counter.js
        └── counter.css
```

The example's `pyproject.toml` declares the entry point and installs the `static` folder as package data:

```toml
[build-system]
requires = ["setuptools>=64"]
build-backend = "setuptools.build_meta"

[project]
name = "potato-plugin-example"
version = "0.1.0"
description = "Example Potato plugin: a counter annotation type and a word-count display"
requires-python = ">=3.9"

[project.entry-points."potato.plugins"]
counter = "potato_plugin_example:register"

[tool.setuptools]
packages = ["potato_plugin_example"]

[tool.setuptools.package-data]
potato_plugin_example = ["static/*"]
```

The entry point can name a function, or a module that has a `register` function. Any other target fails to load with an error naming the entry point. Without the `package-data` table, a regular install can leave out the `static` folder, and the plugin fails to register with a `static folder not found` error.

### The register function

Potato imports the entry point when a config lists the plugin, then calls `register(api)` with a `PluginAPI` object. The API object has three methods:

| Method | What the method registers |
|---|---|
| `add_schema(name, generator, *, required_fields=("name", "description"), optional_fields=(), description="", supports_keybindings=False)` | An annotation type, with the generator that builds the scheme's HTML |
| `add_display(name, display)` | A display type, as an instance of a `BaseDisplay` subclass from `potato.server_utils.displays.base` |
| `add_assets(static_dir, *, scripts=(), styles=())` | A folder, relative to the folder of the module that defines `register`, served at `/plugin-static/<plugin>/`, and the scripts and styles in the folder to load on every page |

Potato registers nothing until `register` returns. If `register` raises an exception, or if any name the plugin uses is already taken, the plugin registers no types and validation reports the error. A plugin that fails halfway leaves no partial set of types behind. Registering one name twice in the same plugin, passing a generator that is not callable, and passing a display that is not a `BaseDisplay` instance each raise an error inside `register`.

### Annotation type generators

A generator takes the scheme's config as a dictionary and returns a tuple of the HTML and a list of keybindings, like the built-in generators in `potato/server_utils/schemas/`. List every config key the generator reads in `optional_fields`, because validation flags any other key on a scheme of the type. The universal scheme keys (e.g., `label_requirement` and `display_logic`) are accepted on a plugin type without being declared. Potato wraps the generator's HTML in the `display_logic` container itself, and conditional display therefore needs no code in the plugin.

The annotation page saves and restores an answer only from inputs the page already handles. Each input needs the class `annotation-input`, a `schema` attribute set to the scheme name, and a `label_name` attribute. `generate_element_identifier(scheme_name, label_name, element_type)` from `potato.server_utils.schemas.identifier_utils` builds the `id`, `name`, `schema`, and `label_name` values. The page saves checkbox, radio, text, textarea, range, select, number, and hidden inputs that carry the class. A range or hidden input is saved only after a change marks the input as modified. A plugin script that changes a hidden input's value therefore also sets the input's `data-modified` attribute. Email, date, and other input types are not saved.

A script that changes an input's value dispatches `input` and `change` events on the input, and the page saves the value when the events fire. To check that answers persist, answer an item, press **Next**, press **Previous**, and confirm the answer is still shown. A page refresh is not a test of saving, because browsers restore form values across a refresh even when nothing was saved.

### Display types

A display type is a subclass of `BaseDisplay`, registered as an instance. The subclass implements `render(field_config, data)` and returns the inner HTML for one field. Potato wraps the returned HTML in the standard field container and adds the field's `label`. The class attributes include `name`, `description`, `required_fields`, `optional_fields`, and `supports_span_target`, and `optional_fields` maps each option name to the option's default value.

### Scripts and styles

Potato resolves the `add_assets` folder against the folder of the module that defines `register`, with the working directory as the fallback. A `register` function in the package's `__init__.py`, as in the counter example, makes the package folder the base. Files named in `add_assets` load on every annotation and phase page, after `annotation.js`. A plugin script can therefore use the functions `annotation.js` defines. Each file is served at `/plugin-static/<plugin>/<file>?v=<package version>`. Bump the package version when a file changes. The version is part of each file's URL, and a new version makes browsers fetch the new copy. Only the plugins a project's config lists get their scripts and styles on the project's pages. Plugin CSS can use the design tokens defined in `potato/static/styles.css` (e.g., `--border` and `--space-sm`).

## Walkthrough of the counter example

The `counter` example adds one annotation type and one display type. In the example, the `counter` type shows a number input between a minus and a plus button, for counting things in an item such as the people in a scene. The `word_count` display shows a text field followed by the field's word count.

Clone the Potato repository at the v2.14.0 tag, install the example plugin in editable mode, and start the example project from the repository root:

```bash
git clone --branch v2.14.0 https://github.com/davidjurgens/potato.git
cd potato
pip install -e examples/plugins/counter/plugin
potato start examples/plugins/counter/config.yaml -p 8000
```

Open `http://localhost:8000`, sign in, and count the people in each scene. The project's config turns on the plugin, renders each item's `text` field with `word_count`, and puts a `counter` scheme beside an ordinary `radio` scheme:

```yaml
# yaml-language-server: $schema=https://potatoannotator.readthedocs.io/en/latest/schemas/potato-config.schema.json
# Needs the example plugin installed first:
#   pip install -e examples/plugins/counter/plugin
annotation_task_name: Plugin example - counting people
task_dir: .
output_annotation_dir: annotation_output/
data_files:
- data/scenes.jsonl
item_properties:
  id_key: id
  text_key: text
user_config:
  allow_all_users: true
  users: []
plugins:
- counter
instance_display:
  fields:
  - key: text
    type: word_count
    label: Scene
annotation_schemes:
- annotation_type: counter
  name: people
  description: How many people does the scene mention?
  min: 0
  max: 50
- annotation_type: radio
  name: setting
  description: Indoors or outdoors?
  labels:
  - indoors
  - outdoors
  - unclear
```

Check the project with Potato's validator before starting the server:

```bash
potato validate examples/plugins/counter/config.yaml --strict
```

The validator loads the plugin, checks both plugin types, and prints `OK — no issues found.` for the example config.

### The register function in the counter example

The `register` function in `potato_plugin_example/__init__.py` declares both types and the static files:

```python
def register(api):
    api.add_schema(
        "counter", generate_counter_layout,
        optional_fields=["min", "max", "step", "start"],
        description="A number with - and + buttons, for counting things in an item",
    )
    api.add_display("word_count", WordCountDisplay())
    api.add_assets("static", scripts=["counter.js"], styles=["counter.css"])
```

The `optional_fields` list makes `min`, `max`, `step`, and `start` the options a `counter` scheme reads. Potato logs any other key on a `counter` scheme as unrecognized, and `potato validate --strict` fails on a misspelling such as `maximum` with the suggestion `Did you mean: 'max'?`.

### The counter generator

The generator builds a form with a fieldset, the scheme's description as the legend, and a number input between two step buttons:

```python
def generate_counter_layout(annotation_scheme):
    return safe_generate_layout(annotation_scheme, _counter_layout)


def _counter_layout(scheme):
    name = escape(scheme["name"])
    ids = generate_element_identifier(scheme["name"], "count", "counter")
    low, high = int(scheme.get("min", 0)), scheme.get("max")
    step = int(scheme.get("step", 1))
    bounds = f'min="{low}" step="{step}"' + (f' max="{int(high)}"' if high is not None else "")
    html = f"""
    <form id="{name}" class="annotation-form counter-plugin" data-annotation-type="counter"
          data-schema-name="{name}" action="javascript:void(0)"
          data-annotation-id="{escape(str(scheme.get('annotation_id', '')))}"
          {generate_layout_attributes(scheme)}>
      <fieldset schema="{name}">
        <legend>{escape(scheme['description'])}</legend>
        <div class="counter-plugin-row" data-start="{int(scheme.get('start', low))}">
          <button type="button" class="counter-plugin-step" data-delta="-{step}"
                  aria-label="Decrease {name}">&minus;</button>
          <input class="{ids['schema']} annotation-input counter-plugin-value" type="number"
                 id="{ids['id']}" name="{ids['name']}" schema="{ids['schema']}"
                 label_name="{ids['label_name']}" {bounds} aria-label="{name} count">
          <button type="button" class="counter-plugin-step" data-delta="{step}"
                  aria-label="Increase {name}">+</button>
        </div>
      </fieldset>
    </form>
    """
    return html, []
```

`safe_generate_layout` runs the layout function inside the error handling Potato's built-in generators use. `generate_element_identifier` builds the input's identifiers from the scheme name and the label name `count`. Potato saves the number in each annotator's `user_state.json` under the scheme `people` and the label `count`. The `min` option defaults to 0, `step` to 1, and `start` to the value of `min`. A scheme without `max` has no upper bound. The generator returns an empty keybinding list.

### The counter script

`counter.js` makes the two buttons change the number:

```javascript
// Counter plugin: the - and + buttons change the number input beside them,
// then fire the events annotation.js listens for, so the value saves like
// any typed number.
(function () {
    function clamp(input, value) {
        var min = input.min === '' ? -Infinity : Number(input.min);
        var max = input.max === '' ? Infinity : Number(input.max);
        return Math.min(max, Math.max(min, value));
    }

    document.addEventListener('click', function (event) {
        var button = event.target.closest('.counter-plugin-step');
        if (!button) return;
        var row = button.closest('.counter-plugin-row');
        var input = row.querySelector('.counter-plugin-value');
        var current = input.value === '' ? Number(row.dataset.start || 0) : Number(input.value);
        input.value = String(clamp(input, current + Number(button.dataset.delta)));
        input.dispatchEvent(new Event('input', { bubbles: true }));
        input.dispatchEvent(new Event('change', { bubbles: true }));
    });
})();
```

The script listens for clicks on any step button on the page, keeps the new value between the input's `min` and `max`, and dispatches `input` and `change` events. The annotation page then saves the value like a number the annotator typed. An empty input counts up or down from the scheme's `start` value.

### The word-count display

`WordCountDisplay` is the display type:

```python
class WordCountDisplay(BaseDisplay):
    name = "word_count"
    description = "Text with its word count"
    optional_fields = {"label": None}

    def render(self, field_config, data):
        text = "" if data is None else str(data)
        words = len(text.split())
        return (f'<div class="word-count-text">{escape(text)}</div>'
                f'<div class="word-count-total">{words} word{"" if words == 1 else "s"}</div>')
```

The `render` method escapes the item's text before writing the text into the page, and counts words by splitting on whitespace. Potato adds the field's `label` when the method's HTML goes into the field container, and the example config sets the label to Scene.

## Limits of the plugin API

The plugin API registers annotation types, display types, and static files. A plugin cannot add an export format or an agreement metric through the API. Answers to a plugin scheme are saved in each annotator's `user_state.json` like the answers to a built-in scheme. The generic tabular exporters (CSV, TSV, JSONL, and Parquet) write plugin answers as `<scheme>.<label>` columns. Format-specific exporters such as COCO and CoNLL do not handle plugin types. Potato's agreement report at `/admin/iaa` picks a measure from each scheme's `annotation_type` and skips a type the report does not know. A plugin scheme therefore gets no agreement score in 2.14.0.

## Troubleshooting

Each message below comes from Potato's plugin loader or validator:

| Message | Cause |
|---|---|
| `plugin 'x' is not installed` | The package is not installed in the environment running Potato, or the package's entry point is in another group. `potato plugins` shows what is installed. |
| `plugin 'x' failed to import` | Importing the entry point raised an exception. The message ends with the error. |
| `raised while registering` | The plugin's `register` function failed. The message ends with the error. |
| `uses names that already exist` | A type name collides with a built-in type or with another plugin's type. Rename the type. |
| `static folder not found` | The folder passed to `add_assets` is missing. A `pyproject.toml` without the `package-data` table is one cause. |
| `annotation type 'x' comes from plugin 'y'; add 'y' to plugins` | The config uses a plugin type without listing the plugin. |

## Further reading

- [Annotation schemes](/docs/core-concepts/annotation-schemes), for the scheme keys every type shares
- [Instance display](/docs/core-concepts/instance-display), for `instance_display` fields and the built-in display types
- [Annotation types overview](/docs/annotation-types/overview), for the built-in types a plugin type sits beside
- [Quick Start with a Coding Agent](/docs/getting-started/quick-start-with-a-coding-agent), for `potato mcp serve`
- [Contributing](/docs/contributing/overview), for changes to Potato itself

For implementation details, see the [source documentation](https://github.com/davidjurgens/potato/blob/master/docs/advanced/plugins.md).
