Skip to main content

Agentrail for Python

CI PyPI Python Licence

agentrail-python adds your Python servers to the journeys Agentrail follows: the requests they answer, the calls they make, the identity your application verified, the milestones you name, your logs and your MCP traffic. Bodies and raw identities never leave your process; MCP arguments and results leave it only when you turn on capture_payloads.

Works with FastAPI, Starlette, Django, Flask and any ASGI or WSGI application. Requires Python 3.10 or later.

Install

pip install agentrail-python

Add [httpx], [requests] or [mcp] for those integrations, for example pip install "agentrail-python[httpx,mcp]".

In Agentrail, open Journeys, select Set up and choose Your servers. Agentrail shows the source's Secret and the workspace's Hash key once, with your collector address. Keep both on your servers, never in a page, for example as AGENTRAIL_SECRET and AGENTRAIL_HASH_KEY.

Quick start

import os
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI

import agentrail_python as ar
from agentrail_python.asgi import AgentrailASGIMiddleware
from my_app.auth import current_user  # your own authentication

# Once, when the process starts.
agentrail = ar.init(
    ar.Options(
        collector=ar.CollectorOptions(
            endpoint="https://<collector>/ingest/otlp",
            secret=os.environ["AGENTRAIL_SECRET"],
        ),
        hash_key=os.environ["AGENTRAIL_HASH_KEY"],
        service_name="orders-api",
    )
)


@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    agentrail.shutdown()  # sends what is still queued


app = FastAPI(lifespan=lifespan)
app.add_middleware(AgentrailASGIMiddleware, client=agentrail)  # records each request


@app.post("/orders/{order_id}/confirm")
async def confirm(order_id: str, user=Depends(current_user)):
    # Only after your application has authenticated the caller. Ids are hashed.
    agentrail.identify(ar.VerifiedIdentity(kind="user", id=user.id))

    # A business step, with a stable name.
    with agentrail.start_milestone(
        "checkout.confirm", ar.MilestoneContext(surface="custom", kind="checkout.confirm")
    ):
        ...

Other frameworks wrap the application once:

application = agentrail.asgi(get_asgi_application())  # Django (ASGI), Starlette, any ASGI app
application = agentrail.wsgi(get_wsgi_application())  # Django (WSGI)
app.wsgi_app = agentrail.wsgi(app.wsgi_app)            # Flask, any WSGI app

MCP

With the official mcp SDK, add the middleware first. Each JSON-RPC message your server receives becomes a step: its method, outcome and JSON-RPC error code, message sizes, the calling client and, on stateful streamable HTTP, a keyed hash of the session ID (the opening initialize included). Wrapped tools, resources and prompts are child spans of that step. Step names carry the tool, the prompt and the requested resource URI (without its userinfo, query or fragment), with payload capture off too.

A wrapped tool that raises is a failed call: MCPServer answers the exception with an isError result of its own, and the step keeps isError but carries the exception's type. A result your tool returns with isError is a failed result (tool_error).

from mcp.server.mcpserver import MCPServer
from agentrail_python.mcp import mcp_capture

capture = mcp_capture(agentrail)
server = MCPServer("orders", middleware=[capture.middleware])  # first in the list
server.tool(name="checkout")(capture.tool("checkout", checkout))

# Streamable HTTP: wrap the app so each MCP step sits under its HTTP request.
app = agentrail.asgi(server.streamable_http_app())

Behind agentrail.asgi (or agentrail.wsgi), a step whose message came by HTTP also carries that request's method, URL (its query cut to Agentrail's markers), user agent, header names (never a value), Accept and Accept-Encoding (each only when the request sent one), and the message's JSON-RPC id. ASGI gives the names in the order they arrived; WSGI keeps no order, so they are sent lower-cased and sorted. A message over stdio, or from an in-memory client, carries none; a wrapped function that is the step carries them when it receives the Context.

Arguments and results are off by default. To send them, pass a redact hook; it gets copies of method, name, request and response and returns what to send, or None to send nothing:

def redact(payload: ar.McpPayload):
    request = dict(payload["request"] or {})
    request.pop("arguments", None)
    return {"request": request, "response": payload["response"]}


capture = mcp_capture(agentrail, capture_payloads=ar.CapturePayloads(redact=redact))

When a span's two payloads together pass 14 MiB, they are cut to fit on a character boundary, the longer first (both, when each passes half), and each cut side is flagged. A multi-round-trip requestState is never sent. A request the MCP SDK refuses before its middleware runs (a malformed body, a wrong header, an unknown session) is no MCP step; behind agentrail.asgi it is still recorded as its HTTP request.

When a customer's CLI uses agentrail-cli-sdk, its requests say which command an agent ran, in which run and session. The ASGI and WSGI middleware record that on the request's span, the session only as a keyed hash, so the agent's CLI runs join its journey. There is nothing to configure.

Agentrail never fails your request: anything it could not capture or send goes to your on_error callback.

Documentation

Install the Python SDK Setup for each framework, outgoing calls, identity, milestones, logs, MCP and location
Python SDK reference Every option, an existing OpenTelemetry setup, delivery and error codes, framework notes
Leave out your own servers Skip calls between your own services
Plugin workflow tracking Report workflow attempts and plugin calls on milestones
What Agentrail records What is sent, what is hashed, and what never leaves your process

The same SDK is available for Node (agentrail-node) and Go (agentrail-go).

Contributing

Issues and pull requests are welcome. See CONTRIBUTING.md for development and releasing.

Licence

Apache-2.0.

Metadata

Release files for agentrail-python 0.3.0

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

Source distribution (sdist)

Source distribution for agentrail-python 0.3.0
File Size Uploaded Provenance Actions
agentrail_python-0.3.0.tar.gz 96.9 kB With provenance Details for agentrail_python-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for agentrail-python 0.3.0
File Interpreter ABI Platform Actions
agentrail_python-0.3.0-py3-none-any.whl Python 3 none any Details for agentrail_python-0.3.0-py3-none-any.whl

Total release size: 156.4 kB

Release files / agentrail_python-0.3.0.tar.gz

Download URL agentrail_python-0.3.0.tar.gz
Size 96.9 kB
Tags Source
SHA-256 checksum
How to use checksums
eae378f22ce538f5fa83643732770b8fc2469318b65edd53ebd585e782fb12b1
BLAKE2b-256 checksum
How to use checksums
2680641bcd771fd8f3bf7a89a4652e73fc9aab46d589c93897d76c71d146460a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 18, 2026.

Transparency log

Release files / agentrail_python-0.3.0-py3-none-any.whl

Download URL agentrail_python-0.3.0-py3-none-any.whl
Size 59.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f6219af8ccf323a07c2310d3f81a9f3d635491162974b60585e83f21861edd21
BLAKE2b-256 checksum
How to use checksums
144f0663855d745641576ae7cfc3dc857171650d39ebfb9d3234b4869d3f91f9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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 Nov 18, 2026.

Transparency log

Security for agentrail-python 0.3.0

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for agentrail_python-0.3.0.tar.gz

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 Nov 18, 2026.

Transparency log

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