Skip to main content

unsworn (Python SDK)

Write Unsworn handlers in Python. A handler is a plain function, sync or async:

from unsworn import json

def get_user(req, ctx):
    # req.params["id"] is already validated and converted by Unsworn,
    # and ctx["auth"] holds the verified token claims.
    return json({"id": req.params["id"], "name": "Ada"})
# unsworn.toml
[[route]]
path = "/users/{id}"
method = "GET"
handler = "src/users.py#get_user"
params = { id = { type = "integer", min = 1 } }

That's all the config a Python handler needs: with no [runtimes.*] for .py, Unsworn runs python3 -u -m unsworn.worker (through uv run in a project with a uv.lock). Write a runtime to run it another way.

Types from the config

unsworn gen writes a route's contract as types, and Request takes them:

[gen]
python = "unsworn_gen.py"
from unsworn import json
from unsworn_gen import GetUserRequest

def get_user(req: GetUserRequest, ctx):
    return json({"id": req.params["id"]})   # a type checker knows id is an int

unsworn dev keeps the file current. See docs/types.md.

Calling other handlers

ctx.call calls a function: a handler declared as [[function]] in the config, in any language.

from unsworn import CallError, json

def search(req, ctx):
    try:
        ranked = ctx.call("rank", {"ids": ids, "user": ctx["auth"]["sub"]})   # a Rust handler
    except CallError as e:
        if e.status == 504:
            ranked = ids   # too slow: answer unranked
        else:
            raise
    return json(ranked)

In an async def handler, await ctx.call(...). Unsworn checks the input against the function's schema, and the function gets this request's context and what is left of its time.

ctx is still a dict: ctx["auth"], ctx.get("tenant").

Reaching other services

ctx.fetch sends a request to an outbound service, declared as [outbound.<name>] in the config. Unsworn makes the request and adds the service's credential, so the handler never holds it:

answer = ctx.fetch("stripe", "/v1/charges", json={"amount": 1200, "currency": "usd"})
if not answer.ok:
    return json({"error": "the charge failed"}, status=502)
charge = answer.json()

In an async def handler, await ctx.fetch(...). It gives back the service's answer whatever its status, and raises FetchError when the request isn't allowed or got no answer.

Replies

Return Response
json(value, status=200, headers=None) JSON body
text(value, status=200, headers=None) Text body
body(bytes_or_iterator, status=200, headers=None) Raw bytes, or streamed when given an iterator or async iterator
{"status": 204} No body
next({"tenant": "acme"}) From a before handler: continue, adding context

MCP tools

A handler listed in [[mcp.tool]] is an ordinary handler. Its arguments arrive as req.json, already validated, and ctx["mcp"] has the tool name, protocol_version and, when the client sends it, client. Unsworn turns the reply into an MCP tool result (see docs/mcp.md):

from unsworn import content, json, tool_error

def get_forecast(req, ctx):
    city = req.json["city"]
    if city not in CITIES:
        return tool_error(f"unknown city {city}")  # the model sees this
    return json({"city": city, "days": forecast(city)})

def chart(req, ctx):
    return content([{"type": "image", "data": png_b64, "mimeType": "image/png"}])
Return Tool result
json(value) Structured content, plus a text copy
text(value) One text block
content(blocks, json=value) MCP content blocks as given; with json, structured content too
tool_error(message) isError: true with message

The request

req has method, path, route, params, query, raw_query, headers (lowercase names), json, text, body (raw bytes), handler, phase, and cancelled (set when Unsworn cancels the request). ctx is a dict with auth (verified claims) and anything before handlers added.

On routes with stream_body = true, req.stream yields the body in chunks as it arrives: async for chunk in req.stream, or for in a sync handler.

Sync handlers run on threads, so one that blocks doesn't hold up other requests. A worker starts with one handler thread, which is the cheapest way to run handlers that return quickly or compute, since Python runs one thread at a time. When calls are queued and the threads are waiting on something, such as a database, it adds a thread for each queued call, up to UNSWORN_MAX_IN_FLIGHT (32 by default, set in the runtime's env). That takes it up to 40 ms the first time, and it retires the extra threads again after a while. Telling a waiting thread from a busy one needs Linux; on other systems queued calls get threads whenever none has run out of work. Handlers that compute in parallel use the runtime's workers, one process each: Unsworn starts with one and adds more while they're busy. print() output goes to stderr, which Unsworn collects into its logs.

Logging

The worker sends records from Python's logging module to Unsworn, tagged with the request being handled. extra values are kept as fields:

import logging

log = logging.getLogger(__name__)

def charge(req, ctx):
    log.info("charged card", extra={"amount": 1200})

The worker sets the root logger's level from Unsworn's, so there's nothing to configure.

Metadata

Release files for unsworn 0.5.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unsworn 0.5.0
File Size Uploaded Provenance Actions
unsworn-0.5.0.tar.gz 15.3 kB Without provenance Details for unsworn-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unsworn 0.5.0
File Interpreter ABI Platform Actions
unsworn-0.5.0-py3-none-any.whl Python 3 none any Details for unsworn-0.5.0-py3-none-any.whl

Total release size: 31.7 kB

Release files / unsworn-0.5.0.tar.gz

Download URL unsworn-0.5.0.tar.gz
Size 15.3 kB
Tags Source
SHA-256 checksum
How to use checksums
4b21462b9709cde94ffeab4a7d2ee10cec05e5bbc69e40abcb75066aef55e2b8
BLAKE2b-256 checksum
How to use checksums
e1741b80d3083ebf8a16f6d9878d98143ca6b39327da25c6e8721c4d31bbc39b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Omarchy","version":"4.5.0","id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / unsworn-0.5.0-py3-none-any.whl

Download URL unsworn-0.5.0-py3-none-any.whl
Size 16.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
103d7f07f18c1243927476102d4596ad1c66e53f593415105a1d185e47ecf793
BLAKE2b-256 checksum
How to use checksums
82cf0182fec7a194fa73a0c6f4c246872cd5533a85ebe653dbf448b8ad223ab9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Omarchy","version":"4.5.0","id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for unsworn 0.5.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page