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
[runtimes.python]
extensions = [".py"]
command = "python3 -u -m unsworn.worker"
protocol = "framed"

[[route]]
path = "/users/{id}"
method = "GET"
handler = "src/users.py#get_user"
params = { id = { type = "integer", min = 1 } }

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. 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.3.2

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.3.2
File Size Uploaded Provenance Actions
unsworn-0.3.2.tar.gz 11.5 kB Without provenance Details for unsworn-0.3.2.tar.gz

Built distribution (wheel)

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

Total release size: 24.0 kB

Release files / unsworn-0.3.2.tar.gz

Download URL unsworn-0.3.2.tar.gz
Size 11.5 kB
Tags Source
SHA-256 checksum
How to use checksums
7073f2b71d54e2be5aaf5f75223ae270e21715ebc6cc831a1a2a9dabea5df906
BLAKE2b-256 checksum
How to use checksums
9ef5c88d212ef8aab90107c85792a456396a0c2e66317a369a9dd6954bda02d3
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.3.2-py3-none-any.whl

Download URL unsworn-0.3.2-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1cfdf977c016950421af222c93d14b9e21bf6e615f3066955c09c9f0a0811c26
BLAKE2b-256 checksum
How to use checksums
cac48ff8b0babd38ab2b81ea246f2bd1079970a1f196996944bd1ade7437e266
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.3.2

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