> ## Documentation Index
> Fetch the complete documentation index at: https://ahvn.top/llms.txt
> Use this file to discover all available pages before exploring further.

# Capsules

> Serialize, store, and restore Python callables as HeavenBase entities.

<Note>
  Capsules are trusted-local executable manifests. Store only code you own or have reviewed.
</Note>

<br />

## 1. What a Capsule Is

A Capsule is the durable form of a Python callable. It stores enough metadata to restore and run a function later, including:

* identity: namespace, name, and explicit version
* signature: parameters, return annotation, and JSON schema
* restore layers: source, import path, and optional `cloudpickle` payload
* dependencies: Python version and imports found in source
* capabilities: whether it can be used locally, exported to MCP, or exported for Anthropic programmatic tools
* trust and fingerprints: local-only execution flags and hashes for review

The default restore order is source first, import path second, and binary payload last when a binary payload was explicitly captured. Source-first restore is what lets a Capsule be loaded from a different folder without importing the file that originally defined the function.

Capsules are system entities owned by the required `system` extension (`sys-capsule`). Canonical implementation lives under `src/heavenbase/extensions/system/capsule/`; import `hb.Capsule` from `import heavenbase as hb`.

<br />

## 2. Store a Function

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb

def add(left: int, right: int) -> int:
    """Add two integers.

    Args:
        left: First integer.
        right: Second integer.

    Returns:
        Sum of both integers.
    """
    return left + right

capsule = hb.Capsule.from_func(
    add,
    name="add",
    namespace="demo",
    version="1",
    include_cloudpickle=False,
)

capsule_id = capsule.register()
```

The version is part of the identity. HeavenBase does not auto-increment versions from content hashes; publish a new version when you want a new public executable contract.

`Capsule.register(...)` defaults to `overwrite=False`. Pass `registry_config=...` to isolate registry storage in tests or demos.

<br />

## 3. Load and Run It Elsewhere

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
loaded = hb.Capsule.load(name="add", namespace="demo", version="1")
assert loaded.run(left=2, right=3) == 5
```

The consumer only needs HeavenBase and access to the registry backend. It does not need to import the original builder module when the source restore layer is available.

For isolated tests or application-specific registries, pass a config mapping without constructing a registry object in user code:

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
loaded = hb.Capsule.load(
    name="add",
    namespace="demo",
    version="1",
    registry_config={
        "workspace": "math-capsule-test",
        "backend": {
            "main": {"type": "sqlite", "name": "main", "database": "file:/path/registry.db"},
        },
    },
)
```

<br />

## 4. Docstrings and Formats

Capsules parse callable docstrings during capture and can synthesize a callable docstring from the stored signature metadata.

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
doc = loaded.manifest.source["doc"]
assert doc["summary"] == "Add two integers."
assert doc["params"]["left"] == "First integer."

print(loaded.to_str("docstring"))
print(loaded.to_str("source"))
print(loaded.to_str("json"))
print(loaded.to_str("yaml"))
```

`Capsule.from_str(...)` restores JSON and YAML manifest strings back into a `Capsule`.

<br />

## 5. Architecture Data Flow

The Capsule flow is explicit and layered:

1. Python callable → internal serialization strategy inspects source, import path, docstring, signature, dependencies, and optional binary fallback.
2. Strategy → `CapsuleManifest` records identity, schema, restore layers, capabilities, trust flags, and fingerprints.
3. `capsule.register()` → hidden registry workspace stores the active `sys-capsule` row.
4. `Capsule.load(...)` → manifest is read by id or by namespace/name/version; checksums are verified on load.
5. `Capsule.to_func()` → restore policy tries source, then import path, then trusted-local binary payload.
6. `Tool` and `Toolkit` wrap Capsules for local calls, MCP serving, and programmatic tool exports.

The JSON serializer also routes callables through the same internal capsule serialization strategy. When a callable cannot be captured as a Capsule, it falls back to a lightweight `module.qualname` reference instead of failing generic JSON serialization.

<br />

## 6. Registry Records

Capsules are stored as normal HeavenBase entities in a hidden registry workspace:

* `sys-capsule`: active manifest row with identity, manifest payload, capabilities, fingerprints, and `last_reason` on overwrite

Immutable revision history is not implemented yet. Overwrites update the active row and record the reason in `last_reason`.

The default registry config is under `heavenbase.capsule.registry` in `CM_HVNB`. You can pass `registry_config=...` when a demo, test, or application should keep executable data in a dedicated file.

Most application code should prefer `capsule.register(...)` and `Capsule.load(...)`. `CapsuleRegistry` remains available for advanced registry administration and inspection through `hb.capsule_registry(config)`.

<br />

## 7. Trust Model

<Warning>
  Restoring a Capsule executes Python code. Treat Capsule registries like source code repositories, not like inert data files.
</Warning>

Capsules do not verify themselves against the current content of the original Python function. The registry checksum only verifies that a loaded Capsule payload still matches the hashes stored with that same manifest. It is a record-integrity check, not a code-safety proof.

HeavenBase caches successful checksum checks in a thread-safe in-memory LRU cache (`heavenbase.capsule.registry.trust.verify_cache_size`), so a process verifies a Capsule payload once per cache key instead of recalculating hashes every time the Capsule is loaded or restored.

Use source-only Capsules by default. `include_cloudpickle` defaults to `False`; enable binary payloads only for reviewed local code that cannot be represented by source or import path. If source-only restore fails, HeavenBase reports that no trusted-local binary fallback is stored.

<br />

## 8. Demo

Run the math demo from the HeavenBase source checkout:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
rtk uv run python demos/developer/05_capsules_toolkits_mcp.py
```

The demo saves `add`, `mul`, `sub`, `div`, `mod`, and `fibonacci` as Capsules, stores a Toolkit, loads it through the public API, and validates the MCP server with a FastMCP client.

<br />

## Further Exploration

<Tip>
  **Related resources:**

  * [Toolkits](/features/toolkits) - Group Capsules into MCP tool collections
  * [Extensions](/features/extensions) - `sys-capsule` is part of the `system` extension
  * [First MCP](/quickstart/first-mcp) - Serve Toolkits over MCP
  * [MCP toolkit reference](/reference/mcp-toolkit) - Full Capsule and Toolkit API tables
</Tip>

<br />
