rungentBuild
Python and other stacks
Add rungent to an API in Python, Go, Java or any other language. Your API serves an annotated OpenAPI document, answers who is signed in and verifies a signed header; rungent serve runs beside it, and one reverse proxy puts both on your origin.
rungent's runtime is TypeScript, so an API in another language runs it as its own process,
rungent serve. A reverse proxy sends rungent's paths to it and everything else to your API, so the
browser sees one origin and the user's session works for both.
browser ─> proxy :8000 ─┬─ /rungent/v0/*, /mcp, /skill.md, … ─> rungent serve :8787 ─┐
└─ everything else ────────────────> your API :8001 <──┘ calls as the user
Your API implements a small contract over HTTP. In Python, the rungent kit on PyPI (imported as rungent) does most of
it; in any other language it is a few dozen lines.
| Your API | Required |
|---|---|
Serves OpenAPI 3.1 with x-rungent on the operations agents may use |
Yes |
| Answers one identity operation: who the credential belongs to | Yes |
Verifies the Rungent-Assertion header on calls from rungent |
Yes |
| Answers search operations over its resources | No |
Annotate a FastAPI app#
pip install "rungent[fastapi]"
The kit needs Python 3.12 or later. op() builds the x-rungent object for FastAPI's
openapi_extra. It takes the x-rungent keys in snake case (timeout_seconds becomes
timeoutSeconds; nested objects keep the wire's camelCase) and raises ValueError at import,
listing every problem, when one is wrong.
# app.py
from fastapi import FastAPI, Request
from pydantic import BaseModel
from rungent import Identity, op
app = FastAPI(title="Cloud Console")
class Vm(BaseModel):
id: str
name: str
status: str
@app.get("/api/vms", openapi_extra=op("list_vms", description="List cloud servers (VMs) and their status."))
async def list_vms(request: Request) -> list[Vm]:
return find_vms(current_user(request))
@app.post(
"/api/vms/{vm_id}/stop",
openapi_extra=op(
"stop_vm",
description="Stop a running cloud server (VM).",
effect="update",
resolve={"vm_id": {"op": "list_vms"}},
confirmation={"title": "Stop server {vm_id}?"},
cli={"command": "vm stop", "args": ["vm_id"]},
),
)
async def stop_vm(vm_id: str, request: Request) -> Vm:
return stop(current_user(request), vm_id)
@app.get("/api/me", openapi_extra=op("whoami", role="identity"))
async def whoami(request: Request) -> Identity:
user = current_user(request)
return Identity(subject=user.id, tenant=user.tenant_id, name=user.name)
FastAPI serves the document at /openapi.json. Identity, like the search and form models
below, serializes in the wire's camelCase and leaves absent fields out. ADMIN_SCOPE
(rungent:admin) in scopes lets a user change rungent's model settings.
Verify the assertion#
RungentHost installs the six checks of Acting as the user
as one middleware. It matches the operation from the route FastAPI dispatches to, and its
approval from the operation's approval key.
import json
import os
from rungent import load_public_keys
from rungent.fastapi import RungentCall, RungentHost
def caller(request: Request) -> tuple[str, str | None] | None:
"""(subject, tenant) of the request's credential, as your UI authenticates it."""
user = current_user(request)
return (user.id, user.tenant_id) if user else None
RungentHost(
app,
keys=load_public_keys([json.loads(os.environ["RUNGENT_PUBLIC_JWK"])]),
audience="https://console.example.com",
identity=caller,
)
@app.post("/api/vms/{vm_id}/stop", openapi_extra=op("stop_vm", effect="update"))
async def stop_vm(vm_id: str, request: Request, rungent: RungentCall) -> Vm:
if rungent is not None: # the call came through rungent, approved by the user
audit(actor="rungent", user=rungent.sub, run=rungent.rid, approval=rungent.apr)
return stop(current_user(request), vm_id)
audience is your public origin, the same as rungent's RUNGENT_HOST_ORIGIN. A request without the
header passes untouched; one that fails a check gets
401 {"detail": "rungent_assertion_invalid", "code": "<check>"}. RungentCall is the verified
AssertionClaims (sub, ten, op, rid, cid, sid, apr, …) or None for a direct user
call. An HTTPException your identity function raises is answered as it is.
RungentHost option |
Use it when |
|---|---|
public_url="https://console.example.com/gw" |
A proxy strips a path prefix before FastAPI. The URL the assertion binds is rebuilt as public_url plus the raw path and query; it defaults to audience. |
replay_cache=Redis.from_url("redis://cache:6379/0") |
You run several workers or replicas. Anything with redis-py's set(key, value, *, nx=True, ex=seconds), sync or async; the default MemoryReplayCache() lives in one process. |
openapi=lambda: catalog_document |
The app is a gateway with no route per operation. Operations are then matched by method and path template against that document; forward requests upstream with strip_rungent_headers(request.headers). |
During a key rotation, pass both public keys to load_public_keys.
Search and form operations#
A role="search" operation answers SearchResponse; rungent calls it as the user, so return only
what that user may see (Search and knowledge):
from rungent import SearchHit, SearchResponse
@app.get("/api/vms/search", openapi_extra=op("search_vms", role="search"))
async def search_vms(request: Request, q: str, limit: int = 10) -> SearchResponse:
return SearchResponse(hits=[
SearchHit(type="vm", id=vm.id, title=vm.name, url=f"/console/instance/{vm.id}", content=vm.description)
for vm in find_vms(current_user(request), q, limit)
])
A role="form" operation receives the arguments known so far and answers a Form
(Forms and approvals):
from typing import Any
from rungent import ChoiceQuestion, Form, FormOption, TextQuestion
@app.post("/api/vms/form", openapi_extra=op("vm_form", role="form"))
async def vm_form(args: dict[str, Any]) -> Form:
return Form(
prompt="Create a server",
questions=[
TextQuestion(id="name", prompt="Name", required=True),
ChoiceQuestion(id="zone_id", prompt="Zone", required=True,
options=[FormOption(id=z.id, label=z.name) for z in await list_zones()]),
],
)
@app.post("/api/vms", openapi_extra=op("create_vm", description="Create a cloud server (VM).", form="vm_form"))
async def create_vm(body: VmSpec, request: Request) -> Vm: ...
The Python kit at a glance#
Everything imports from rungent, except the FastAPI integration in rungent.fastapi.
| Name | What it is |
|---|---|
op(name, **keys) |
{"x-rungent": {...}} for openapi_extra, checked against the x-rungent schema. Typed nested objects: Confirmation, Reference, Next, Cli. |
RungentHost, RungentCall |
The assertion middleware, and the dependency that hands a route its verified claims. |
Identity, ADMIN_SCOPE |
The identity answer; "rungent:admin". |
SearchHit, SearchResponse |
The search answer: at most 50 hits, excerpt ≤ 300 and content ≤ 4000 characters. |
Form, TextQuestion, ChoiceQuestion, FormOption |
The generic form: 1 to 24 questions with unique ids. |
load_public_keys(jwks) |
Public keys by kid from the JWKs rungent keys generate prints. |
verify_assertion(token, *, keys, audience, method, url, body, remember) |
The signature, lifetime, audience, request and replay checks, without FastAPI; url is the full URL as sent, body the exact bytes. |
check_call(claims, *, subject, tenant, op, approval) |
The user, operation and approval checks. |
RungentAssertionError |
Raised by both, with code: the check that failed. |
args_hash, canonical_json |
The hash an approval binds to, as in TypeScript. |
strip_rungent_headers(headers) |
A copy without Rungent-Assertion and Rungent-Host-Assertion. |
Failure codes: malformed, unknown_key, bad_signature, expired, not_yet_valid,
too_long, audience, method, url, body, replay, subject, tenant, operation,
approval_missing.
Any other language#
Acahti, written in Go, implements the contract in its own code. Keep the OpenAPI generator you
have (swag, springdoc, a hand-written file): it only has to pass x-rungent through. The identity
operation answers {"subject": "u_123", "tenant": "t_9", "name": "Ada Lovelace"}. Then verify
the assertion, rejecting the request with 401 and rungent_assertion_invalid unless every check
holds:
| Check | Holds when |
|---|---|
| Signature | The header is {"alg":"EdDSA","typ":"rungent-call+jwt","kid":…} and the signature verifies with the pinned key of that kid |
| Lifetime | exp - iat ≤ 60, exp has not passed by more than 60 seconds, and iat is not more than 60 seconds ahead |
| Audience | aud is your public origin |
| Request | htm is the method; htu is your public origin followed by the path and query as received; bsh is the base64url SHA-256 of the exact body bytes |
| Replay | jti was not seen before; keep it until exp plus the skew, shared by every process |
| User | sub, and ten when present, equal the identity your API resolved from the credential |
| Operation | op is the x-rungent.name of the operation that serves this method and path |
| Approval | When that operation needs approval (every write, by default), apr is present |
The two cryptographic checks, in Go's standard library:
// keys: kid → ed25519.PublicKey, decoded from the base64url "x" of each pinned JWK.
func verifySignature(token string, keys map[string]ed25519.PublicKey) (claims []byte, err error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return nil, errInvalid
}
raw, err := base64.RawURLEncoding.DecodeString(parts[0])
var header struct{ Alg, Kid, Typ string }
if err != nil || json.Unmarshal(raw, &header) != nil || header.Alg != "EdDSA" || header.Typ != "rungent-call+jwt" {
return nil, errInvalid
}
key, ok := keys[header.Kid]
sig, err := base64.RawURLEncoding.DecodeString(parts[2])
if !ok || err != nil || !ed25519.Verify(key, []byte(parts[0]+"."+parts[1]), sig) {
return nil, errInvalid
}
return base64.RawURLEncoding.DecodeString(parts[1])
}
// bsh: the body exactly as received, before any parsing.
func bodyHash(body []byte) string {
sum := sha256.Sum256(body)
return base64.RawURLEncoding.EncodeToString(sum[:])
}
For htu, use the public origin even when rungent reaches you on an internal address (in Go,
origin + r.URL.RequestURI()).
Run rungent serve beside your API#
Make a signing key first. The command prints the public JWK, for your API, and writes the private one, for rungent, to a new file:
npx rungent keys generate --kid rungent-dev -o rungent-dev.private.jwk > rungent-dev.public.jwk
RUNGENT_URL=http://localhost:8000 \
RUNGENT_HOST_ORIGIN=http://localhost:8000 \
RUNGENT_HOST_BASE_URL=http://localhost:8001 \
RUNGENT_HOST_OPENAPI=/openapi.json \
RUNGENT_SIGNING_KEY="$(cat rungent-dev.private.jwk)" \
RUNGENT_SECRET="a development secret of 32 bytes or more" \
RUNGENT_DATABASE_URL=sqlite:rungent.sqlite \
RUNGENT_MODELS='[{"id":"main","provider":"openai","model":"gpt-4.1-mini","apiKey":"sk-…"}]' \
PORT=8787 \
npx rungent serve
RUNGENT_HOST_ORIGIN is the origin the browser sees; RUNGENT_HOST_BASE_URL is where rungent reaches
your API. rungent serve needs Node.js 24; the Docker image ghcr.io/rungent/rungent-server runs the
same server. Every variable is in Deploy.
Put both behind one origin#
Any reverse proxy works. In development, Caddy does it in a few lines:
# Caddyfile
:8000 {
@rungent path /rungent/* /mcp /skill.md /llms.txt /.well-known/rungent-keys.json
handle @rungent {
reverse_proxy localhost:8787
}
handle {
reverse_proxy localhost:8001
}
}
The nginx version for production is in Deploy. Then check it with a token your API accepts:
npx rungent check --openapi http://localhost:8001/openapi.json
curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/skill.md
RUNGENT_HOST=http://localhost:8000 RUNGENT_TOKEN=$TOKEN npx rungent vm stop vm-42
/skill.md lists list_vms and stop_vm. The CLI asks you to confirm, then rungent calls
POST /api/vms/vm-42/stop as you. For the dock in your pages, add it exactly as in
JavaScript, served from :8000.
Where to go next#
For agents: python.mdEdit this page