> Markdown version of https://tuna.am/en/docs/guides/install/sdk/python/. Documentation index: [llms.txt](https://tuna.am/en/llms.txt), full text in one file: [llms-full.txt](https://tuna.am/en/llms-full.txt). Any page is available as Markdown: append `.md` to its URL without the trailing slash.

# Python

The Python SDK opens Tuna tunnels straight from your code: expose a local HTTP or TCP service at a public address without installing `tuna`.

* Two ways in: `listen` hands each incoming connection to your code, `forward` proxies connections to a local address.
* The main API is asyncio-based. The blocking `tuna_sdk.sync` suits plain scripts and Jupyter.
* Survives network failures: reconnects and keeps the same public address.
* A single dependency, [asyncssh](https://pypi.org/project/asyncssh/). Type hints are included (`py.typed`).

> **Info.** The API is not stable yet: it may change before v1.

The package is [tuna-sdk](https://pypi.org/project/tuna-sdk/) on PyPI, source code is on [GitHub](https://github.com/yuccastream/tuna-sdk-python).

## Installation

```shell
pip install tuna-sdk

```

The module name is `tuna_sdk`. Requires Python 3.10 or later.

If pypi.org is unavailable, the package is available in the `code.tuna.am` registry:

```shell
pip install tuna-sdk --extra-index-url https://code.tuna.am/api/packages/tuna/pypi/simple/

```

## Authentication

Create an [API key](https://my.tuna.am/api_keys?lang=en) with **Run tunnels** enabled (the **For tunnels** preset) and pass it in `Options.api_key` or the `TUNA_API_KEY` environment variable.

## Forward to a local service

`forward` proxies connections from the tunnel to a local address, `host:port` or `unix:///path/to.sock`, and runs until the task is cancelled or the tunnel ends for good:

```python
import asyncio
import tuna_sdk


def on_event(e: tuna_sdk.Event) -> None:
    if e.type == "connected":
        print("forwarding", e.url, "-> 127.0.0.1:8080")


asyncio.run(tuna_sdk.forward(tuna_sdk.Options(protocol="http", on_event=on_event), "127.0.0.1:8080"))

```

Without asyncio:

```python
tuna_sdk.sync.forward(tuna_sdk.Options(protocol="tcp", port="my-db"), "127.0.0.1:5432")

```

## Handle connections yourself

`listen` yields each connection as a `(reader, writer)` pair with the same methods as asyncio streams:

```python
async def main() -> None:
    async with tuna_sdk.listen(tuna_sdk.Options(protocol="tcp")) as tunnel:
        print("public URL:", tunnel.url)
        async for reader, writer in tunnel:
            asyncio.ensure_future(handle(reader, writer))

```

`tuna_sdk.sync.listen` yields a regular blocking `socket.socket`, so it works with `socketserver` and similar code:

```python
with tuna_sdk.sync.listen(tuna_sdk.Options(protocol="http")) as tunnel:
    print("public URL:", tunnel.url)
    for sock in tunnel:
        handle(sock)

```

Leaving the `with` block or calling `close()` stops accepting and reconnecting. Accepted connections keep working, and the tunnel stays connected until the last one is closed. `abort()` cuts them off too.

## Options

| `Options` field                            | Meaning                                                                                                                                                          |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `protocol`                                 | `http` or `tcp`, required                                                                                                                                        |
| `api_key`                                  | API key, defaults to `$TUNA_API_KEY`                                                                                                                             |
| `subdomain`, `domain`                      | HTTP: [reserved subdomain](https://tuna.am/en/docs/tunnels/http.md#reserved-subdomain) or [custom domain](https://tuna.am/en/docs/tunnels/http.md#custom-domain) |
| `port`                                     | TCP: [reserved port](https://tuna.am/en/docs/tunnels/ports.md) or its alias                                                                                      |
| `proxy_protocol`                           | TCP: [PROXY protocol](https://tuna.am/en/docs/tunnels/tcp.md#proxy-protocol) version, `1` or `2`                                                                 |
| `cidr_allow`, `cidr_deny`                  | TCP: client subnets allowed or rejected by the Tuna node                                                                                                         |
| `on_event`                                 | callback for tunnel events                                                                                                                                       |
| `connect_timeout`                          | limit on the wait for the first connection, in seconds; `None` means no limit                                                                                    |
| `server_url`, `ssl_context`, `client_name` | API address, TLS settings for it, client name reported to the server                                                                                             |

## Events and errors

`on_event` receives an `Event` of type `connected`, `reconnecting`, `reconnected`, `banner`, `session_expiring`, `terminated` or `local_error`. Calls never overlap and run on the event loop (for `tuna_sdk.sync`, on its background thread), so keep the callback short.

Network failures and temporary server errors are retried: the pause grows from 1 to 15 seconds with random jitter, and `Retry-After` is respected. If the node stops responding, `reconnecting` arrives with a `KeepAliveTimeoutError`. The tunnel ends with an exception when retrying is pointless; check it with `is_permanent`:

* `ServerError`: the API rejected the request — bad or revoked key, missing permission, unknown reserved name, unpaid plan;
* `TerminatedError`: the server closed the tunnel — it was deleted, suspended or hit the session time limit.

## Behavior worth knowing

* When either side of a forwarded connection closes, the connection is closed in both directions.
* The `Host` header and the PROXY protocol header reach your service as sent.
* The API client is `urllib` and honors `HTTPS_PROXY`. Connections to Tuna nodes are plain SSH and do not use the proxy.
* For a private CA, set `ssl_context`.
* asyncssh is licensed under EPL-2.0 or GPL-2.0-or-later; the SDK itself is MIT-licensed.
