Skip to main content

Pynect

Pynect keeps a Chanx API in Python, generates its TypeScript client, and lets the same generated channels connect remotely over WebSocket or locally over a Unix socket/Windows named pipe.

It deliberately does not proxy arbitrary Python objects. Chanx owns messages, validation, routing, streaming, and client types.

Install

bun add pynect @chanx-js/client

Python projects use Chanx directly:

[project]
name = "model-catalog"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
  "chanx[fast_channels]>=2.14,<3",
  "pynect-worker>=0.8,<1",
]

[tool.pynect]
app = "server:app"

app is the only Pynect setting normally needed. It identifies the FastAPI or Starlette ASGI application containing the Chanx routes. It defaults to server:app.

The example directory contains a complete model-catalog project with generated TypeScript plus local IPC and remote WebSocket clients.

Write the API in Python

from collections.abc import AsyncIterator
from typing import Literal

from chanx.core.decorators import channel
from chanx.fast_channels.websocket import AsyncJsonWebsocketConsumer
from chanx.messages.base import BaseMessage
from fastapi import FastAPI
from pydantic import BaseModel
from pynect_worker import ws_handler


class GreetPayload(BaseModel):
    name: str


class GreetRequest(BaseMessage):
    action: Literal["greet"] = "greet"
    payload: GreetPayload


class GreetManyRequest(BaseMessage):
    action: Literal["greet_many"] = "greet_many"
    payload: GreetPayload


class GreetResponse(BaseMessage):
    action: Literal["greeted"] = "greeted"
    payload: str


@channel(name="greeter")
class Greeter(AsyncJsonWebsocketConsumer):
    @ws_handler
    async def greet(self, message: GreetRequest) -> GreetResponse:
        return GreetResponse(payload=f"Hello {message.payload.name}")

    @ws_handler
    async def greet_many(
        self, message: GreetManyRequest
    ) -> AsyncIterator[GreetResponse]:
        for name in message.payload.name.split(","):
            yield GreetResponse(payload=f"Hello {name.strip()}")


app = FastAPI(title="Greeter", version="1.0.0")
app.router.add_websocket_route("/ws/greeter", Greeter.as_asgi())

Annotate a handler with AsyncIterator[Response] and yield messages to make it a stream. Pynect forwards each yield, emits Chanx's protocol-level complete frame when the iterator exits normally, and types the corresponding request as an async iterator. Application messages do not need a completion model or flag:

import { createPynectClient, greeter } from './_generated/model-catalog/index.js';

const connection = createPynectClient(clientOptions).connect(greeter);
const result = await connection.request({
  action: 'greet_many',
  payload: { name: 'Ada, Grace' },
});

for await (const response of result) {
  console.log(response.payload);
}

Pynect records iterator actions on the generated channel descriptor. Its generated createPynectClient() uses that metadata so TypeScript infers normal actions as Promise<Response> and iterator actions as AsyncIterable<Response> through the same connection.request() method. The request needs only its action and payload. Concurrent streams use Chanx request refs for correlation and share one physical socket.

Generate TypeScript

bunx pynect generate

By default this writes both the exported schema and Chanx modules to:

_generated/model-catalog/
  asyncapi.json
  channels.ts
  index.ts
  schemas.ts

Set out under [tool.pynect] when the TypeScript project lives elsewhere:

[tool.pynect]
app = "server:app"
out = "../web/src/_generated/model-catalog"

Configuration precedence is command options, [tool.pynect], then defaults. Pynect uses Pyfig to resolve uv and Python, and runs schema export inside the configured uv project. Optional python, uv, debug, validation, and format fields are available for projects that need them.

Remote connection

Generated modules are standard @chanx-js/client descriptors:

import { createPynectClient, greeter } from './_generated/model-catalog/index.js';

const client = createPynectClient({ baseUrl: 'wss://api.example.com' });
const connection = client.connect(greeter);
const response = await connection.request({
  action: 'greet',
  payload: { name: 'Ada' },
});

Local IPC

For a local process, start the same ASGI app through Pynect and pass its client options to Chanx:

import { startIpcServer } from 'pynect';
import { createPynectClient, greeter } from './_generated/model-catalog/index.js';

await using server = await startIpcServer({ root: '../python' });
const client = createPynectClient(server.clientOptions);
const connection = client.connect(greeter);

startIpcServer() always starts a worker owned by the current process. The launcher captures the real Python PID, and the worker watches its parent PID, so it exits if the parent disappears. Use await using for scoped cleanup or call await server.close() explicitly. Both are safe to call more than once.

For a long-lived command, wait for the worker:

const server = await startIpcServer({ root: '../python' });
await server.wait();

Pynect forwards SIGINT, SIGTERM, SIGHUP, and the platform shutdown signal (SIGQUIT on macOS/Linux or SIGBREAK on Windows) through the owned worker tree. On macOS/Linux, uv and Python run in an isolated process group so the whole group receives the signal. On Windows, Pynect follows uv's behavior and lets the console deliver Ctrl+C or Ctrl+Break directly, avoiding an abrupt emulated signal; if Python starts after that event, the captured PID receives a retained shutdown signal. A custom parent signal handler remains authoritative. ensureIpcServer() remains available only when deliberately reusing an existing endpoint is desired.

Run a long-lived local server from the command line with:

bunx pynect serve

The default endpoint is <temp>/model-catalog.sock on macOS/Linux and \\.\pipe\model-catalog on Windows. Override it with MODEL_CATALOG_IPC_PATH or the ipcPath JavaScript option.

MIT licensed.

Metadata

Release files for pynect-worker 0.8.7

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

Source distribution (sdist)

Source distribution for pynect-worker 0.8.7
File Size Uploaded Provenance Actions
pynect_worker-0.8.7.tar.gz 9.0 kB Without provenance Details for pynect_worker-0.8.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pynect-worker 0.8.7
File Interpreter ABI Platform Actions
pynect_worker-0.8.7-py3-none-any.whl Python 3 none any Details for pynect_worker-0.8.7-py3-none-any.whl

Total release size: 19.8 kB

Release files / pynect_worker-0.8.7.tar.gz

Download URL pynect_worker-0.8.7.tar.gz
Size 9.0 kB
Tags Source
SHA-256 checksum
How to use checksums
cb27e7f8989b300e242bc184f6074e88e34f60a434a806312e0b84ad2ee94f89
BLAKE2b-256 checksum
How to use checksums
763524538be12b65b7a46fc78ae02b8364b676672204fadb1287619f2efc32b1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / pynect_worker-0.8.7-py3-none-any.whl

Download URL pynect_worker-0.8.7-py3-none-any.whl
Size 10.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0d1f548f4b0a86a3fea6273fbaf52072327e7d220723996bc5b915743f7b09b1
BLAKE2b-256 checksum
How to use checksums
af6767d8664094b753cd2bd13b6bdc0f78bb1a65dd167c047ff2dc3b942bb143
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for pynect-worker 0.8.7

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