Skip to content

API reference

Look up Python and Rust interfaces, serving callbacks and CLI commands.

On this page

Python provider runtime

Import Mppi from mppi_provider. Construct and operate the runtime on your serving event loop. The host owns listeners, TLS, execution and retention.

Mppi.from_config

Signature
await Mppi.from_config(config_path: str | Path = "mppi.toml", *,
    coverage: CoverageProvider, execution: ExecutionProvider,
    testnet: bool = False, profile: DeploymentProfile | None = None,
    rpc_env: str | None = None, control_auth_timeout: float = 60.0,
    hooks: Hooks | None = None) -> Mppi
Inputs
Required coverage/execution implementations, saved private config and explicit network. Auth timeout is seconds. Optional RPC environment name, trusted profile and hooks.
Returns
A verified built-in Circle runtime; saved operator and original wallet-operation record are required.
Behavior
Starts no listener or inference job. Configuration/network/deployment/operator disagreement fails setup. With no rpc_env, uses the saved RPC selection.
Usage · within your application
sdk = await Mppi.from_config("mppi.toml", testnet=True,
    coverage=coverage, execution=execution)

Mppi

Signature
Mppi(config: ProviderConfig, *, chain: ChainFollower,
    contract: ContractCalls, wallet: TransactionWallet,
    coverage: CoverageProvider, execution: ExecutionProvider,
    control_auth_timeout: float = 60.0, hooks: Hooks | None = None)
Inputs
Your validated config and compatible runtime capabilities; timeout in seconds.
Returns
Explicitly composed payment runtime exposing runs and sessions interfaces.
Behavior
The integration owns the chain follower's loop, wallet operation durability and execution callbacks. Construction does not establish serving readiness.
Usage · within your application
sdk = Mppi(config, chain=chain, contract=contract, wallet=wallet,
    coverage=coverage, execution=execution)

register_grpc

Signature
sdk.register_grpc(server: grpc.aio.Server) -> None
Inputs
Your server configured with GRPC_OPTIONS.
Returns
Both native services registered on that server.
Behavior
Register before host-owned listener startup; this call does not configure TLS or start the server.
Usage · within your application
server = grpc.aio.server(options=GRPC_OPTIONS)
sdk.register_grpc(server)

discovery

Signature
sdk.discovery(path: str) -> DiscoveryResponse | None
Inputs
One of the three discovery paths listed below.
Returns
Status, header pairs and body bytes, or None for an unmatched path.
Behavior
Route through your HTTP stack unchanged. Discovery reflects applied/confirmed declarations, not pending prices or session readiness.
Usage · within your application
response = sdk.discovery("/discover")

start

Signature
await sdk.start() -> Readiness
Inputs
No arguments; use the owning event loop.
Returns
ready plus structured failures.
Behavior
Starts the SDK lifecycle and chain-dependent readiness checks. The host remains responsible for starting its listener and checking public routing.
Usage · within your application
readiness = await sdk.start()
print(readiness.ready, readiness.failures)

shutdown

Signature
await sdk.shutdown(deadline: float) -> ShutdownResult
Inputs
An absolute time.monotonic() deadline in seconds, not a duration.
Returns
Unresolved session IDs, runs and pending economic operations.
Behavior
Stops grants and waits boundedly for final reports. Does not stop your server, prove job termination or close escrow. Retain unresolved results.
Usage · within your application
report = await sdk.shutdown(time.monotonic() + 30.0)

Execution and reporting API

CoverageProvider

Signature
await coverage(request: PreparedRequest,
    context: RunContext) -> TokenCounts
Inputs
Validated original request.payload bytes and stream mode; context binds session/run, generation, model and price hash.
Returns
Prepared input/cache/output bounds as TokenCounts before paid work.
Behavior
Preparation performs no paid execution. Include at least the configured output buffer. A context alone does not grant dispatch.
Usage · within your application
# Implement this callable against your engine's preparation API.
# Return TokenCounts(input_tokens, cache_tokens, output_tokens).

