Metadata-Version: 2.4
Name: carcha-seal
Version: 0.1.0
Summary: Carcha Seal for Python: licensing that keeps working offline (activation, check-ins, offline grace, offline license files, feature decryption).
Author: Carcha Labs
License-Expression: LicenseRef-Carcha-Seal-Vendor-Terms
Project-URL: Homepage, https://seal.carchalabs.com/
Project-URL: Documentation, https://seal.carchalabs.com/docs/
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD-PARTY-NOTICES.txt
Provides-Extra: mcp
Requires-Dist: mcp<3,>=2.3; extra == "mcp"
Dynamic: license-file

# Carcha Seal for Python

Licensing for Python apps that keeps working offline: activation, check-ins, offline grace, clock checks, offline license files and feature decryption, with the same behaviour as the Electron, C++ and .NET SDKs. `carcha_seal` is a thin layer over the native library's C interface ([`packages/native`](https://github.com/carcha-labs/carcha-seal-sdk/tree/main/packages/native), `seal.h`), loaded with `ctypes`: the client logic, lease verification and decryption run there. This package makes the HTTP requests (Python's `urllib`) and returns Python objects. It has no dependencies. Python 3.11 or later.

## Install

```sh
pip install carcha-seal            # the client and site licenses
pip install "carcha-seal[mcp]"     # and the MCP gate (MCP Python SDK 2.x)
```

One wheel per platform, each with that platform's native library (`py3-none-<platform>`): Windows x64, macOS 11 or later (Apple Silicon and Intel), and Linux with glibc 2.28 or later (`manylinux_2_28`, x86_64 and aarch64: RHEL 8, Debian 10, Ubuntu 20.04 and later). Not yet: Alpine (musl), Windows on Arm. There is no source distribution, so pip on another platform finds no match rather than a package that cannot load. Inside an air gap, put the wheels for your platform in your own package index or install them from files (`pip install carcha_seal-<version>-py3-none-<platform>.whl`).

On an Intel Mac, install the MCP extra from wheels only: `pip install --only-binary=:all: "carcha-seal[mcp]"`. The MCP SDK depends on the `cryptography` package (through PyJWT), and its newest versions have no wheel for Intel macOS (15 November 2026: 50.0.2 has none, 48.0.1 has one). Without the option pip takes the newest version and builds it from source, which fails without a Rust toolchain. `carcha-seal` on its own has no dependencies and installs the same everywhere.

## Use

```python
import carcha_seal as seal

client = seal.SealClient(
    product="studio",
    server_url="https://seal.carchalabs.com/<your slug>",  # https://, or http:// on this computer only
    public_keys=PUBLIC_KEYS,      # the PEM from the console, in your code, not read from a file
    storage_dir=app_data_dir,     # license.dat is kept here
    app_version="2.4.0",
)                                 # raises ValueError naming a bad option ("carcha_seal: insecure_server_url")

try:
    state = client.activate(key_the_user_typed)
except seal.LicenseError as e:
    show(e.message)               # e.code: "activation_limit", "invalid_key", "network", ...

state = client.check()            # at every start: online when the server answers, else offline grace
if state.has_feature("pro"):
    model = client.decrypt("pro", encrypted_model)   # data you encrypted for the feature
```

| Method | What it does |
| --- | --- |
| `activate(key, machine_name=None)` | Activates this device; no machine name is sent unless you pass one |
| `check()` | The license state; offline from the saved lease, with its grace period and clock checks |
| `deactivate()` | Releases this device's seat |
| `offline_request(key)`, `activate_offline(file)`, `deactivate_offline()` | Offline activation by file |
| `decrypt(feature, data)` | Decrypts data encrypted for a feature; the content key stays in the native library (the plaintext returned is a Python `bytes`, which Python cannot wipe) |
| `close()` | Frees the native client (or use the client in a `with` block) |

`LicenseState` has `status` (`LicenseStatus.VALID`, `GRACE`, `INVALID`, `UNLICENSED`, `CLOCK_SUSPECT`), `is_usable`, `has_feature()`, `features`, `reason`, `message`, `customer`, `expires_at`, `maintenance_until`, `revalidate_by` (timezone-aware `datetime`), `key_hint`, `offline`, `offline_activated` and `notices_json`. A saved license that is there and cannot be read (the file is damaged, or is not a license record) is not "no license": the state is invalid with the reason `storage_unreadable`, nothing is removed, and entering the key again or loading the offline license file again replaces it.

