Skip to content

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.

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.

Scaffold a Python library with uv:

Terminal window
uv init --lib bub-echo-plugin
cd bub-echo-plugin

Create src/bub_echo_plugin/plugin.py:

  • Directorybub-echo-plugin/
    • pyproject.toml
    • Directorysrc/
      • Directorybub_echo_plugin/
        • __init__.py
        • plugin.py # Plugin and hook implementations

Expose the plugin under [project.entry-points."bub"] in pyproject.toml:

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.

Mark hook methods with @hookimpl:

src/bub_echo_plugin/plugin.py
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.

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}"

Once your plugin is written, install it into the environment where Bub runs and verify that its hooks are discovered and executed.

Terminal window
uv sync
Terminal window
uv run bub hooks

Confirm echo appears under run_model.

Now send a test prompt to verify that your plugin is active:

Terminal window
uv run bub run "hello from my plugin"

You should see the echoed output intercepted by your plugin:

[echo:cli:local] hello from my plugin
  1. Matching Python environment: ensure bub runs in the same virtual environment where the plugin was installed.
  2. Refresh entry-point metadata: re-run uv sync (or pip install -e .) after editing entry-points in pyproject.toml.
  3. Hook priority: Bub registers builtin hooks 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).

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:

Register @tool functions with provide_tools:

from bub import hookimpl, tool
from 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]

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 user input (build_prompt):

    from bub import hookimpl
    from bub.envelope import content_of
    @hookimpl
    def 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):

    @hookimpl
    def system_prompt(prompt, state):
    return "Include referenced file paths at the end of your reply."

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 replace
    from bub import hookimpl
    from bub.hooks.interception import LLMCallRequest
    @hookimpl
    def 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 hookimpl
    from bub.hooks.interception import ToolCall, ToolCallDecision
    @hookimpl
    def 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.

Completion hooks run after a call finishes, making them handy for measuring latency, reporting metrics, or writing audit logs:

from bub import hookimpl
@hookimpl
def after_llm_call(request, result, state):
print(f"model={request.model} error={result.error!r} elapsed={result.duration_ms}ms")
@hookimpl
def after_tool_call(call, result, state):
print(f"tool={call.tool} error={result.error!r} elapsed={result.duration_ms}ms")

Use load_state and save_state to persist application state across Turns (see TurnState):

import asyncio
from 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()

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()
  • Lifecycle services start automatically in bub chat and bub gateway, and are skipped in one-off bub run calls.
  • Exclude a service at startup with --enable-channel '!myapp.lifecycle'.

Use provide_lifespan with an async generator to manage database pools or HTTP clients across framework.running():

from bub import hookimpl
@hookimpl
async def provide_lifespan():
client = await connect_database()
try:
yield
finally:
await client.close()

Replace the default file store via provide_tape_store (see Store conversation history in a database):

from pathlib import Path
from bub import hookimpl
from bub.core.store import FileTapeStore
@hookimpl
def provide_tape_store():
return FileTapeStore(Path("./application-tapes"))

Register custom Typer subcommands on the root bub CLI via register_cli_commands:

import typer
from bub import hookimpl
@hookimpl
def register_cli_commands(app: typer.Typer):
@app.command()
def my_cmd(name: str = "world") -> None:
typer.echo(f"Executed: {name}")

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"):
pass

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.

With bub-extism, WebAssembly modules compiled from Go, Rust, or other languages can run as Bub hooks:

extism.json
{
"plugins": {
"prompt": {
"manifest": { "wasm": [{ "path": "go-build-prompt.wasm" }] },
"wasi": true,
"hooks": { "build_prompt": "build_prompt" }
}
}
}
Terminal window
export BUB_EXTISM_CONFIG_PATH=./extism.json
bub run "Say hello from a prompt built outside Python."