ExecutionProvider

Signature
execution(request: PreparedRequest, context: RunContext,
    runs: ProviderRuns, stop_requested: asyncio.Event) -> AsyncIterator[bytes]
Inputs
Prepared request, run context, payment/report interface and stop event.
Returns
Original inference JSON object bytes, after consuming upstream framing.
Behavior
Invoked after admission. The provider owns actual cancellation and definitive final reports; iterator EOF and a stop signal are not accounting evidence.
Usage · within your application
# Implement this async iterator with your inference engine.
# Yield its JSON bytes and call the runs methods below.

require_coverage

Signature
await sdk.runs.require_coverage(context: RunContext,
    remaining_tokens: TokenCounts) -> CoverageResult
Inputs
The complete desired remaining bound, not a delta; retain the original run context.
Returns
granted, required USDC base-unit amount and optional PaymentFailure.
Behavior
Reserves eligible shared coverage. Proceed only when granted; denial requires stopping the actual job within the existing covered bound. It is not permission to pause indefinitely.
Usage · within your application
grant = await sdk.runs.require_coverage(context, remaining_tokens)
print(grant.granted, grant.required_amount, grant.failure)

report_usage

Signature
await sdk.runs.report_usage(context: RunContext,
    counts: TokenCounts) -> AccountingResult
Inputs
Nondecreasing cumulative input/cache/output counts at the run's accepted prices.
Returns
Context, counts, meter sequence, session usage amount and duplicate flag.
Behavior
Moves the exact consumed delta from reservation to usage. Invalid/decreasing/uncovered reports cannot advance accounting or manufacture credit.
Usage · within your application
accounting = await sdk.runs.report_usage(context, counts)

report_terminal

Signature
await sdk.runs.report_terminal(context: RunContext,
    counts: TokenCounts, status: RunStatus) -> FinalAccountingResult
Inputs
Definitive final cumulative counts and COMPLETED, FAILED or CANCELLED status.
Returns
Final accounting plus status; matching terminal/receipt records are prepared when writable.
Behavior
Accounts once and releases only unused reservation. Exact repeats are no-ops; conflicting reports fail. A cancellation request alone cannot justify this call.
Usage · within your application
final = await sdk.runs.report_terminal(context, final_counts, status)

Python provider session API

Use sdk.sessions on the provider event loop. Session IDs are 32-byte values. Collection methods preserve original operation identity through uncertainty; inspect per-session outcomes and canonical evidence.

sessions.get

Signature
await get(sid: bytes) -> SessionView
Inputs
Known session ID.
Returns
Observed monetary state, freshness and readiness.
Behavior
Inspection only. Missing evidence must not be replaced with zero usage.
Usage · within your application
view = await sdk.sessions.get(session_id)

sessions.list

Signature
await list(*, cursor: str | None = None, limit: int = 100) -> SessionPage
Inputs
Opaque cursor; checked page limit 1–1,000.
Returns
Known session views and next_cursor.
Behavior
Does not discover all sessions on the network or reconcile a payment submission.
Usage · within your application
page = await sdk.sessions.list(limit=100)

sessions.checkpoint

Signature
await checkpoint(sid: bytes) -> RecoveryEvidence
Inputs
Known session ID.
Returns
Detached snapshot, reservations, signed run evidence, publications, operation/baseline and closing evidence.
Behavior
The caller must persist the complete evidence. It is not a database write or a proof of readiness.
Usage · within your application
evidence = await sdk.sessions.checkpoint(session_id)

sessions.recover

Signature
await recover(evidence: RecoveryEvidence) -> SessionView
Inputs
Complete authoritative history restored by your infrastructure.
Returns
Validated session view after rechecking retained and canonical evidence.
Behavior
Missing/conflicting evidence fails without replacing live state. Does not restore old Control authority, restart work or itself establish readiness.
Usage · within your application
view = await sdk.sessions.recover(evidence)