One operation runs at a time on a client: calls from several threads wait for each other, because an operation's two native calls (before and after the request) must not be split by another one.

## Site licenses (containers and air-gapped servers)

Inside a container or a Kubernetes pod a device fingerprint is not stable, so device-bound activation does not fit. The vendor issues a **site license file** in the console (License, Site license file) for a deployment instead. It is bound to no device: whoever holds the file holds the license, so it always expires, cannot be revoked before then, and carries no feature keys. It enforces the term and the features offline; how many copies run is a contract term.

```python
lic = seal.SiteLicenseFile(
    "/etc/seal/license.json",     # the Secret, mounted as a directory (not with subPath)
    product="studio",
    public_keys=PUBLIC_KEYS,
    state_dir="/var/lib/studio",  # optional: a floor against a clock set back
)
site = lic.check()                # raises LicenseError: "no_license", "expired", "clock_rolled_back", ...
if site.has_feature("pro"):
    ...
```

`check()` re-reads the file when it changes (a renewed Secret swaps a symlink), so a renewal needs no restart. A Secret mounted with `subPath` never receives updates (Kubernetes docs); updates to a directory mount arrive eventually, so renew before the old file expires. `verify_site_license(text, product=..., public_keys=...)` verifies a file's text once. `SiteLicense` has `license_id`, `product`, `deployment`, `features`, `customer`, `issued_at`, `not_before`, `expires_at`, `maintenance_until` and `seconds_left()`.

The clock floor (`state_dir`) refuses a clock more than the leeway (300 s) behind the latest time the license saw. It raises the cost of turning the clock back; whoever controls the machine can also reset the folder.

## MCP servers: tools gated by the license

`carcha_seal.mcp.LicenseGate` is a middleware for MCP servers built on the official MCP Python SDK (`pip install "carcha-seal[mcp]"`, MCP SDK 2.x). Each gated tool needs a feature of the site license:

```python
from mcp.server.mcpserver import MCPServer
from mcp.server.subscriptions import InMemorySubscriptionBus
import carcha_seal as seal
from carcha_seal.mcp import LicenseGate

license = seal.SiteLicenseFile(os.environ["CARCHA_SEAL_LICENSE_FILE"], product="studio", public_keys=PUBLIC_KEYS)
gate = LicenseGate(license, tools={"search_documents": "tools.search", "export_report": "pro"}, free={"ping"})
bus = InMemorySubscriptionBus()
mcp = MCPServer("studio", middleware=[gate], subscriptions=bus)
# run gate.watch(bus) alongside the server (its lifespan or task group)
```

- `tools/list` shows only the tools the license grants (and `free` ones), in the server's order. A cache hint (`ttlMs`) is capped at the license's end.
- `tools/call` of a tool the license does not grant returns a tool result with `isError: true` and a text the model can read ("… Do not retry this tool; tell the user …"), with the reason under `_meta["carchalabs.com/seal"]`: `{"code", "tool", "feature"}`. Codes: `feature_not_licensed`, `tool_not_licensed`, `license_missing`, `license_expired`, `license_invalid`, `clock_rolled_back`. It is not a protocol error, so the model sees why.
- The call is checked every time, not only the list: a client may cache the list, list-changed reaches only clients that listen for it, and the SDK's low-level `Server` passes a `tools/call` for a name it never listed to your handler.
- A tool in neither `tools` nor `free` is refused (`unmapped="deny"`), so a tool added later is not given away by forgetting to map it; `unmapped="allow"` lets such tools through.
- `watch(bus)` checks the license every 30 seconds and right after it expires, and when the usable features change (a renewed file, an expiry) tells clients: 2026-07-28 clients through `subscriptions/listen`, earlier clients on their connection.
- `usage=` counts each call's outcome (`ok`, `error`, `denied`) per tool: a `UsageLog` (below), or any object with `record(tool, outcome)`. A name the gate does not know is counted as `*`.

