---
title: "Use MainSDK from Python"
description: "Add the native mainsdk library to a Python service, store data and files as one owner, and return problem details from an ASGI app."
section: "guides"
status: "Planned for 1.5"
spec: "python-sdk"
canonical: "https://mainsdk.dev/docs/guides/use-mainsdk-from-python"
updated: "2026-10-28"
---

# Use MainSDK from Python

> Add the native mainsdk library to a Python service, store data and files as one owner, and return problem details from an ASGI app.

Status: Planned for 1.5 · Canonical: https://mainsdk.dev/docs/guides/use-mainsdk-from-python · Updated: 2026-10-28

You will install `mainsdk`, run it on its local drivers, and wrap an ASGI app. It takes about 10 minutes. The library is native, pure Python with no dependencies. It shares no code with the TypeScript SDK, only `main.yaml`, the error codes and the wire formats.

## You need

- Python 3.10 or later and a `main.yaml` with `schema: 1` (`npx mainsdk init` writes one).
- The library is pre-release and not on PyPI. Install it from the MainSDK repository: `pip install ./packages/python`.

## 1. Call an interface

Calls are `async`. The request context travels in `contextvars`, so tasks you create inside a `scope` inherit it.

```python title="app.py"
from mainsdk import App, scope

app = await App.load()
with scope(tenant="tnt_a", user="u1"):
    file = await app.files.upload(b"hello", owner="u1", label="pii")
    orders = await app.db.orders.for_("u1").list()
```

A call that needs a tenant and has none raises `MAIN-TENANT-0001`.

## 2. Return problem details from ASGI

```python title="server.py"
from mainsdk.web import ProblemMiddleware

app = ProblemMiddleware(fastapi_app)
```

The middleware reads `traceparent`, sets the context, and renders any `MainError` as `application/problem+json` with its `code` and `fix`. Any other error returns a 500 with the message hidden.

## 3. Check the project

`npx mainsdk check` runs ruff (`MAIN-PYTHON-0001`), pyright in strict mode (`MAIN-PYTHON-0002`) and bandit (`MAIN-PYTHON-0003`) with the usual gates. A missing tool is a warning, `MAIN-PYTHON-0004`, never a pass. Run `pytest` too.

## Next

- Python agents load the `mainsdk-python` skill.
- Run the parity vectors against your install: `mainsdk conformance run --impl "python -m mainsdk.conformance" --json`.