sessions.settle

Signature
await settle(sid: bytes) -> OperationResult
Inputs
Known session ID with collectable usage and valid authority.
Returns
Original collection operation, state and per-session outcome.
Behavior
Captures eligible cumulative usage within signed ceiling, deposit and deadline. Keeps escrow open. Equal capture creates no positive event or activity refresh.
Usage · within your application
result = await sdk.sessions.settle(session_id)

sessions.settleBatch

Signature
await settleBatch(session_ids: tuple[bytes, ...]) -> OperationResult
Inputs
Ordered session IDs.
Returns
Retained batch operation and ordered per-session target coverage/results.
Behavior
Simulates exact sender/calldata; item failures are isolated by the contract. An outer successful transaction is not success for every item. Do not split/retry an unknown submission.
Usage · within your application
result = await sdk.sessions.settleBatch((first_id, second_id))

sessions.close

Signature
await close(sid: bytes) -> OperationResult
Inputs
Known session ID; final accounting, authority and contract eligibility still apply.
Returns
Retained close operation; confirmed canonical capture/refund evidence when available.
Behavior
Preserves close intent and stops new grants. Accounts for definitive final work before closure. After expiry only eligible refund-only close at already settled capture remains.
Usage · within your application
result = await sdk.sessions.close(session_id)

Rust API

Rust uses the same protocol and accounting, with its own types and names. Session/run hashes use B256; async trait operations return IntegrationResult<T>. ExecutionStream carries your original JSON output. The application provides Send + Sync coverage/execution implementations.

Rust · composition signatures
pub async fn runtime_from_config(
    host: HostConfiguration, wallet_operation_path: impl AsRef<Path>,
    coverage: Arc<dyn CoverageProvider>, execution: Arc<dyn ExecutionProvider>,
) -> Result<Mppi, SetupError>

pub async fn runtime_from_config_with_options(
    host: HostConfiguration, wallet_operation_path: impl AsRef<Path>,
    coverage: Arc<dyn CoverageProvider>, execution: Arc<dyn ExecutionProvider>,
    options: RuntimeOptions,
) -> Result<Mppi, SetupError>

Use the retained wallet-operation record. RuntimeOptions includes CircleOptions, optional polling interval, runtime limits and hooks; freshness and collection margin come from validated configuration. The helper starts neither the runtime nor a listener.

Rust · explicit composition and serving
Mppi::new(config: ProviderConfig, chain: Arc<ChainFollower>,
    contract: ContractCalls, wallet: Arc<dyn TransactionWallet>,
    coverage: Arc<dyn CoverageProvider>, execution: Arc<dyn ExecutionProvider>)
    -> Result<Mppi, ValidationError>

pub async fn serve(runtime: Arc<Mppi>, listener_config: &ListenerConfig,
    shutdown: CancellationToken, policy: &ServePolicy)
    -> Result<ShutdownResult, ServeError>

Trait / method / Inputs and result