The tool set depends only on the license, never on the connection, as the MCP spec requires of `tools/list`. Works with `MCPServer` (`middleware=[gate]`) and the low-level `Server` (`server.middleware.append(gate)`), over stdio and HTTP.

## Usage reports (counting where nothing can call home)

`carcha_seal.usage.UsageLog` counts calls per tool and outcome, writes them once per period as hash-chained records in a folder, and exports a usage report the customer sends to you; you upload it in the console (License, Usage reports), which checks it and adds what it counts.

```python
from carcha_seal.usage import UsageLog

usage = UsageLog("/var/lib/studio/usage")           # one folder per running copy (a PVC per replica)
gate = LicenseGate(license, tools=TOOLS, usage=usage)
...
report = usage.export(license.check())              # JSON text: the records since the last export, signed
usage.close()                                       # writes the counts still in memory
```

- Each record holds its sequence number, the SHA-256 of the record before it, its time window and the counts. The report's manifest names the product, license, deployment and site license file, the record range and the chain's head, and is signed with an Ed25519 key the deployment made for itself on first use (`usage.key` in the folder, readable by the owner only).
- The console refuses a report that was changed after it was signed or whose records were changed, removed or reordered; it shows records missing between two reports, a report that contradicts one already received, and a new key for a deployment (what deleting the folder gives).
- `export(license, from_seq=…)` exports again from a record, for a file that was lost, even after later files were uploaded; the console counts only records it has not counted.
- One report holds at most 10,000 records and about 9 MB (what the console takes); while `unexported` is not 0, export again.
- A second process on the same folder is refused (`UsageLogInUse`): two writers would fork the chain.
- Counts not yet in a record are written by `flush()`, `export()` and `close()`; a process killed without them loses at most one period (`period`, default one hour).
- A report proves the counts were not changed after they were written, not that every call was counted: whoever runs the software holds the key.

## HTTP

The default transport is `urllib`:
- Certificates are checked with Python's default SSL context.
- The proxy comes from the `<scheme>_proxy` environment variables, else macOS System Configuration or the Windows registry.
- Redirects are refused: one could take the license key to another address.
- Each request takes at most `timeout` seconds (default 8) and reads at most 1 MB.

Any failure is "no answer", and the client then works from the saved lease. To use your own HTTP stack, pass `transport`: a function from `HttpRequest` (`url`, `user_agent`, `body`) to `HttpResponse(status, body)`, returning `NO_ANSWER` when there was none. An exception your transport raises reaches the caller of that operation; the client stays usable.

## Not yet in this package

Floating licenses (seats), as in the C++ and .NET SDKs. Inside containers, use a site license file (above) or, in a connected cluster, floating seats once they are in this package.

## Tests

Against an installed wheel (what CI runs on every platform: `.github/workflows/python-packages.yml`), from outside this folder:

```sh
python scripts/build_wheel.py --library <built library> --platform manylinux_2_28_x86_64 --out dist   # needs `build`
pip install --only-binary=:all: "dist/carcha_seal-<version>-py3-none-<platform>.whl[mcp]"   # wheels only: nothing is compiled
python tests/installed.py /tmp/scenarios.tsv     # refuses to run against src/
```

From the source tree: build the native library, copy it into `src/carcha_seal/_lib/`, then:

```sh
cargo run --quiet --manifest-path ../client/Cargo.toml --example scenarios_tsv > /tmp/scenarios.tsv
PYTHONPATH=src python tests/scenarios.py /tmp/scenarios.tsv /tmp/seal-python   # every scenario recorded from the Electron SDK
PYTHONPATH=src python -m unittest tests/test_transport.py                       # urllib against a local server
PYTHONPATH=src python -m unittest tests/test_site.py                            # site licenses: every vector, Secret renewal, clock floor
PYTHONPATH=src python -m unittest tests/test_mcp.py                             # the MCP gate (needs mcp 2.x): in process, over stdio, both protocol eras
PYTHONPATH=src python -m unittest tests/test_usage.py                           # usage reports (verified with packages/core when it is built)
PYTHONPATH=src python tests/make_usage_vectors.py                               # regenerate packages/lease/tests/usage-vectors.json
```
