Write a plugin
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
Section titled “Before you start”- Python 3.9 or later. The SDK needs no other package.
- A clone of strands-agents/stash. The SDK is at
integrations/plugin-sdk/python.
1. Write the plugin
Section titled “1. Write the plugin”This plugin searches a postmortem archive over HTTP. Save it as
/home/me/plugins/postmortems.py:
import jsonimport socketimport urllib.errorimport urllib.parseimport urllib.request
from stash_plugin import Failure, Plugin, Record
plugin = Plugin("postmortems", description="Postmortems of past incidents.")
@plugin.initializedef 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.searchdef 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()initializegets the source’ssettingsand the plugin’s environment. What it returns is thestatethat each other function gets first.- The plugin declares each method that has a function. Leave out what your store can’t do.
searchreturns records, or(record, score)pairs, best first.- Raise a
Failurefor an error that Stash can act on. RaiseFailure.throttledinstead of sleeping: Stash waits and sends the request again. printgoes to the daemon log. It can’t break the protocol.
2. Shape each record
Section titled “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 for every field and Paths
for the path rules.
3. Add the source
Section titled “3. Add the source”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 for its keys
and Local program environment
for each value shape.
4. Create the mount and search it
Section titled “4. Create the mount and search it”stash create ops --config stash.toml
attempt=1while :; 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 2done
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
Section titled “Serve more methods”A store that lists its records also uses @plugin.list and @plugin.get:
listreturns a page and the cursor of the next one, orNoneat the end.@plugin.planreturns what Stash loads when the mount starts. Without it, the mount loads nothing at start, and files come only fromsearchandget.listandsearchget a folder and filters only if your function takes thescopeandfiltersparameters. 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 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
serves a folder of Markdown files with list, get, search, and ingest.
Publish the plugin
Section titled “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:
[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
Section titled “Next steps”- Plugin source: each key of a
pluginsource. - Plugin protocol: the messages, for a plugin in another language.