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.
The function joins the request's trace. To have it
called under a span of your own, pass that span's traceparent:
ctx.call("embed", value, traceparent=traceparent).
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.9.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| unsworn-0.9.0.tar.gz | 15.7 kB | Without provenance | Details for unsworn-0.9.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| unsworn-0.9.0-py3-none-any.whl | Python 3 | none | any | Details for unsworn-0.9.0-py3-none-any.whl |
Total release size: 32.4 kB
Release files / unsworn-0.9.0.tar.gz
| Download URL | unsworn-0.9.0.tar.gz |
|---|---|
| Size | 15.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4fb2c238d6da6e5e7483b8b7bd953c89adaaf728d3279f80efc53ad86f39d54b
|
|
BLAKE2b-256 checksum How to use checksums |
7c9d4d4a51d313ccdb9007d0b3a99aa09a46ebb84defaddc06b5bb297b1a269e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / unsworn-0.9.0-py3-none-any.whl
| Download URL | unsworn-0.9.0-py3-none-any.whl |
|---|---|
| Size | 16.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9e5617268cf7e321faf74d972c0b16674ec2c5bda1dd9f72c5a84e30605bb6bb
|
|
BLAKE2b-256 checksum How to use checksums |
21e717c83c3c6bffb3772588134081c0cddbb707fea191441a13107513e65fef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Debian GNU/Linux","version":"13","id":"trixie","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for unsworn 0.9.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.