You write a plugin when your agent needs a store that Stash has no kind for: a team wiki, a ticket archive, or another memory service. A plugin is a program that Stash starts with the mount. It speaks the plugin protocol on stdin and stdout, and the mount shows its records as files.

The Python SDK speaks the protocol for you. You write one function for each thing that your store can do.

## Before you start

-   Python 3.9 or later. The SDK needs no other package.
-   A clone of [strands-agents/stash](https://github.com/strands-agents/stash). The SDK is at `integrations/plugin-sdk/python`.

## 1\. Write the plugin

This plugin searches a postmortem archive over HTTP. Save it as `/home/me/plugins/postmortems.py`:

```python
import json
import socket
import urllib.error
import urllib.parse
import urllib.request

from stash_plugin import Failure, Plugin, Record

plugin = Plugin("postmortems", description="Postmortems of past incidents.")


@plugin.initialize
def start(settings, env):
    if "url" not in settings:
        raise Failure.validation("set settings.url")
    token = env.get("POSTMORTEMS_TOKEN", "").strip()
    if not token:
        raise Failure.validation("set env.POSTMORTEMS_TOKEN")
    return {"url": settings["url"], "token": token}


@plugin.search
def search(state, query, limit):
    url = f"{state['url']}/search?" + urllib.parse.urlencode({"q": query, "n": limit})
    request = urllib.request.Request(
        url, headers={"Authorization": f"Bearer {state['token']}"}
    )
    try:
        with urllib.request.urlopen(request, timeout=20) as answer:
            hits = json.load(answer)["hits"]
    except urllib.error.HTTPError as error:
        if error.code in (408, 425):
            raise Failure.timeout("the archive did not finish the search") from None
        if error.code == 429:
            raise Failure.throttled("the archive throttled the search") from None
        if error.code >= 500:
            raise Failure.unavailable("the archive is unavailable") from None
        if error.code in (401, 403):
            raise Failure.access_denied("the archive refused the token") from None
        raise Failure.other(f"the archive answered HTTP {error.code}") from None
    except urllib.error.URLError as error:
        if isinstance(error.reason, socket.timeout):
            raise Failure.timeout("the archive did not answer") from None
        raise Failure.unavailable("the archive is unavailable") from None
    except socket.timeout:
        raise Failure.timeout("the archive did not answer") from None
    return [
        Record(
            id=hit["id"],
            body=hit["text"],
            preview=hit["summary"],
        )
        for hit in hits
    ]


main = plugin.run

if __name__ == "__main__":
    main()
```

-   `initialize` gets the source’s `settings` and the plugin’s environment. What it returns is the `state` that each other function gets first.
-   The plugin declares each method that has a function. Leave out what your store can’t do.
-   `search` returns records, or `(record, score)` pairs, best first.
-   Raise a `Failure` for an error that Stash can act on. Raise `Failure.throttled` instead of sleeping: Stash waits and sends the request again.
-   `print` goes to the daemon log. It can’t break the protocol.

## 2\. Shape each record

Give each `Record` a stable `id` and its file text in `body`. The example leaves `dir` and `name` out, so external values never become paths. See [Records](/docs/user-guide/stash/reference/plugin-protocol/index.md#records) for every field and [Paths](/docs/user-guide/stash/reference/plugin-protocol/index.md#paths) for the path rules.

## 3\. Add the source

```toml
mount_point = "/tmp/ops-context"

[sources.postmortems]
kind = "plugin"
description = "Postmortems of past incidents"
plugin = "postmortems"
command = ["python3", "/home/me/plugins/postmortems.py"]
settings = { url = "https://postmortems.example.com/api" }

[sources.postmortems.env]
POSTMORTEMS_TOKEN = { file = "/home/me/.config/stash/postmortems-token" }
PYTHONPATH = "/home/me/stash/integrations/plugin-sdk/python/src"
```

The plugin gets only a small part of the daemon’s environment and the variables in `env`. Use a file or command-backed value for a secret, so the config never holds it. See the [`plugin` source](/docs/user-guide/stash/reference/configuration/index.md#plugin) for its keys and [Local program environment](/docs/user-guide/stash/reference/configuration/index.md#local-program-environment) for each value shape.

## 4\. Create the mount and search it

```sh
stash create ops --config stash.toml

attempt=1
while :; do
  status=$(stash status ops) || exit 1
  printf '%s\n' "$status"
  case "$status" in
    *"state: ready"*) break ;;
    *"state: failed"*) exit 1 ;;
  esac
  if [ "$attempt" -ge 60 ]; then
    printf '%s\n' "The mount did not become ready within two minutes." >&2
    exit 1
  fi
  attempt=$((attempt + 1))
  sleep 2
done

stash search ops "checkout latency" --path "/plugin/postmortems/*"
```

The loop stops when the mount is ready or failed. It also stops after two minutes. Each search hit is a file below `/tmp/ops-context/plugin/postmortems/`.

## Serve more methods

A store that lists its records also uses `@plugin.list` and `@plugin.get`:

-   `list` returns a page and the cursor of the next one, or `None` at the end.
-   `@plugin.plan` returns what Stash loads when the mount starts. Without it, the mount loads nothing at start, and files come only from `search` and `get`.
-   `list` and `search` get a folder and filters only if your function takes the `scope` and `filters` parameters. Without them, the SDK refuses such a request.

To take the agent’s turns, serve `@plugin.ingest`, and set `write.trajectory = {}` on the source. `ingest` can get the same batch again with the same `token`, so write it one time.

See the [plugin protocol](/docs/user-guide/stash/reference/plugin-protocol/index.md) for the parameters and results of each method.

After `initialize`, the functions run at the same time, on up to 8 threads. Keep the state safe for more than one thread.

[`examples/notes.py`](https://github.com/strands-agents/stash/blob/833198a2b91f6490291149d06b4daac8de0727c8/integrations/plugin-sdk/python/examples/notes.py) serves a folder of Markdown files with `list`, `get`, `search`, and `ingest`.

## Publish the plugin

Name the package and its program `stash-source-<name>`. For a source with no `command`, Stash runs `stash-source-<plugin>` from the daemon’s `PATH`:

```toml
[project]
name = "stash-source-postmortems"
dependencies = ["strands-stash-plugin"]

[project.scripts]
stash-source-postmortems = "stash_source_postmortems:main"
```

A user installs it with `pipx install stash-source-postmortems`, and leaves `command` out of the source.

## Next steps

-   [Plugin source](/docs/user-guide/stash/sources/plugin/index.md): each key of a `plugin` source.
-   [Plugin protocol](/docs/user-guide/stash/reference/plugin-protocol/index.md): the messages, for a plugin in another language.