CoverageProvider::coverage
&PreparedRequest, &RunContext → async IntegrationResult<TokenCounts>. Prepare before paid work.
ExecutionProvider::execute
PreparedRequest, RunContext, Arc<dyn ProviderRuns>, CancellationToken → ExecutionStream. Own termination and reporting.
ProviderRuns::require_coverage
&RunContext, TokenCounts → async IntegrationResult<CoverageResult>. Complete remaining bound.
ProviderRuns::report_usage
&RunContext, TokenCounts → async IntegrationResult<AccountingResult>. Cumulative counts.
ProviderRuns::report_terminal
&RunContext, TokenCounts, RunStatus → async IntegrationResult<FinalAccountingResult>. Definitive final outcome.
ProviderSessions::get / checkpoint
B256 → async IntegrationResult<SessionView / RecoveryEvidence>. Inspect or detach history.
ProviderSessions::list
Option<&str>, usize → async IntegrationResult<SessionPage>. Checked cursor/limit.
ProviderSessions::recover
RecoveryEvidence → async IntegrationResult<SessionView>. No implicit readiness or replay.
ProviderSessions::settle / close
B256 → async IntegrationResult<OperationResult>. Inspect state and canonical outcomes.
ProviderSessions::settle_batch
&[B256] → async IntegrationResult<OperationResult>. Ordered item outcomes.
ProviderLifecycle::runs / sessions
No inputs → Arc<dyn ProviderRuns / ProviderSessions>. Integration capabilities.
ProviderLifecycle::grpc_services
No inputs → GrpcServices<Self::Chat, Self::Control>. Register both services.
ProviderLifecycle::discovery
&str → Option<DiscoveryResponse>. Publish returned status, headers and bytes.
ProviderLifecycle::start
No inputs → async IntegrationResult<Readiness>. Inspect failures.
ProviderLifecycle::shutdown
Absolute tokio::time::Instant → async IntegrationResult<ShutdownResult>. Retain unresolved work.

The Python report/session behavior above also describes protocol obligations in Rust. It does not rename Rust methods: use settle_batch, not settleBatch. with_limits and with_limits_and_hooks extend explicit construction with RuntimeLimits and Hooks. Your host owns storage, workers and engine recovery.

Provider configuration

ProviderConfig.from_file

Signature
ProviderConfig.from_file(path: str | Path = "mppi.toml", *,
    overrides: Mapping[str, object] | None = None) -> ProviderConfig
Inputs
TOML configuration file, plus optional explicit section overrides. Amounts and provider IDs in TOML are canonical quoted decimals.
Returns
Validated ProviderConfig, including the desired canonical catalogue.
Behavior
Local parsing only; no wallet or registry operation. Invalid/unknown configuration fails. File TLS paths resolve relative to the file before programmatic overrides.
Usage · within your application
config = ProviderConfig.from_file("mppi.toml")

ProviderConfig.from_mapping

Signature
ProviderConfig.from_mapping(values: Mapping[str, object], *,
    overrides: Mapping[str, object] | None = None) -> ProviderConfig
Inputs
Configuration mapping and optional section overrides; exact programmatic integer amounts are permitted.
Returns
Validated ProviderConfig without network activity.
Behavior
Merges supported section mappings; models are replaced as a section. Rejects unsupported keys or invalid values rather than publishing partial configuration.
Usage · within your application
config = ProviderConfig.from_mapping(values, overrides=overrides)
Python · parse without network operations
from mppi_provider import ProviderConfig

config = ProviderConfig.from_file("mppi.toml")
catalog_bytes = config.catalog.canonical_bytes

from_file(path, overrides=...) and from_mapping(values, overrides=...) apply explicit section overrides. Loading validates declarations without wallet calls, registration or inference. Unknown keys fail. TOML money/provider IDs use canonical quoted decimal strings; programmatic amounts may be exact integers.

Section / Fields and behavior

provider
Name, description, HTTPS public_origin and nonzero recipient; optional image/services.
identity
Confirmed provider_id and owner wallet_address; onboarding writes these.
chain
Positive max_age_ms; network defaults to mainnet; optional RPC.
upstream
Full internal API base URL including path; optional api_key_env reference.
models
Unique IDs, capabilities, input/output rates and optional cache rate.
payment
Positive collection_margin_ms and authorization_wait_ms; output buffer defaults 1,000 and funding suggestion 1,000,000 token equivalents.
settlement
Positive interval_ms; optional positive amount/units triggers.
listen
Optional Rust standalone bind and explicit tls_mode. Direct mode requires cert/key paths; ingress mode rejects them.

TLS paths are relative to the configuration file. Configuration and discovery documents are bounded to 1 MiB. Duration conversions must fit the specified range. Secrets and resolved upstream credentials do not belong in discovery or the validated public configuration model.

Results, identifiers and units

Result / Fields to inspect

OpenResult · agent
operation, optional session. Usable session requires confirmed opening and readiness.
OperationResult
operation_ref, state, optional wallet_operation_id, tx_hash, observation, ordered sessions outcomes.
SessionView
session_id, descriptor, deposit, settled_cumulative, optional accepted_authorization/usage_amount, status, observation, fresh, readiness.
SessionPage
sessions and next_cursor. Provider listing can paginate; the built-in agent returns zero or one session and no cursor.
Readiness
ready and structured failures.
ShutdownResult
unresolved_session_ids, unresolved_runs, pending_operations.
RunContext
Session/run IDs, Control generation, model and accepted price hash; not an execution grant.
AccountingResult
Context, cumulative counts, meter sequence, session usage amount and duplicate flag.

Operation state / Interpretation

pending
Original operation is unresolved; retain its reference.
confirmed
Canonical transaction and block evidence establish its effect; still inspect per-session outcomes.
failed
Recorded failure; inspect its cause and evidence before any new action.
unknown
Submission/effect cannot be established. Reconcile original intent; do not assume no payment.

MPPI money is uint64 in six-decimal USDC base units. Rates are base units per million tokens; raw catalogue rates are canonical decimal strings. Token counts are exact uint64 integers, cache is a subset of input. Use arbitrary-precision or checked wide intermediate arithmetic; floats and booleans are not money.

Python IDs/hashes are bytes: session/run/catalogue hashes are 32 bytes and wallet addresses are 20 bytes in typed records. Hex is a display encoding. Contract SessionStatus uses Open=0, Closing=1, Closed=2; protobuf includes an unspecified value and uses 1, 2, 3. Convert explicitly.

Provider CLI

Install the native mppi CLI and complete the provider quickstart before using the operational commands below. Run with your private configuration and original sidecars available.

Command / Behavior

mppi provider init --testnet
Write editable local declarations; refuses overwrite; no wallet/network call.
mppi provider onboard
Verify/register identity, confirm recipient and URI, publish catalogue last.
mppi provider update --changes changes.json
Apply only explicit updates; use the recipient proof process when necessary.
mppi provider serve --host /absolute/path/to/host
Launch your trusted compiled host with validated configuration; does not create an engine adapter.
mppi provider verify
Check observed identity/discovery/TLS/unpaid gRPC; no funded inference.

Flag / input / Purpose

--testnet / --mainnet
Select the network; saved provider configuration otherwise determines it.
--config PATH
Applied config, default mppi.toml; retain its sidecars.
--declarations PATH
Initialization/onboarding declarations, default provider-declarations.toml.
--wallet ADDRESS
Select the existing Circle operator; repeat until completed configuration is saved.
--provider-id UINT256
Adopt an owned identity. Omission on first setup creates a new registration. Retain this flag on incomplete reruns.
--ca PATH
Explicit trusted TLS CA bundle for verify; system roots are the default.
--recipient-proof FILE
Exact exported request plus recipient signature.
--rpc-env NAME / --profile FILE
Explicit trusted RPC environment/profile selection.
--timeout-ms
CLI bounded request timeout; default 30,000 ms.
--changes FILE
Update object with only intended changes.
--host / --upstream
Trusted absolute executable and optional process-only API-base override for serve.

Exit 0 means requested check/setup completed; 2 means pending work or required recipient proof; 1 reports invalid input, conflicts or unavailable evidence. Retain configuration, onboarding/update records and the original wallet-operation journal. Runtime inspection uses SDK session APIs; there is no separate CLI session-inspection command.

Discovery and wire API

Surface / Purpose

GET /discover
Provider registration document on the declared HTTPS origin.
GET /.well-known/agent-registration.json
The corresponding agent registration document.
GET /models
Advisory model capabilities checked against the confirmed catalogue.
/mppi.v1.Chat/Completions
Server-streaming CompleteRequest → ChatChunk stream.
/mppi.v1.Control/Session
Bidirectional ControlMessage stream for the authenticated payment session.

Wire family / Important fields and interpretation

CompleteRequest
Model, stream flag, session/run IDs, Control generation, rate_card_hash, auth_signature and original payload bytes. Presence, widths and payload bindings are validated.
ChatChunk
One of original JSON payload, Terminal or UpstreamError.
Terminal
Final token counts, informative amount, session/run/model/price binding, status and final meter sequence; optional attributable settlement reference.
ChallengeRequest / Challenge
Unpaid, correlated request/model and provider/deployment/catalogue evidence; no inference execution.
SessionOpen / ReconnectChallenge / ReconnectRequest / SessionState
Canonical funding evidence and signed attachment, fixed authority and current Control generation.
Voucher / Meter
Session-wide signed cumulative authorization and provider-reported cumulative usage; off-chain, not deposits or payouts.
TopUpNotice / LowCredit / Drain
Funding observation/guidance and termination coordination; no automatic deposit or job pause/resume.
Receipt
Final accounting and required confirmed session chain observation, with attributable settlement reference when available.
CloseRequest / CloseResult
Signed cooperative close intent and canonically confirmed close/refund result.

The protobuf schema fixes field names, widths, presence and oneof choices; the protocol profile fixes validation and meaning. Control never carries prompts/output. A provider's internal HTTP inference API is separate from MPPI's native gRPC surface. There is no released Responses RPC.

Contract operations and authority

The SDK normally prepares and verifies these operations. All application calls are nonpayable and use the fixed Arc USDC ERC-20 interface. The descriptor binds funding wallet, immutable session signer, provider identity, recipient, operator, token and salt.

Call / Authority / effect

open(d, deposit, expectedRateCardHash, auth)
Funding wallet; positive authorized USDC deposit creates the session.
topUp(d, amount, auth)
Funding wallet; positive additional deposit; existing descriptor and opening hash stay fixed.
settle(d, cumulativeAmount, captureAmount, voucherSig)
Frozen operator or recipient; eligible increasing capture to the fixed recipient.
settleBatch(d[], cumulativeAmounts[], captureAmounts[], voucherSigs[])
Same per-item authority, equal array lengths and isolated item failure.
close(d, cumulativeAmount, captureAmount, voucherSig)
Operator or recipient; eligible final capture and refund to the funding wallet.
requestClose(d)
Funding wallet; start the closing interval while eligible.
withdraw(d)
Funding wallet; refund after the closing predicate is satisfied.
releaseIdle(d)
Permissionless eligible idle exit; funding wallet receives the refund.
getSession, computeSessionId, voucherDigest, pauseLevel
Views/helpers. Computing a session ID does not establish its existence.

The contract enforces amount/authority/deadline predicates, not the truth of token counts. The protocol team's guardian, safe and timelock control the defined pause/administration operations; these are not provider integration methods. Payments pause blocks funding/capture/provider close but permits eligible wallet exits. All pause blocks session mutations. USDC restrictions may independently block transfers.

Errors and limits

Failure / Action

INSUFFICIENT_DEPOSIT · RESOURCE_EXHAUSTED
Inspect the current deposit. A deliberate top-up may fund future work; the failed request does not revive.
SESSION_NOT_FOUND · NOT_FOUND
Only fresh confirmed zero deposit establishes absence. Pending funding or missing private state is not absence.
SESSION_NOT_READY / PRICE_CHANGED
Review the requested/current hashes and explicitly accept new prices before a fresh request.
SESSION_NOT_READY / AUTHORIZATION_REQUIRED
The bounded pre-admission authorization wait expired. Resolve readiness before choosing a fresh request.
CONTRACT_PAUSED / CLAIM_DEADLINE / CHAIN_STATE_STALE
Stop new grants; inspect pause, collection eligibility and fresh canonical chain evidence.
STATE_UNAVAILABLE / INCONSISTENT_STATE / INCONSISTENT_USAGE
Preserve valid state and restore/inspect complete evidence. Do not manufacture zero usage.
CONTROL_NOT_READY / CLOSE_PENDING / SESSION_CLOSED
Authenticate when eligible or continue the original close/exit. Do not reopen closed or closing work.
INVALID_ARGUMENT / UNAUTHENTICATED / ALREADY_EXISTS
Correct input, authority or duplicate run identity; do not replay an uncertain run.
CANCELLED / DEADLINE_EXCEEDED / UNAVAILABLE
Retain run and payment evidence. A transport outcome alone does not establish execution or payment outcome.

Payment not-ready errors use FAILED_PRECONDITION with a required reason; unknown reasons remain not-ready. Reserved VOUCHER_STALE has no duplicate-voucher producer. Rich payment details are google.rpc.Status with one mppi.v1.PaymentError in grpc-status-details-bin; these are not HTTP 402 responses.

Provider callback/report validation failures cannot advance accounting or release reservations. An execution error without definitive counts remains unresolved. UpstreamFailure represents an upstream application failure; it does not authorize invented final usage.

Configurable default bound / Value

Decompressed protobuf / SessionState
16 MiB
Ordinary Control message
64 KiB
Catalogue bytes
1 MiB
JSON nesting
128 containers
Reconnect pending run IDs
1,024
Application send/receive queue
64 messages and 16 MiB
Rich error Status
2 KiB

These are implementation resource bounds, not pricing plans or performance guarantees. A deployment can set tighter bounds. Enforce decompressed limits, fail explicitly at capacity and never truncate recovery evidence. No automatic inference replay follows a failed RPC.

Lifecycle hooks

Import Hooks from your role's Python package. Synchronous callbacks receive owned record snapshots and return None. Configure them on explicit Client composition or provider construction/from_config; Rust uses runtime Hooks with Arc callbacks and runtime options.

Callback / Observation

on_challenge / on_session_open
Verified/enqueued setup or confirmed opening and attachment boundaries.
on_voucher / on_meter
Authorization and usage observation; neither is a payout.
on_low_credit / on_drain
Guidance and lifecycle instructions; no automatic funding.
on_settle / on_close
Confirmed collection/close evidence; inspect batch item outcomes.
on_error
Structured boundary failures without prompts, secrets or raw upstream bodies.
Python · observer configuration
from mppi_provider import Hooks

hooks = Hooks(on_meter=lambda meter: print(meter.session_id.hex()))
# Pass hooks to explicit Client composition or provider construction.
# sdk.hook_stats exposes delivered/dropped/failed/queued counts.

Delivery is best effort, bounded to 64 records and 1 MiB plus one in progress. The newest observation is dropped at capacity. Callbacks can repeat; shutdown drops pending observations. Hand off quickly to your own logs/metrics. Callback counts are not payment evidence or a durable event log.

Supporting types and local testing

Family / Use and canonical reference

Rates, TokenCounts, Catalog / CatalogRow
Exact counts, rates and canonical accepted catalogue bytes. SDKs do not tokenize inference.
funding_amount, required_coverage, cumulative_usage
Checked funding, reservation and billing arithmetic in mppi-protocol.
parse_catalog / publish_catalog
Validate or create canonical model-price evidence; parsing is not identity verification.
RunAccounting / report_transition
Pure accounting transitions; not an execution grant, durable commit or chain confirmation.
RecoveryEvidence, RecoveryRun, RecoveryOperation
Caller-retained history; recovery revalidates canonical evidence.
DiscoveryDocuments, configuration records
Advanced integration entry points described by the public onboarding/runtime guides.

The loopback MockProvider supports local client practice. It performs no escrow, wallet operations, signature verification or real token accounting and must not be presented as a public provider. Unpaid endpoint verification and a real funded exchange establish different things.

SDKs and installation

Networks and contracts

Release versions

API reference | Agent providers | MPPI Docs