Skip to main content

FastAPI middleware, auth, streaming infrastructure, and context management for the Matrx ecosystem

Project description

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 + ContextVar + get_app_context / set_app_context / try_get_app_context / clear_app_context
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 — the FastAPI Depends() helper that pulls AppContext into a route handler

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 to AppContext, and pushes AppContext onto the ContextVar.
  • Spawns the task as a background asyncio.Task.
  • Catches CancelledError (client disconnect) and generic exceptions — the latter are surfaced via emitter.fatal_error(...).
  • Emits heartbeat keepalives while the task is running.
  • Clears the ContextVar on 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.

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

matrx_connect-0.1.8.tar.gz (131.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

matrx_connect-0.1.8-py3-none-any.whl (117.6 kB view details)

Uploaded Python 3

File details

Details for the file matrx_connect-0.1.8.tar.gz.

File metadata

  • Download URL: matrx_connect-0.1.8.tar.gz
  • Upload date:
  • Size: 131.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for matrx_connect-0.1.8.tar.gz
Algorithm Hash digest
SHA256 01fd7778a1b9dee93fdcdccd5b811184509b8db2e032f22f411f1b7386974ca4
MD5 2c855866fe0ab276e810658af18c905e
BLAKE2b-256 cf4ee06f6fe3dfc5976696d722b8cf01b3a5c64f7d103d5bb0d18c6abc7415b3

See more details on using hashes here.

Provenance

The following attestation bundles were made for matrx_connect-0.1.8.tar.gz:

Publisher: publish-package.yml on AI-Matrix-Engine/aidream

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file matrx_connect-0.1.8-py3-none-any.whl.

File metadata

  • Download URL: matrx_connect-0.1.8-py3-none-any.whl
  • Upload date:
  • Size: 117.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for matrx_connect-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 cc9a9705d436a99525c5da3b287aa80f60559d3ee76e60c6ccc5203b94129b72
MD5 cece5b197a2e142e6854c97b3c380fd9
BLAKE2b-256 566b9681257beb098c71da0f28b3f0d389c22e652ddcbc35cea4a8f59ab8712a

See more details on using hashes here.

Provenance

The following attestation bundles were made for matrx_connect-0.1.8-py3-none-any.whl:

Publisher: publish-package.yml on AI-Matrix-Engine/aidream

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page