Skip to main content
Commands, package names, and image names on this page come from the open-source project that Mibyan Desktop is built on, and can differ from the Mibyan Desktop installer. For the supported Mibyan install and update path, see Install and update.
This guide walks through building a complete Mibyan plugin from scratch. By the end you’ll have a working plugin with multiple tools, lifecycle hooks, shipped data files, and a bundled skill — everything the plugin system supports.
Not sure which guide you need?Mibyan has several distinct pluggable interfaces — some use Python register_* APIs, others are config-driven or drop-in directories. Use this map first:See the full Pluggable interfaces table for a consolidated view of every extension surface including config-driven (TTS, STT, MCP, shell hooks) and drop-in directory (gateway hooks) styles.
Third-party-product plugins ship standalone — not into the core treePlugins that integrate someone else’s product or project — observability/metrics backends, vendor SaaS connectors, analytics dashboards, paid-service tie-ins — are built and distributed as standalone plugin repos, not merged into NousResearch/hermes-agent. Users install them into ~/.mibyan/plugins/ or via a pip entry point; everything in this guide works the same way from a standalone repo. This is a coupling-and-maintenance decision (the core moves fast and we don’t own your backend), not a quality bar — a plugin can be excellent and still belong in its own repo. Promote it in the Nous Research Discord #plugins-skills-and-skins channel. See CONTRIBUTING.md for the policy.

Portable Agent Plugins v1 packages

Mibyan can also install and load directory packages that target the Agent Plugins v1.0.0 format. This is a compatibility adapter for the portable components Mibyan already owns. It does not replace native plugin.yaml plus register(ctx) plugins.
Install and activate a portable package through the normal workflow:
Portable packages are disabled after installation unless you explicitly enable them. An enabled package may provide immediate skills/*/SKILL.md directories and stdio MCP servers from root mcp.json. Skills are read-only, namespaced, and loaded through skills_list plus skill_view. MCP commands are passed as one executable token with a separate argument list, never through a shell. Use skills_list to discover the full qualified skill name. Portable skill namespaces have the deterministic form agent-plugin-<slug>-<hash>, derived from the discovered plugin key so sanitized names cannot collide. A portable package’s MCP servers keep the names their mcp.json gives them, the same rule as a user’s own mcp_servers block, so the model-facing mcp__<server>__<tool> name keeps the tool verb inside the 64-character provider cap. A duplicate server name is a load-time conflict: a config.yaml server wins over a package, and the first-loaded package wins over the next; the loser is skipped with a warning naming both. Mibyan validates plugin.json, Agent Skills frontmatter, fixed component locations, mcp.json, resolved paths, and symlink containment locally. It does not fetch JSON schemas while loading a package. A bad skill or MCP entry is skipped at its own boundary when valid sibling components can still load. PLUGIN_ROOT points to the resolved package root. PLUGIN_DATA points to a profile-scoped writable directory managed by Mibyan. Values declared in portable MCP env are visible package data, not a secret storage mechanism. Do not place credentials in mcp.json. The current portable subset supports stdio and Streamable HTTP MCP entries. Portable streamable-http entries are routed through Mibyan’ existing native remote MCP client (the same runtime that powers URL-based mcp_servers config), with the v1 boundary rules enforced: the URL must be absolute http(s) with no user information or fragment, plain HTTP is accepted only for localhost/loopback hosts, and configured headers are never forwarded across a cross-origin redirect. Legacy sse entries are reported and skipped. Agent Plugins v1 does not define trust, permissions, provenance, or a sandbox. Enabling a package grants its instructions and local executable the same full-trust posture as other installed Mibyan plugins. The rendered specification currently labels v1.0.0 a Working Draft, while the versioned specification repository records it as Published. Mibyan keys behavior on the canonical v1.0.0 schema identifiers and normative text, not either mutable status label. This is an explicit supported subset, not a claim of full Agent Plugins conformance.

Native plugin compatibility contract

Native plugin.yaml plus register(ctx) plugins are protected by behavior, not by one global plugin API number. Mibyan does not expose a PLUGIN_API_VERSION, require a manifest-wide api: match, or attach an API version to unrelated values. A plugin that uses a documented behavior should continue to work after a normal Mibyan upgrade. The compatibility rules are:
  • Evolve additively. Documented PluginContext methods are not removed or renamed. New parameters are optional, have defaults, and should be keyword-only. Existing return fields are not removed or silently retyped.
  • Hook payloads are keyword payloads. New hook data is added as keyword fields, never by changing the meaning or position of an existing field. Mibyan inspects callback signatures: a legacy callback receives the fields it declares, while a callback with **kwargs receives the complete current payload. New plugins should accept **kwargs so they can opt into additive data without another signature change.
  • Manifests are open to additions. Unknown plugin.yaml fields are ignored. Older Mibyan releases can therefore load a plugin whose manifest contains metadata introduced by a newer release, provided the plugin code itself uses supported runtime behavior.
  • Provider interfaces grow through defaults. New provider methods have a default implementation. New callback context is optional and forwarded only when signature inspection shows that a provider accepts it. Adding an abstract method or an unconditionally forwarded argument requires a migration window rather than a flag-day signature change.
  • Version the contract that crosses a boundary. A capability may carry its own schema version when it defines a wire payload or persisted format (for example, observer payloads or secret-source state). Keep fields additive within that local schema. Persisted plugin state and config must remain readable, or ship an explicit migration; resumed sessions written by the old format must still replay. Do not add version literals to unrelated callback or context values.
The contract covers documented surfaces only. Replacing or wrapping core functions, methods, module attributes or private tables at runtime (assigning AIAgent.<method>, setattr on a Mibyan module, writing into sys.modules or a core dict) is not a supported extension point. It breaks whenever the internals move, and it collides with every other plugin patching the same seam. The plugin catalog refuses it at admission (mibyan plugins validate, no core override check). If a public hook you need is missing, open an issue describing it.

Deprecation policy

A documented native plugin behavior may be deprecated only with all of the following:
  1. a replacement and migration instructions in the plugin guide and release notes;
  2. a warning emitted at most once per process, naming the replacement and the earliest removal release;
  3. support for the old behavior through at least two subsequent minor releases; and
  4. behavior-based compatibility coverage for both the legacy path and the replacement throughout that window.
Removal after the window must include any migration needed for persisted data or resumable sessions. In practice, additive aliases and adapters are preferred to removal. Mibyan enforces this contract with frozen external-plugin fixtures discovered from an isolated mibyan_HOME. Those tests load and invoke the plugin through PluginManager; they assert real registration and callback outcomes rather than internal symbol lists or source-code shape.

Sep 2026 module decomposition: old import paths removed

Mibyan’s internals were split into <stem>_<topic> sibling modules in Sep 2026 (PR #102117). Internal import paths were never part of the plugin contract above. A temporary compatibility layer kept the old paths resolving until 2026-09-14; it has been removed, so a plugin that still imports an old path fails to load with an ImportError (the reason shows in mibyan plugins list). To fix such a plugin, import the name from the module that defines it now, or better, use ctx and the documented ABCs instead of internals. The full old-to-new map is the COMPAT_MANIFEST.md from the last commit that shipped the layer.

What you’re building

A calculator plugin with two tools:
  • calculate — evaluate math expressions (2**16, sqrt(144), pi * 5**2)
  • unit_convert — convert between units (100 F → 37.78 C, 5 km → 3.11 mi)
Plus a hook that logs every tool call, and a bundled skill file.

Step 1: Create the plugin directory

Create a directory and continue with Step 2:

Validate with Plugin Doctor

mibyan plugins doctor [path-or-id] runs the same directory discovery, manifest parser, namespaced import, register(ctx), hook registry, and tool registry used by Mibyan itself. It reports invalid hook names, callbacks that do not accept **kwargs, registration failures, and drift between declared and registered tools/hooks. Pass --ci to exit non-zero on an error:
Doctor uses a temporary mibyan_HOME, restores plugin registration state after the check, and blocks direct Python socket connections to catch accidental network access while registration runs. This is not a sandbox: plugin code still executes in-process with the current user’s permissions and can spawn subprocesses, so only run Doctor on code you trust enough to import.

Step 2: Write the manifest

Create plugin.yaml:
This tells Mibyan: “I’m a plugin called calculator, I provide tools and hooks.” The provides_tools and provides_hooks fields are lists of what the plugin registers. Optional fields you could add:

Declaring capabilities

If your plugin needs a privileged host surface — overriding a built-in tool, picking the model for ctx.llm calls, etc. — declare it in capabilities:. At install/enable time the user sees the list and consents once; if a later version adds a capability, the update flow asks again for just the addition. Undeclared or unconsented capabilities are simply off (fail closed), so probe before using them and degrade gracefully:
Known capability ids: tools.override, llm.provider_override, llm.model_override, llm.agent_id_override, llm.profile_override, llm.task_override (see mibyan_cli/plugin_capabilities.py for the canonical registry). Unknown ids are ignored. The older per-capability config keys (plugins.entries.<id>.allow_tool_override, …) still work but are deprecated — declare capabilities instead so users get a single, auditable consent screen. Capabilities are consent + audit, not a sandbox: they gate host API surfaces, nothing more. Pip-distributed plugins have no plugin.yaml directory once installed, so declare capabilities in distribution metadata instead, via the companion mibyan_agent.plugin_capabilities entry-point group. Each declaration is named <plugin-id>.<capability-id> and points at the same object as your mibyan_agent.plugins entry point:
Mibyan reads these from installed metadata without importing your code, so mibyan plugins capabilities and the consent flow stay accurate for pip installs.

Manifest v2 reference

plugin.yaml also supports an additive v2 schema (#64165). Every field is optional; a manifest without manifest_version is a v1 manifest and stays fully supported forever. Unknown fields never break loading — they are ignored with a warning (forward compatibility), and a manifest_version newer than this Mibyan understands still loads with a warning.
Shared dependency admissionPlugin installation requests Python dependency consent. Enabling the plugin prepares its requirements with core dependencies, extras, and enabled plugins through PM. Pack enables use the same admission transaction. Reinstalling an active plugin requests consent against its staged declaration before publication. A refusal preserves the installed plugin and selected environment.The installer and PM admission reject unsupported manifest_version values and unmet requires_mibyan constraints before publication.

Python dependencies

A directory plugin can bring its own PyPI packages. Declare them either in the manifest (python_dependencies, above) or, preferably, in a pyproject.toml next to plugin.yaml:
When both exist the pyproject.toml wins. What Mibyan does with them:
  • Install / enable — PM resolves core, selected extras, and the enabled plugin union across every profile sharing the dependency home, including custom mibyan_HOME roots. A new plugin is downloaded disabled; Python dependency consent precedes enablement. pyproject.toml takes precedence over python_dependencies and legacy pip_dependencies.
  • Atomic publication — PM prepares a fresh environment generation before publishing an enablement or an active plugin replacement. Resolution, download, or build failure preserves the previous environment and plugin selection; no existing plugin is sacrificed.
  • Updates retain the union — mibyan update includes enabled plugins while preparing its new generation. There is no post-update pip reinstall. mibyan plugins update prepares active replacements before swapping their code and dependency generation together.
  • Requirement hygiene — malformed PEP 508 requirements are refused. Environment markers remain intact for the target interpreter to evaluate. mibyan-agent self-dependencies are omitted because the checkout supplies Mibyan. Direct-URL requirements are not managed; use a plugin-owned external runtime for them.
  • --no-deps downloads a new plugin without dependency consent and leaves it disabled, even with --enable. It cannot bypass PM admission when replacing an active plugin.
  • python_runtime: external keeps a sidecar’s dependencies out of the shared union. Mibyan does not install that Python runtime or modify its declaration.
  • Nothing to load is an error — mibyan plugins validate rejects plugin.yaml without __init__.py, desktop/plugin.js, or plugin.json beside it. Pip-layout packages need a directory-plugin wrapper.
  • security.allow_lazy_installs: false blocks on-demand acquisition. Explicit dependency consent and explicit enablement authorize PM preparation; discovery never installs.
mibyan_HOME/plugins/ survives mibyan update and Desktop updates: the updater only rebuilds the venv and the checkout, never the home directory.

Dependency security policy

Mibyan quarantines its own dependencies: the checkout’s [tool.uv] exclude-newer = "14 days" keeps a freshly published release of any package Mibyan itself depends on out of mibyan update and the built-in lazy installs for two weeks, so a hijacked upload is caught upstream before it reaches users. That quarantine does not apply to your plugin’s dependencies. When Mibyan resolves your plugin into its environment, the cutoff stays on the packages Mibyan itself locks and nowhere else, so a plugin can floor on a release published yesterday and install today — and the plugin’s author, not Mibyan, is responsible for what that pulls in. (A plugin that needs a newer version of a package Mibyan itself depends on still waits out that package’s window.) Set your own policy and hold yourself to it. Strongly recommended:
  • Upper bounds on every dependency — >=floor,<next_major for stable packages, >=0.29,<0.32 for pre-1.0 ones. A bare >=X.Y adopts every future release unreviewed.
  • Floor on the oldest API-compatible version, not the release of the week. A floor on a fresh wheel forces every installer onto it the day it appears; >=old,!=broken,<next keeps the wide range and skips the one bad release.
  • Adopt a new-release quarantine of your own — wait ~14 days before floors move to a new release, and resolve with uv --exclude-newer "14 days" (or UV_EXCLUDE_NEWER) in your own CI so the lock you test is the one users get.
  • Pin your lock, review your bumps. Treat a dependency bump as a code change: read the upstream diff, then re-pin.
The plugin catalog review reads your dependency list at the pinned SHA (plugin.yaml or pyproject.toml) and flags bare floors and missing bounds; an entry is not held for a floor that is merely recent.

Step 3: Write the tool schemas

Create schemas.py — this is what the LLM reads to decide when to call your tools:
Why schemas matter: The description field is how the LLM decides when to use your tool. Be specific about what it does and when to use it. The parameters define what arguments the LLM passes.

Step 4: Write the tool handlers

Create tools.py — this is the code that actually executes when the LLM calls your tools:
Key rules for handlers:
  1. Signature: def my_handler(args: dict, **kwargs) -> str
  2. Return: Always a JSON string. Success and errors alike.
  3. Never raise: Catch all exceptions, return error JSON instead.
  4. Accept **kwargs: Mibyan injects context keywords (task_id, session_id, user_task, parent_agent, …) and only forwards the ones your signature names, so def handler(args) works; **kwargs is how you opt into the full, additively growing context.

Step 5: Write the registration

Create __init__.py — this wires schemas to handlers:
What register() does:
  • Called exactly once at startup
  • ctx.register_tool() puts your tool in the registry — the model sees it immediately
  • ctx.register_hook() subscribes to lifecycle events
  • ctx.register_cli_command() registers a CLI subcommand (e.g. mibyan my-plugin <subcommand>)
  • ctx.register_command() registers an in-session slash command (e.g. /myplugin <args> inside CLI / gateway chat) — see Register slash commands below
  • ctx.dispatch_tool(name, arguments) — call any other tool (built-in or from another plugin) with the parent agent’s context (approvals, credentials, task_id) wired up automatically. Useful from slash-command handlers that need to invoke terminal, read_file, or any other tool as if the model had called it directly.
  • ctx.get_config() / ctx.set_config() access only this plugin’s settings namespace; ctx.state stores plugin-owned runtime data under the active profile.
  • If this function crashes, the plugin is disabled but Mibyan continues fine
dispatch_tool example — a slash command that runs a tool:
The dispatched tool goes through the normal approval, redaction, and budget pipelines — it’s a real tool invocation, not a shortcut around them.

Store settings and runtime state

Use plugin-relative config keys for user-visible behavior. Mibyan resolves them under plugins.entries.<plugin-id>.settings and rejects global, cross-plugin, and traversal paths:
Use ctx.state for plugin-owned cursors, caches, and deduplication data rather than placing runtime bookkeeping in config.yaml:
State is profile-scoped, atomically replaced, safe across concurrent writers, and limited to 10 MiB per plugin. Portable packages share the same directory as their PLUGIN_DATA; native plugins receive a collision-resistant, Windows-safe namespace. Malformed existing state is reported and preserved. Config and state have different owners: settings are user-visible behavior in config.yaml, while state is plugin-owned runtime data under <mibyan_HOME>/plugin-data/. Neither API exposes another plugin’s namespace.

Settings form in the Desktop

Every key you declare in the manifest’s config_schema renders as a field in the Desktop app’s Capabilities → Plugins tab (the gear on the plugin’s row). No Desktop code is needed: the backend’s plugins.manage list returns the schema plus each key’s current value, and saving writes through the same writer as ctx.set_config(), so plugins.entries.<id>.settings.<key> is what your plugin reads back. The form is table-driven by type: Every entry also accepts label (shown instead of the key), description (help text under the field), default and required.
Secrets never touch config.yaml. A secret field carries only the .env name and whether a value is set; the Desktop stores the value through the same credential route as provider API keys (PUT /api/env), and your plugin reads it with os.environ.get("MY_PLUGIN_API_KEY") — exactly like a requires_env entry. The plugins.manage settings action refuses secret keys and any value whose type or choices disagree with the schema.

Step 6: Test it

Start Mibyan:
You should see calculator: calculate, unit_convert in the banner’s tool list. Try these prompts:
Check plugin status:
Output:

Debugging plugin discovery

If your plugin doesn’t show up — or shows up but isn’t loading — set mibyan_PLUGINS_DEBUG=1 to get verbose discovery logs on stderr:
You’ll see, for every plugin source (bundled, user, project, entry-points):
  • which directories were scanned and how many manifests each yielded
  • per manifest: resolved key, name, kind, source, on-disk path
  • skip reasons: disabled via config, not enabled in config, exclusive plugin, no plugin.yaml, depth cap reached
  • on load: the plugin being imported, plus a one-line summary of what register(ctx) registered (tools, hooks, slash commands, CLI commands)
  • on parse failure: a full traceback for the exception (YAML scanner errors, etc.)
  • on register() failure: a full traceback pointing at the line in your __init__.py that raised
The same logs are always written to ~/.mibyan/logs/agent.log at WARNING level (failures only) and DEBUG level (everything) when the env var is set. So if you can’t run with the env var (e.g. from inside the gateway), tail the log file instead:
Common reasons a plugin doesn’t appear:
  • Not enabled in config — plugins are opt-in. Run mibyan plugins enable <name> (the name comes from the plugins list output, which can be <category>/<plugin> for nested layouts).
  • Wrong directory layout: Native packages use ~/.mibyan/plugins/<plugin-name>/plugin.yaml (flat) or one category level. Portable packages use root plugin.json in the same locations. Anything deeper is ignored.
  • Missing __init__.py: Native packages need both plugin.yaml and __init__.py with a register(ctx) function. Portable packages do not import Python and do not require __init__.py.
  • Wrong kind — gateway adapters need kind: platform in their manifest. Memory providers are auto-detected as kind: exclusive and routed through the memory.provider config instead of plugins.enabled.

Your plugin’s final structure

Four files, clear separation:
  • Manifest declares what the plugin is
  • Schemas describe tools for the LLM
  • Handlers implement the actual logic
  • Registration connects everything

What else can plugins do?

Ship data files

Put any files in your plugin directory and read them at import time:
That’s for files you ship. State you write is different — see the next section.

Store durable state

Never write runtime state into your plugin directory: that’s the install tree, and mibyan plugins update / remove git-pull or delete it — your users’ data dies with it. The sanctioned home is the per-plugin data root, which survives both and follows the active profile:
One directory per plugin means every plugin’s data is inspectable in one predictable place. Secrets don’t belong here — credential reads go through the standard .env / secret-scope path like everywhere else.

Bundle skills

Plugins can ship skill files that the agent loads via skill_view("plugin:skill"). Register them in your __init__.py:
The agent can now load your skills with their namespaced name:
Key properties:
  • Plugin skills are read-only — they don’t enter ~/.mibyan/skills/ and can’t be edited via skill_manage.
  • Plugin skills are not listed in the system prompt’s <available_skills> index — they’re opt-in explicit loads.
  • Bare skill names are unaffected — the namespace prevents collisions with built-in skills.
  • When the agent loads a plugin skill, a bundle context banner is prepended listing sibling skills from the same plugin.
Legacy patternThe old shutil.copy2 pattern (copying a skill into ~/.mibyan/skills/) still works but creates name collision risk with built-in skills. Prefer ctx.register_skill() for new plugins.

Ship a language pack

A plugin can add a UI language or override the wording of an existing one for every surface at once — Python (agent.i18n.t(): approval prompts, gateway replies, tool verbs, tips), the mibyan --tui interface and the Desktop app. Declare provides_locales and ship the YAML; no Python is needed:
When provides_locales is declared the loader calls ctx.register_locale_dir(<plugin>/locales) before register() (a manifest-only pack with no __init__.py loads like a manifest-only Desktop plugin). Catalogs are layered and partial: pack → user overlay (<mibyan_HOME>/locales/) → bundled → English → key; a pack only needs the keys it changes, and the last pack loaded wins per key. Core values keep English’s named {placeholders}; TUI/Desktop entries whose English value is a function are written as strings with positional {0}, {1} placeholders. Plugins with code can register programmatically — the handles are PluginRegistrations, so unloading the plugin removes the layer, and registration never changes display.language:
mibyan plugins validate checks each declared id has a parseable, text-only locales/<id>.yaml (a non-text leaf is an error) and warns with the names of keys absent from the English catalog of that surface. Renderers fetch the pack layer through the i18n.languages / i18n.catalog RPCs. User-facing guide: Language Packs.

Gate on environment variables

If your plugin needs an API key:
If WEATHER_API_KEY isn’t set, the plugin is disabled with a clear message. No crash, no error in the agent — just “Plugin weather disabled (missing: WEATHER_API_KEY)”. When users run mibyan plugins install, they’re prompted interactively for any missing requires_env variables. Values are saved to .env automatically. For a better install experience, use the rich format with descriptions and signup URLs:
Both formats can be mixed in the same list. Already-set variables are skipped silently.

Lazy-install optional Python dependencies

For an SDK covered by a Mibyan project extra, use pm.ensure_import at the operation that needs it. Use pm.available for a read-only availability check. Do not install dependencies from a frequently polled check_fn. This example requests the existing bedrock extra:
The argument is a pyproject.toml extra name. It is not an arbitrary package specification or a plugin-qualified key. The old LAZY_DEPS registry and FeatureUnavailable exception no longer exist. If a new environment is selected, the helper can report a required restart. Return that error instead of importing from a second environment inside the running process. Already available dependencies need no installation, even when security.allow_lazy_installs is false. For a directory plugin’s own Python dependencies, declare dependencies under [project] in its pyproject.toml. Without an authored project file, PM combines legacy pip_dependencies and python_dependencies lists from plugin.yaml or plugin.yml. Old PM-generated project files do not override these lists. Consent, workspace membership, and currency checks use the same declaration. PM prepares their dependencies together with core requirements before enabling the plugin. The generated workspace does not rewrite the plugin directory or the shipped lockfile. Dependency conflicts refuse admission and preserve the previous selection. PM does not automatically disable other plugins. Dependencies installed manually with pip are not durable PM declarations. A later environment replacement need not retain them. Wrapper plugins whose Python runtimes remain outside PM can use the memory-provider survival contract. See Package management for the runtime layout and lazy-install policy.

Thread-safe lazy singletons

Plugins often cache an expensive object — an SDK client, an HTTP session, a connection pool — in a module-level variable built on first use:
This is a footgun. Mibyan runs multiple threads in one process (delegated tool calls, background workers, the self-improvement fork), so two threads can hit get_client() before _client is set, both pass the is not None check, both run the expensive build, and the second write clobbers the first — leaking whatever resource the loser opened (connection, file handle, background thread). Don’t hand-roll the lock. Use the helpers in plugins/plugin_utils.py:
Both serialize concurrent first calls with double-checked locking and run the factory at most once. If the factory raises, nothing is cached and the next call retries. The honcho memory plugin (plugins/memory/honcho/client.py) is the reference consumer.
Rule of thumb: any time you write global _something followed by a is None check and a build, reach for one of these instead.

Conditional tool availability

For tools that depend on optional libraries:

Overriding a built-in tool

To replace a built-in tool with your own implementation (e.g. swap the default browser tool for a headed-Chrome CDP backend, or replace web_search with a custom corporate index), pass override=True:
Without override=True, the registry rejects any registration that would shadow an existing tool from a different toolset — this prevents accidental overwrites. Overriding a built-in tool additionally requires the operator to opt in via plugins.entries.<plugin_id>.allow_tool_override: true in config.yaml; without that gate, register_tool(override=True) raises PluginToolOverrideError. The override is logged so it’s auditable in ~/.mibyan/logs/agent.log. Plugins load after built-in tools, so the registration order is correct: your handler replaces the built-in one. Non-bundled plugins also need an operator grant. For any plugin that does not ship with Mibyan core (user, project, or pip source), override=True against an existing built-in tool additionally requires a per-plugin opt-in in config.yaml:
Without the grant, ctx.register_tool(..., override=True) raises PluginToolOverrideError; since register() exceptions are caught by the loader, the plugin is disabled and Mibyan continues. The gate exists because an enabled plugin that silently replaces a privileged built-in like shell_exec or write_file could intercept everything the model routes through it. Bundled plugins are exempt: an override there is a maintainer decision. If config cannot be loaded, the gate fails closed. You normally never edit this key by hand. mibyan plugins enable <name> asks whether to grant the capability only when the plugin’s manifest declares it under capabilities: (the consent screen, defaulting to no); a plugin that declares no capabilities is enabled without any grant prompt. The --allow-tool-override / --no-allow-tool-override flags set or revoke the grant explicitly in either case, for scripted installs or for pre-authorizing a plugin that has not adopted the manifest block. The same grant also gates deregister(): without it, a plugin cannot remove a tool it does not own (which would otherwise be a way around the override check).

Register multiple hooks

Hook reference

Each hook is documented in full on the Event Hooks reference — callback signatures, parameter tables, exactly when each fires, and examples. Here’s the summary: Most hooks are fire-and-forget observers — their return values are ignored. The exceptions are pre_llm_call, which can inject context into the conversation, and pre_tool_call, which can return a block/approve directive. All callbacks should accept **kwargs for forward compatibility. If a hook callback crashes, it’s logged and skipped. Other hooks and the agent continue normally. The kanban lifecycle hooks fire after the board DB change commits, so a callback always sees durable state and can never hold the SQLite write lock. Because kanban workers run as separate mibyan -p <profile> chat -q subprocesses, kanban_task_claimed fires in the dispatcher process while kanban_task_completed / kanban_task_blocked fire in the worker process — hook in the dispatcher to observe every transition centrally, or in the worker for per-task in-session context. The API request hooks are observers for the raw provider request, one level below the per-turn pre_llm_call / post_llm_call pair: a single turn that calls tools makes several API requests, and these hooks fire around each one. They exist for observability plugins (tracing, cost accounting, latency dashboards). The request and response kwargs are sanitized, size-capped JSON views of the provider payload (sensitive keys redacted, long strings truncated, SDK objects normalized), and usage is a plain token-summary dict. Every payload carries the correlation fields turn_id, api_request_id, task_id, session_id, and api_call_count, so a plugin can stitch requests, tool calls, and turns together. api_request_error fires when a provider call raises and adds status_code, retry_count / max_retries, retryable, reason, and an error dict with type and message.

pre_llm_call context injection

This is the only hook whose return value matters. When a pre_llm_call callback returns a dict with a "context" key (or a plain string), Mibyan injects that text into the current turn’s user message. This is the mechanism for memory plugins, RAG integrations, guardrails, and any plugin that needs to provide the model with additional context.

Return format

Any non-None, non-empty return with a "context" key (or a plain non-empty string) is collected and appended to the user message for the current turn.

Oversized-context spill

Per-hook context is capped at 10,000 characters by default. Anything above the cap is written to $mibyan_HOME/hook_outputs/<session_id>/<uuid>.txt and replaced with a head/tail preview plus the saved path. The model can read the full content via read_file or terminal if it genuinely needs it. This keeps a runaway plugin from inflating every subsequent turn’s prompt and blowing out the prompt cache prefix. Tune in config.yaml:

How injection works

Injected context is appended to the user message, not the system prompt. This is a deliberate design choice:
  • Prompt cache preservation — the system prompt stays identical across turns. Anthropic and OpenRouter cache the system prompt prefix, so keeping it stable saves 75%+ on input tokens in multi-turn conversations. If plugins modified the system prompt, every turn would be a cache miss.
  • Ephemeral — the injection happens at API call time only. The original user message in the conversation history is never mutated, and nothing is persisted to the session database.
  • The system prompt is Mibyan’s territory — it contains model-specific guidance, tool enforcement rules, personality instructions, and cached skill content. Plugins contribute context alongside the user’s input, not by altering the agent’s core instructions.

Example: Memory recall plugin

Example: Guardrails plugin

Example: Observer-only hook (no injection)

Multiple plugins returning context

When multiple plugins return context from pre_llm_call, their outputs are joined with double newlines and appended to the user message together. The order follows plugin discovery order (alphabetical by plugin directory name).

Middleware: change what happens

Hooks observe the agent loop (with the few documented steering shapes above). Middleware changes what happens: request middleware rewrites the effective payload before anything downstream sees it, and execution middleware wraps the actual call. Register it from the same register(ctx) entry point:
The canonical list of kinds is VALID_MIDDLEWARE in mibyan_cli/middleware.py: Rules that matter in practice:
  • Request middleware chains: each callback sees the payload as rewritten by earlier callbacks, while original_args / original_request always carries the pre-middleware copy. Payloads are copied between callbacks, so mutate freely.
  • You can include source, reason, and name strings in the returned dict. They land in the middleware trace, which downstream observer hooks receive as the middleware_trace kwarg.
  • next_call in execution middleware is single-use. Calling it twice raises, because it would re-run the provider or tool.
  • A middleware callback that raises is logged and skipped; the chain continues. A downstream failure raised after your next_call propagates as itself. Middleware can never break the base runtime path.
  • Middleware payloads carry middleware_schema_version (mibyan.middleware.v1) alongside the observer telemetry fields.
  • Unknown kinds register with a warning instead of failing, so a plugin written against a newer Mibyan still loads on an older one.

Register CLI commands

Plugins can add their own mibyan <plugin> subcommand tree:
After registration, users can run mibyan my-plugin status, mibyan my-plugin config, etc. Memory provider plugins use a convention-based approach instead: add a register_cli(subparser) function to your plugin’s cli.py file. The memory plugin discovery system finds it automatically — no ctx.register_cli_command() call needed. See the Memory Provider Plugin guide for details. Active-provider gating: Memory plugin CLI commands only appear when their provider is the active memory.provider in config. If a user hasn’t set up your provider, your CLI commands won’t clutter the help output.

Register slash commands

Plugins can register in-session slash commands — commands users type during a conversation (like /lcm status or /ping). These work in both CLI and gateway (Telegram, Discord, etc.).
After registration, users can type /mystatus in any session. The command appears in autocomplete, /help output, and the Telegram bot menu. Signature: ctx.register_command(name: str, handler: Callable, description: str = "", args_hint: str = "") Key differences from register_cli_command(): Conflict protection: If a plugin tries to register a name that conflicts with a built-in command (help, model, new, etc.), the registration is silently rejected with a log warning. Built-in commands always take precedence. Async handlers: The gateway dispatch automatically detects and awaits async handlers, so you can use either sync or async functions:

Dispatch tools from slash commands

Slash command handlers that need to orchestrate tools (spawn a subagent via delegate_task, call file_edit, etc.) should use ctx.dispatch_tool() instead of reaching into framework internals. The parent-agent context (workspace hints, spinner, model inheritance) is wired up automatically.
Signature: ctx.dispatch_tool(name: str, args: dict, *, parent_agent=None) -> str Runtime behavior:
  • CLI mode: parent_agent is resolved from the active CLI agent so workspace hints, spinner, and model selection inherit as expected.
  • Gateway mode: There is no CLI agent, so tools degrade gracefully — workspace is read from the configured terminal working directory and no spinner is shown.
  • Explicit override: If the caller passes parent_agent= explicitly, it is respected and not overwritten.
This is the public, stable interface for tool dispatch from plugin commands. Plugins should not reach into ctx._cli_ref.agent or similar private state.

Act from inside a hook (profile + tools)

ctx._cli_ref is only populated in an interactive CLI session. It is None in the gateway, in non-interactive mibyan chat -q runs, and in kanban-spawned worker sessions — so any plugin logic that reaches through _cli_ref silently no-ops in exactly those contexts. Two stable, session-agnostic APIs cover what hooks actually need:
  • ctx.profile_name — the active profile name (e.g. "default", or the assignee profile in a kanban worker). Derived from mibyan_HOME, so it works everywhere with no _cli_ref dependency.
  • ctx.dispatch_tool(name, args) — invoke any registered tool (built-in or plugin), including the kanban_* tools, delegate_task, terminal, read_file, etc. Works from hook callbacks regardless of which process the hook fires in.
Together these let a kanban lifecycle hook observe a transition and act on the board without touching framework internals:
For running a full mibyan <subcommand> (e.g. mibyan kanban show), shell out with the terminal tool via ctx.dispatch_tool("terminal", {"command": "mibyan kanban show ..."}) — there is no in-process slash-command bridge for headless worker sessions, and tools are the supported way to drive Mibyan from a hook.

Handle Slack Block Kit button clicks

Plugins that post Block Kit messages with interactive elements (buttons, overflow menus, datepickers, etc.) can register the click handlers directly with the Slack adapter — no monkey-patching of slack_bolt.AsyncApp required.
Signature: ctx.register_slack_action_handler(action_id, callback) -> None Runtime behavior:
  • The handler is queued at plugin-load time and wired into the adapter’s slack_bolt.AsyncApp when the Slack platform connects.
  • Each callback is wrapped defensively: if your handler raises, the gateway logs the error and best-effort-acks the click so Slack stops retrying.
  • Standard slack_bolt rules apply — await ack() within 3 seconds, then do longer work.
  • For multi-workspace deployments the handler fires for clicks from any connected workspace; use body["team"]["id"] if you need to scope behaviour.
This is the public way for plugins to participate in Slack interactivity. Older plugins may patch SlackAdapter.connect; prefer this API instead. For the full slack_bolt surface (events, shortcuts, commands — not just Block Kit actions), use the generic register_platform_handler("slack", ...) below.

Register native platform handlers (any platform)

Plugins that need to receive platform events the core adapter doesn’t route — extra update types, native button callbacks, reaction/member events, webhook routes — can register a handler factory that the platform’s adapter invokes at connect time. This works on every gateway platform.
Signature: ctx.register_platform_handler(platform, factory) -> None What native is, per platform: Runtime behavior:
  • Factories are queued at plugin-load time and invoked when the platform connects — for platforms where dispatch order matters (Telegram, Slack, Teams, aiohttp routers) they run before the core handlers register, so scoped plugin handlers take precedence and everything else falls through.
  • Always scope handlers you add to first-match dispatch tables. On Telegram, use CallbackQueryHandler(..., pattern=r"^myplugin:") — an unscoped handler would swallow the core button flows (exec approvals, model picker, clarify prompts).
  • Each factory is isolated: if it raises, the error is logged and the platform still connects.
  • Import platform SDKs inside the factory body, not at module level — register() must work when the SDK isn’t installed.
  • One plugin can register factories for several platforms; each fires only when its platform connects.
Telegram alias: ctx.register_telegram_handler(factory) is a back-compat alias for ctx.register_platform_handler("telegram", factory). Example — Telegram, pattern-scoped inline buttons:
Example — Discord, reaction events:

Mid-run plugin loading: what activates now vs next session

A plugin can load while the gateway (or the TUI/Desktop server) is already running: mibyan plugins install/enable, a Desktop or dashboard install, a catalog re-pin, or a tool-triggered force re-discovery. Every one of those paths runs a real forced rescan (discover_plugins(force=True)) and PluginManager.on_plugin_loaded(callback) fires from inside it with one summary per newly loaded plugin (mibyan_cli/plugins_activation.py):
  • Active immediately — gateway slash commands, gateway transform hooks / other hooks, and platform callbacks: the gateway runner subscribes at boot and calls every live adapter’s idempotent rewire_plugin_handlers(), so a register_platform_handler factory (or Slack action handler) registered by a late plugin is wired without a restart. Re-wiring is deduped per native client by (plugin, factory qualname); on Telegram the late handlers are hoisted ahead of core’s catch-all filters.COMMAND / CallbackQueryHandler (PTB dispatches the first match per group), exactly as they would sit at connect.
  • Deferred — tools and prompt sections apply from the next session (the running session’s prompt/tool schema is cache-stable, same rule as /skills install); mcp_servers (the plugin’s mcp.json servers, by their mcp.json names) connect on mcp.reload or the next session.
  • There is no un-wire: disabling a plugin mid-run keeps its already-wired handlers until the gateway restarts, and the surfaces say so.
Install surfaces report exactly this split: mibyan plugins install/enable prints it after nudging the running gateway (reload-plugins control-socket verb), plugins.manage install/toggle/update returns activation + gateway_reloaded (restart_required is true only when no gateway answered).
This guide covers general plugins (tools, hooks, slash commands, CLI commands). The sections below sketch the authoring pattern for each specialized plugin type; each links to its full guide for field reference and examples.

Specialized plugin types

Mibyan has five specialized plugin types beyond the general surface. Each ships as a directory under plugins/<category>/<name>/ (bundled) or ~/.mibyan/plugins/<category>/<name>/ (user). The contract differs by category — pick the one you need, then read its full guide.

Model provider plugins — add an LLM backend

Drop a profile into plugins/model-providers/<name>/:
Lazy-discovered the first time anything calls get_provider_profile() or list_providers() — auth.py, config.py, doctor.py, models.py, runtime_provider.py, and the chat_completions transport auto-wire to it. User plugins override bundled ones by name. Full guide: Model Provider Plugins — field reference, overridable hooks (prepare_messages, build_extra_body, build_api_kwargs_extras, fetch_models), api_mode selection, auth types, testing.

Platform plugins — add a gateway channel

Drop an adapter into plugins/platforms/<name>/:
Full guide: Adding Platform Adapters — complete BasePlatformAdapter contract, message routing, auth gating, setup wizard integration. Look at plugins/platforms/irc/ for a stdlib-only working example.

Memory provider plugins — add a cross-session knowledge backend

Drop an implementation of MemoryProvider into plugins/memory/<name>/:
Memory providers are single-select — only one is active at a time, chosen via memory.provider in config.yaml. If a provider also loads as a general plugin, general discovery owns its lifecycle hooks. The memory loader supplies hooks only as a fallback until that same plugin source loads successfully through general discovery. Repeated provider loads replace the fallback hook group; distinct callbacks within the group are preserved. This does not deduplicate hooks from different plugin sources or change provider activation. Full guide: Memory Provider Plugins — full MemoryProvider ABC, threading contract, profile isolation, CLI command registration via cli.py.

Context engine plugins — replace the context compressor

Context engines are single-select — chosen via context.engine in config.yaml. Full guide: Context Engine Plugins.

Image-generation backends

Drop a provider into plugins/image_gen/<name>/:
Full guide: Image Generation Provider Plugins — full ImageGenProvider ABC, list_models() / get_setup_schema() metadata, success_response()/error_response() helpers, base64 vs URL output, user overrides, pip distribution. Reference examples: plugins/image_gen/openai/ (DALL-E / GPT-Image via OpenAI SDK), plugins/image_gen/openai-codex/, plugins/image_gen/xai/ (Grok image gen).

Non-Python extension surfaces

Mibyan also accepts extensions that aren’t Python plugins at all. These are shown in the Pluggable interfaces table; the sections below sketch each authoring style briefly.

MCP servers — register external tools

Model Context Protocol (MCP) servers register their own tools into Mibyan without any Python plugin. Declare them in ~/.mibyan/config.yaml:
Mibyan connects to each server at startup, lists its tools, and registers them alongside built-ins. The LLM sees them exactly like any other tool. Full guide: MCP.

Gateway event hooks — fire on lifecycle events

Drop a manifest + handler into ~/.mibyan/hooks/<name>/. Unlike plugins there is no plugins.enabled step: the gateway imports every valid hook directory at startup, so placing the files is the opt-in (trust model):
Events include gateway:startup, session:start, session:end, session:reset, agent:start, agent:step, agent:end, and wildcard command:*. Errors in hooks are caught and logged — they never block the main pipeline. Full guide: Gateway Event Hooks.

Shell hooks — run a shell command on tool calls

If you just want to run a script when a tool fires (notifications, audit logs, desktop alerts, auto-formatters), use shell hooks in config.yaml — no Python required:
Supports all the same events as Python plugin hooks (pre_tool_call, post_tool_call, pre_llm_call, post_llm_call, on_session_start, on_session_end, pre_gateway_dispatch) plus structured JSON output for pre_tool_call blocking decisions. Full guide: Shell Hooks.

Skill sources — add a custom skill registry

If you maintain a GitHub repo of skills (or want to pull from a community index beyond the built-in sources), add it as a tap:
Publishing your own tap is just a GitHub repo with skills/<skill-name>/SKILL.md directories — no server or registry signup needed. Full guides: Skills Hub · Publishing a custom tap (repo layout, minimal example, non-default paths, trust levels).

TTS / STT via command templates

Any CLI that reads/writes audio or text can be plugged in through config.yaml — no Python code:
For STT, point mibyan_LOCAL_STT_COMMAND at an argv-tokenized template. It runs without implicit shell interpretation; wrap it in sh -c, cmd /c, or PowerShell explicitly if the trusted local command requires shell syntax. Supported placeholders: {input_path}, {output_path}, {format}, {voice}, {model}, {speed} (TTS); {input_path}, {output_dir}, {language}, {model} (STT). Any path-interacting CLI is automatically a plugin. Full guides: TTS custom command providers · STT.

Distribute via pip

For sharing plugins publicly, add an entry point to your Python package:
Entry-point discovery remains supported when the distribution is present in the environment supplied by the installation owner (for example, a Nix derivation). It is discovery, not permission to inject packages into a PM-selected generation. For managed installs, distribute a directory plugin with pyproject.toml or manifest Python requirements and use mibyan plugins install / enable so PM can admit it transactionally. Restart Mibyan after a new environment is selected. mibyan pm install accepts managed tool names, not arbitrary PyPI packages.

Distribute for NixOS

Nix is no longer explicitly supportedNix/NixOS is no longer an explicitly supported install path (best-effort only) — see Nix Setup. This section is kept for users already deploying on NixOS.
NixOS users can install your plugin declaratively if you provide a pyproject.toml with entry points: Entry-point plugins (recommended for distribution):
Directory plugins (no pyproject.toml needed):
See the Nix Setup guide for complete documentation including overlay usage and collision checking.

Common mistakes

Handler doesn’t return JSON string:
Missing **kwargs in handler signature:
Handler raises exceptions:
Schema description too vague: