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.
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.
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 nativeplugin.yaml plus
register(ctx) plugins.
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
Nativeplugin.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
PluginContextmethods 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
**kwargsreceives the complete current payload. New plugins should accept**kwargsso they can opt into additive data without another signature change. - Manifests are open to additions. Unknown
plugin.yamlfields 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.
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:- a replacement and migration instructions in the plugin guide and release notes;
- a warning emitted at most once per process, naming the replacement and the earliest removal release;
- support for the old behavior through at least two subsequent minor releases; and
- behavior-based compatibility coverage for both the legacy path and the replacement throughout that window.
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)
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:
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
Createplugin.yaml:
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 forctx.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:
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 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:
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_HOMEroots. A new plugin is downloaded disabled; Python dependency consent precedes enablement.pyproject.tomltakes precedence overpython_dependenciesand legacypip_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 updateincludes enabled plugins while preparing its new generation. There is no post-update pip reinstall.mibyan plugins updateprepares 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-agentself-dependencies are omitted because the checkout supplies Mibyan. Direct-URL requirements are not managed; use a plugin-owned external runtime for them. --no-depsdownloads 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: externalkeeps 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 validaterejectsplugin.yamlwithout__init__.py,desktop/plugin.js, orplugin.jsonbeside it. Pip-layout packages need a directory-plugin wrapper. security.allow_lazy_installs: falseblocks 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_majorfor stable packages,>=0.29,<0.32for pre-1.0 ones. A bare>=X.Yadopts 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,<nextkeeps 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"(orUV_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.
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
Createschemas.py — this is what the LLM reads to decide when to call your tools:
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
Createtools.py — this is the code that actually executes when the LLM calls your tools:
- Signature:
def my_handler(args: dict, **kwargs) -> str - Return: Always a JSON string. Success and errors alike.
- Never raise: Catch all exceptions, return error JSON instead.
- Accept
**kwargs: Mibyan injects context keywords (task_id,session_id,user_task,parent_agent, …) and only forwards the ones your signature names, sodef handler(args)works;**kwargsis how you opt into the full, additively growing context.
Step 5: Write the registration
Create__init__.py — this wires schemas to handlers:
register() does:
- Called exactly once at startup
ctx.register_tool()puts your tool in the registry — the model sees it immediatelyctx.register_hook()subscribes to lifecycle eventsctx.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 belowctx.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 invoketerminal,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.statestores 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:
Store settings and runtime state
Use plugin-relative config keys for user-visible behavior. Mibyan resolves them underplugins.entries.<plugin-id>.settings and rejects global, cross-plugin,
and traversal paths:
ctx.state for plugin-owned cursors, caches, and deduplication data rather
than placing runtime bookkeeping in config.yaml:
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’sconfig_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.
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:calculator: calculate, unit_convert in the banner’s tool list.
Try these prompts:
Debugging plugin discovery
If your plugin doesn’t show up — or shows up but isn’t loading — setmibyan_PLUGINS_DEBUG=1 to get verbose discovery logs on stderr:
- 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__.pythat raised
~/.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:
- Not enabled in config — plugins are opt-in. Run
mibyan plugins enable <name>(the name comes from theplugins listoutput, 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 rootplugin.jsonin the same locations. Anything deeper is ignored. - Missing
__init__.py: Native packages need bothplugin.yamland__init__.pywith aregister(ctx)function. Portable packages do not import Python and do not require__init__.py. - Wrong
kind— gateway adapters needkind: platformin their manifest. Memory providers are auto-detected askind: exclusiveand routed through thememory.providerconfig instead ofplugins.enabled.
Your plugin’s final structure
- 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:Store durable state
Never write runtime state into your plugin directory: that’s the install tree, andmibyan 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:
.env / secret-scope path like everywhere else.
Bundle skills
Plugins can ship skill files that the agent loads viaskill_view("plugin:skill"). Register them in your __init__.py:
- Plugin skills are read-only — they don’t enter
~/.mibyan/skills/and can’t be edited viaskill_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.
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:
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: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, usepm.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:
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: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:
plugins/memory/honcho/client.py) is the reference consumer.
Rule of thumb: any time you writeglobal _somethingfollowed by ais Nonecheck 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 replaceweb_search with a custom corporate index), pass override=True:
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:
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
"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 at10,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 frompre_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 sameregister(ctx) entry point:
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_requestalways carries the pre-middleware copy. Payloads are copied between callbacks, so mutate freely. - You can include
source,reason, andnamestrings in the returned dict. They land in the middleware trace, which downstream observer hooks receive as themiddleware_tracekwarg. next_callin 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_callpropagates 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 ownmibyan <plugin> subcommand tree:
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.).
/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 viadelegate_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.
ctx.dispatch_tool(name: str, args: dict, *, parent_agent=None) -> str
Runtime behavior:
- CLI mode:
parent_agentis 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.
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 frommibyan_HOME, so it works everywhere with no_cli_refdependency.ctx.dispatch_tool(name, args)— invoke any registered tool (built-in or plugin), including thekanban_*tools,delegate_task,terminal,read_file, etc. Works from hook callbacks regardless of which process the hook fires in.
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 ofslack_bolt.AsyncApp required.
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.AsyncAppwhen 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.
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.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.
ctx.register_telegram_handler(factory) is a back-compat alias for ctx.register_platform_handler("telegram", factory).
Example — Telegram, pattern-scoped inline buttons:
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 aregister_platform_handlerfactory (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-allfilters.COMMAND/CallbackQueryHandler(PTB dispatches the first match per group), exactly as they would sit at connect. - Deferred —
toolsandpromptsections apply from the next session (the running session’s prompt/tool schema is cache-stable, same rule as/skills install);mcp_servers(the plugin’smcp.jsonservers, by their mcp.json names) connect onmcp.reloador 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.
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).
Specialized plugin types
Mibyan has five specialized plugin types beyond the general surface. Each ships as a directory underplugins/<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 intoplugins/model-providers/<name>/:
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 intoplugins/platforms/<name>/:
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 ofMemoryProvider into plugins/memory/<name>/:
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.engine in config.yaml.
Full guide: Context Engine Plugins.
Image-generation backends
Drop a provider intoplugins/image_gen/<name>/:
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:
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):
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 inconfig.yaml — no Python required:
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: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 throughconfig.yaml — no Python code:
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: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
NixOS users can install your plugin declaratively if you provide apyproject.toml with entry points:
Entry-point plugins (recommended for distribution):
pyproject.toml needed):
Common mistakes
Handler doesn’t return JSON string:**kwargs in handler signature:

