Skip to main content

Add Machine Payments Protocol (MPP) support to FastAPI endpoints in a few lines.

Project description

fastapi-mpp

PyPI version Python versions License: MIT GitHub stars

Machine Payments Protocol middleware for FastAPI.

Version v0.2 hardens receipt validation, replay protection, session binding, and HTTP authentication semantics. This project is still beta.

Installation

pip install fastapi-mpp

For production validation, install Tempo support so default cryptographic validation is available:

pip install "fastapi-mpp[tempo]"

Optional extras:

pip install "fastapi-mpp[dotenv]"
pip install "fastapi-mpp[stripe]"
pip install "fastapi-mpp[all]"

Usage

Server setup

from fastapi import FastAPI, Request
from mpp_fastapi.core import MPP

app = FastAPI()

# Production mode (default): requires receipt_validator or fastapi-mpp[tempo].
mpp = MPP()

@app.get("/premium")
@mpp.charge(amount="0.05", currency="USD", description="Premium data")
async def premium(request: Request):
    return {"data": "paid content"}

HTTP flow (v0.2 hardened)

  1. Client calls endpoint without credential.
  2. Server responds 402 Payment Required with:
    • WWW-Authenticate: Payment challenge="<base64url(JSON)>", realm="MyAPI", expires="..."
    • challenge body containing challenge_id, intent, amount, currency, expires_at, hints
  3. Wallet pays and retries with:
    • Authorization: Payment credential="<base64url(receipt-json)>"
  4. Server validates receipt (fail-closed in production), applies replay checks, and returns success with:
    • Payment-Receipt: <base64url(receipt-json)>
    • optional session headers when session mode is enabled.

Legacy compatibility can be kept with allow_legacy_headers=True:

  • X-MPP-Receipt
  • X-MPP-Session-Id

Session budgets

from fastapi import FastAPI, Request
from mpp_fastapi.core import MPP
from mpp_fastapi.types import MPPChargeOptions

app = FastAPI()
mpp = MPP()

session_options = MPPChargeOptions(
    amount="0.01",
    currency="USD",
    description="Session-metered call",
    session=True,
    max_amount="0.50",
    require_idempotency_key=True,
)

@app.post("/agent/infer")
@mpp.charge(options=session_options)
async def infer(request: Request):
    return {"result": "paid inference"}

Sessions are HMAC-signed opaque tokens bound to:

  • route scope
  • optional payer source
  • currency/provider
  • issued-at and expiry (default 15 minutes)
  • max budget tracked in store

Local Run

uv venv
source .venv/bin/activate
uv pip install -e ".[dev]"
uvicorn examples.simple_app:app --reload

Then test:

curl -i http://127.0.0.1:8000/free
curl -i http://127.0.0.1:8000/premium

Expected behavior demo:

GET /free -> 200 OK
GET /premium (without Authorization) -> 402 Payment Required
GET /premium (with Authorization: Payment credential="...") -> 200 OK

Security

Read SECURITY.md before production usage.

  • Beta warning: use with caution.
  • In-memory replay/session/rate-limit stores are suitable for single-process deployments only.
  • Production mode is fail-closed when receipt validation is not configured.
  • HTTPS is enforced in production mode.

Headers

Incoming:

  • Authorization: Payment credential="..." (preferred)
  • Payment-Receipt (supported)
  • Payment-Session (session spends)
  • X-MPP-Receipt and X-MPP-Session-Id in legacy mode
  • Idempotency-Key for safer retries

Response on 402:

  • WWW-Authenticate: Payment challenge="...", realm="...", expires="..."
  • JSON challenge payload

Response on success:

  • Payment-Receipt
  • Payment-Session when session authorization is established

Design Notes

  • In-memory stores are intentionally simple for v0.2; Redis-backed stores are planned.
  • Header size limit is enforced (8KB) for authorization and receipt headers.
  • A basic in-memory challenge rate limiter is enabled (default 10 challenges/IP/minute).

Roadmap

  • Redis-backed replay/session/rate-limit stores
  • Full conformance with evolving HTTP Payment auth draft semantics
  • Advanced rate limiting and abuse controls
  • Payment provider adapters and richer telemetry

Contributing

  1. Fork the repository.
  2. Create a feature branch.
  3. Add tests for behavior changes.
  4. Run:
uv pip install -e ".[dev]"
pytest
ruff check .
mypy src
  1. Open a PR with clear before/after behavior.

Credits

Inspired by the MPP ecosystem work and early protocol specs from Tempo and Stripe collaborators. Please refer to official protocol repos/specs for normative behavior and updates.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi_mpp-0.2.0.tar.gz (14.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_mpp-0.2.0-py3-none-any.whl (15.7 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_mpp-0.2.0.tar.gz.

File metadata

  • Download URL: fastapi_mpp-0.2.0.tar.gz
  • Upload date:
  • Size: 14.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for fastapi_mpp-0.2.0.tar.gz
Algorithm Hash digest
SHA256 87a0f84162f81c34224344ac31891547c3d69bc9622af428d8ca3ed67cf0db4d
MD5 39e0caf7f5fd03ee12cf1431f82cdd13
BLAKE2b-256 51de0542b780d3da3938f3c918eb2f467573e4eca1e2d7169dea1bfb5b1177ae

See more details on using hashes here.

File details

Details for the file fastapi_mpp-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_mpp-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 15.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.12

File hashes

Hashes for fastapi_mpp-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7bc714f0b995a18db76d0b9fca69255114deeed3985bc291df33c825cb2b3708
MD5 7c81cc6e99447a17efad29a10c20fef6
BLAKE2b-256 10f6ef3247056f2c10cc3ee2779c08b5eaf7733512eb827f2aee83b835b4f858

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page