Plugins and Hooks
Bub discovers plugins automatically via standard Python Entry Points and uses hooks to inject custom logic into each stage of the runtime.
Plugins can extend Bub in three ways:
- Custom tools: register tool functions via
provide_tools; - Background services: mount long-running services (such as MCP clients or message channels) via
Lifecycle; - Pipeline hooks: rewrite prompts, approve or block tool calls, and persist state across Turns.
Create a minimal plugin
Section titled “Create a minimal plugin”Before diving into advanced hooks, let’s build a minimal offline echo plugin that needs no model API key so you can walk through the full workflow end to end.
1. Initialize the project
Section titled “1. Initialize the project”Scaffold a Python library with uv:
uv init --lib bub-echo-plugincd bub-echo-pluginCreate src/bub_echo_plugin/plugin.py:
Directorybub-echo-plugin/
- pyproject.toml
Directorysrc/
Directorybub_echo_plugin/
- __init__.py
- plugin.py # Plugin and hook implementations
2. Declare the entry point
Section titled “2. Declare the entry point”Expose the plugin under [project.entry-points."bub"] in pyproject.toml:
[build-system]requires = ["hatchling"]build-backend = "hatchling.build"
[project]name = "bub-echo-plugin"version = "0.1.0"requires-python = ">=3.12"dependencies = ["bub[app]"]
[project.entry-points."bub"]echo = "bub_echo_plugin.plugin:echo_plugin"- The entry-point group name must be
"bub". - The key (
echo) is the plugin identifier; the value points to the module, instance, or class to load.
3. Implement a hook
Section titled “3. Implement a hook”Mark hook methods with @hookimpl:
from bub import hookimpl
class EchoPlugin: @hookimpl def run_model(self, prompt, session_id, state): return f"[echo:{session_id}] {prompt}"
echo_plugin = EchoPlugin()Implementing run_model replaces the default model call and returns the echoed prompt with the session ID.
Entry-point target forms
Section titled “Entry-point target forms”An entry point can reference a module, an instance, or a class/factory:
| Target syntax | Registered object | When to use |
|---|---|---|
bub_myplugin.plugin |
Module | Hooks are stateless functions |
bub_myplugin.plugin:plugin |
Instance | Hooks share state via self |
bub_myplugin.plugin:MyPlugin |
Class or factory function | Plugin needs access to the BubFramework instance |
When targeting a class or factory function, Bub passes the BubFramework instance as the first argument:
from bub import BubFramework, hookimpl
class MyPlugin: def __init__(self, framework: BubFramework) -> None: self.framework = framework
@hookimpl def build_prompt(self, message, session_id, state): return f"Workspace: {self.framework.workspace}\n{message}"Install and verify
Section titled “Install and verify”Once your plugin is written, install it into the environment where Bub runs and verify that its hooks are discovered and executed.
Install in editable mode
Section titled “Install in editable mode”uv syncVerify hook registration
Section titled “Verify hook registration”uv run bub hooksConfirm echo appears under run_model.
Run a test
Section titled “Run a test”Now send a test prompt to verify that your plugin is active:
uv run bub run "hello from my plugin"You should see the echoed output intercepted by your plugin:
[echo:cli:local] hello from my pluginTroubleshooting and execution order
Section titled “Troubleshooting and execution order”- Matching Python environment: ensure
bubruns in the same virtual environment where the plugin was installed. - Refresh entry-point metadata: re-run
uv sync(orpip install -e .) after editingentry-pointsinpyproject.toml. - Hook priority: Bub registers
builtinhooks first, then entry-point plugins. At equal priority, plugins registered later run first (LIFO). Use@hookimpl(tryfirst=True)or@hookimpl(trylast=True)to adjust ordering explicitly (see Hooks reference: Priority and dispatch).
Common hook patterns
Section titled “Common hook patterns”Bub provides extension points across the entire runtime lifecycle (see the Hooks reference for all 27 signatures). Most real-world customizations fall into four common patterns:
1. Provide tools
Section titled “1. Provide tools”Register @tool functions with provide_tools:
from bub import hookimpl, toolfrom bub.core.tools import Tool
@tool(name="orders.get")def get_order(order_id: str) -> dict[str, str]: """Look up an order's shipping status by order ID.""" return {"id": order_id, "status": "shipped"}
class OrdersPlugin: @hookimpl def provide_tools(self) -> list[Tool]: return [get_order]Deferred tool schemas
Section titled “Deferred tool schemas”When a plugin registers many tools, injecting every full schema into the system prompt consumes context tokens. Set deferred=True to load schemas on demand:
@tool(name="orders.export", deferred=True)def export_orders(format: str) -> str: """Export a report of historical orders.""" ...Deferred tools initially expose only their name and short description; the model calls tool.describe to load the full schema when needed.
2. Rewrite prompts, intercept calls, and persist state
Section titled “2. Rewrite prompts, intercept calls, and persist state”Rewrite prompts
Section titled “Rewrite prompts”-
Rewrite user input (
build_prompt):from bub import hookimplfrom bub.envelope import content_of@hookimpldef build_prompt(message, session_id, state):text = content_of(message)return [f"Answer using project terminology:\n\n{text}"] -
Append system instructions (
system_prompt, joined with blank lines by priority):@hookimpldef system_prompt(prompt, state):return "Include referenced file paths at the end of your reply."
Intercept model or tool calls
Section titled “Intercept model or tool calls”Interception hooks run before a call executes. Note: raising an exception in an interception hook is logged and skipped — it does not block execution. Return a decision object to modify or block a call:
-
Cap model parameters (
before_llm_call):from dataclasses import replacefrom bub import hookimplfrom bub.hooks.interception import LLMCallRequest@hookimpldef before_llm_call(request: LLMCallRequest, state):max_tokens = min(request.max_tokens or 512, 512)return replace(request, max_tokens=max_tokens) -
Approve or deny tool calls (
before_tool_call):from bub import hookimplfrom bub.hooks.interception import ToolCall, ToolCallDecision@hookimpldef before_tool_call(call: ToolCall, state):if call.tool == "orders.cancel" and not state.get("can_cancel_orders", False):return ToolCallDecision.deny("This session is not permitted to cancel orders.")return None
See Pre-call interception and decisions and ToolCallDecision.
Audit completed calls
Section titled “Audit completed calls”Completion hooks run after a call finishes, making them handy for measuring latency, reporting metrics, or writing audit logs:
from bub import hookimpl
@hookimpldef after_llm_call(request, result, state): print(f"model={request.model} error={result.error!r} elapsed={result.duration_ms}ms")
@hookimpldef after_tool_call(call, result, state): print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms")Persist state across Turns
Section titled “Persist state across Turns”Use load_state and save_state to persist application state across Turns (see TurnState):
import asynciofrom bub import hookimpl
class TurnCounter: def __init__(self) -> None: self.counts: dict[str, int] = {} self.lock = asyncio.Lock()
@hookimpl async def load_state(self, message, session_id): async with self.lock: return {"completed_turns": self.counts.get(session_id, 0)}
@hookimpl async def save_state(self, session_id, state, message, model_output): async with self.lock: self.counts[session_id] = state.get("completed_turns", 0) + 1
turn_counter = TurnCounter()3. Mount services and storage
Section titled “3. Mount services and storage”Background services (Lifecycle)
Section titled “Background services (Lifecycle)”Components that stay running alongside bub chat or bub gateway (such as MCP clients or schedulers) subclass Lifecycle and register via provide_channels:
from bub.channels.base import Lifecycle
class MyRuntime(Lifecycle): name = "myapp.lifecycle"
async def start(self, stop_event) -> None: await self._connect(stop_event)
async def stop(self) -> None: await self._close()Lifecycleservices start automatically inbub chatandbub gateway, and are skipped in one-offbub runcalls.- Exclude a service at startup with
--enable-channel '!myapp.lifecycle'.
Process-wide lifespan resources
Section titled “Process-wide lifespan resources”Use provide_lifespan with an async generator to manage database pools or HTTP clients across framework.running():
from bub import hookimpl
@hookimplasync def provide_lifespan(): client = await connect_database() try: yield finally: await client.close()Custom Tape store
Section titled “Custom Tape store”Replace the default file store via provide_tape_store (see Store conversation history in a database):
from pathlib import Pathfrom bub import hookimplfrom bub.core.store import FileTapeStore
@hookimpldef provide_tape_store(): return FileTapeStore(Path("./application-tapes"))4. Add CLI subcommands
Section titled “4. Add CLI subcommands”Register custom Typer subcommands on the root bub CLI via register_cli_commands:
import typerfrom bub import hookimpl
@hookimpldef register_cli_commands(app: typer.Typer): @app.command() def my_cmd(name: str = "world") -> None: typer.echo(f"Executed: {name}")Interactive terminal prompts
Section titled “Interactive terminal prompts”Use bub.inquirer to prompt for input or confirmation inside custom CLI commands:
from bub.inquirer import ask_confirm, ask_text
token = ask_text("Enter verification token")if ask_confirm("Continue execution?", kind="permission"): passDistribution and WASM extensions
Section titled “Distribution and WASM extensions”Package as a Python wheel
Section titled “Package as a Python wheel”Package plugins, skills, and custom CLI commands into a standard Python wheel. See Packaging and distribution for build configuration, or Load portable Agent Plugins for declarative cross-platform packages.
WASM plugins (experimental)
Section titled “WASM plugins (experimental)”With bub-extism, WebAssembly modules compiled from Go, Rust, or other languages can run as Bub hooks:
{ "plugins": { "prompt": { "manifest": { "wasm": [{ "path": "go-build-prompt.wasm" }] }, "wasi": true, "hooks": { "build_prompt": "build_prompt" } } }}export BUB_EXTISM_CONFIG_PATH=./extism.jsonbub run "Say hello from a prompt built outside Python."