matrx-connect
FastAPI connectivity layer for the Matrx ecosystem: auth middleware, streaming-response infrastructure, request-scoped AppContext, and the Emitter protocol. Despite the name, "connect" is about connecting a FastAPI app to the Matrx streaming + auth contract — not database connectivity.
Install
pip install matrx-connect
Python 3.12+ required. Depends only on matrx-utils from the Matrx family.
What's in the box
| Module | What it does |
|---|---|
matrx_connect.context.app_context |
AppContext dataclass + sealed tenant factories (require_tenant_context, tenant_system_context, tenant_resource_context) + ContextVar helpers |
matrx_connect.context.emitter_protocol |
Emitter protocol — every method any producer can call (send_chunk, send_reasoning, send_phase, send_data, send_info, send_warning, fatal_error, send_end, tool events, …) |
matrx_connect.context.events |
Pydantic event payload schemas shared with the frontend |
matrx_connect.emitters.stream_emitter |
StreamEmitter — the JSONL/NDJSON HTTP streaming implementation |
matrx_connect.emitters.console_emitter |
ConsoleEmitter — dev/test implementation that prints to stdout |
matrx_connect.middleware.auth |
AuthMiddleware — pluggable JWT + admin-token + fingerprint resolution, with a resolve_guest callback hook |
matrx_connect.streaming.response |
create_streaming_response(ctx, task, *args, ...) — the ONLY public entry point for streaming endpoints |
matrx_connect.dependencies |
context_dep reads AppContext; authenticated_resource_bootstrap authenticates a declared resource route and returns only its literal X-Organization-Id claim |
The streaming endpoint pattern
Every streaming route follows this exact shape. It's enforced across every repo that uses matrx-connect, so that the behavior of heartbeats, client disconnects, and error handling stays consistent:
from fastapi import APIRouter, Depends
from matrx_connect import AppContext, context_dep
from matrx_connect.streaming import create_streaming_response
router = APIRouter()
@router.post("/topics/{topic_id}/search")
async def trigger_search(topic_id: str, ctx: AppContext = Depends(context_dep)):
return create_streaming_response(
ctx, _run_search, topic_id,
initial_message="Starting search…", debug_label="ResearchSearch",
)
async def _run_search(emitter, topic_id: str):
# AppContext is already set on the ContextVar.
# Cancellation + exception handling are done for you.
result = await do_work(topic_id)
await emitter.send_data(SearchResult(...).model_dump())
await emitter.send_end()
What create_streaming_response does for you:
- Creates the
StreamEmitter, attaches it toAppContext, and pushesAppContextonto theContextVar. - Spawns the task as a background
asyncio.Task. - Catches
CancelledError(client disconnect) and generic exceptions — the latter are surfaced viaemitter.fatal_error(...). - Emits heartbeat keepalives while the task is running.
- Clears the
ContextVaron exit.
Your task function never touches set_app_context / clear_app_context / CancelledError. If you find yourself reaching for those symbols in application code, extend create_streaming_response instead.
Wiring the auth middleware
from fastapi import FastAPI
from matrx_connect.middleware.auth import AuthMiddleware
app = FastAPI()
app.add_middleware(
AuthMiddleware,
jwt_secret=settings.JWT_SECRET,
admin_token=settings.ADMIN_TOKEN,
admin_user_id=settings.ADMIN_USER_ID,
resolve_guest=my_guest_resolver, # optional callback for fingerprint-based guests
)
After this, every request has an AppContext on request.state.context and context_dep will hand it to any route handler that depends on it.
Resource handlers that authorize a named row after middleware admission use
authenticated_resource_bootstrap. Pair it with the exact
authenticated_resource_routes(app, authenticated_resource_bootstrap) output
when configuring AuthMiddleware; it defers organization pre-refusal for
those method/path declarations without creating an organization-free or tenant
context. The handler still owns row authorization.
Standalone-friendliness
matrx-connect has a single sibling dependency (matrx-utils, for verbose-logging). It assumes no ORM, no database, no Supabase — wire those in from your app. The Emitter is a typing.Protocol, so you can hand create_streaming_response any object that satisfies the shape.
Contributing
See CLAUDE.md for package-specific import rules and conventions. This package lives in the aidream monorepo at github.com/AI-Matrix-Engine/aidream-current.
License
MIT.
Release files for matrx-connect 0.1.125
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| matrx_connect-0.1.125.tar.gz | 300.4 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| matrx_connect-0.1.125-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 534.5 kB
Release files / matrx_connect-0.1.125.tar.gz
| Download URL | matrx_connect-0.1.125.tar.gz |
|---|---|
| Size | 300.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b32771e4e52d8f87af35e7ca21db6c8aedac503fa82b7df299c6a6678a9242ff
|
|
BLAKE2b-256 checksum How to use checksums |
3725e8bd2be51613b42b8cbf791bf8b0663ac6b62a55f69256d18cd41d3c0ca3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 21, 2026.
Transparency logRelease files / matrx_connect-0.1.125-py3-none-any.whl
| Download URL | matrx_connect-0.1.125-py3-none-any.whl |
|---|---|
| Size | 234.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3687f4a2ea32ff89b2c3dbf4222c5a0213e3c50aab43a6ae8eb5837221b25ea7
|
|
BLAKE2b-256 checksum How to use checksums |
dd1e1a331e7566d05b737104d94468936b563f24f3d0e9c5ad26b1f659f5164a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Sep 21, 2026.
Transparency log