Metadata-Version: 2.5
Name: mettr
Version: 0.2.0
Summary: Live analytics for websites and SaaS products: mettr for Python, with Django, FastAPI, Starlette and Flask middleware
Project-URL: Homepage, https://mettr.app
Project-URL: Documentation, https://mettr.app/docs/python
Project-URL: Repository, https://github.com/mettrhq/mettr-python
Author: mettr
License-Expression: MIT
License-File: LICENSE
Keywords: analytics,crawlers,dashboard,django,fastapi,flask,live,privacy,realtime
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Django
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: django
Requires-Dist: django>=4.2; extra == 'django'
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == 'flask'
Provides-Extra: starlette
Requires-Dist: starlette>=0.37; extra == 'starlette'
Description-Content-Type: text/markdown

# mettr for Python

Live analytics for websites and SaaS products: who is on your site right
now, what they do, where they came from and what broke, with no delay.
This package sends a Python app's side of it to [mettr](https://mettr.app):
your product's own events, crawlers' visits (search engines and AI
crawlers seldom run the browser script), 404s, exceptions, response times
and subscriptions, and serves the browser script from your own domain.

```bash
pip install mettr
```

Python 3.10 or later, no dependencies. Django, FastAPI, Starlette and
Flask have their middleware below.

## Settings

The client reads the environment; arguments win.

| variable | what |
|---|---|
| `METTR_SECRET_KEY` | the site's secret key (mettr, the site's settings, Tracking); keep it on the server |
| `METTR_PUBLIC_KEY` | the site's public key, for the script tag and the proxy |
| `METTR_ENABLED` | `true` or `false`; by default on once a key is set (Django: off while `DEBUG`) |
| `METTR_PROXY_PATH` | the first-party path, `_live` by default; empty serves the script from mettr |
| `METTR_ENDPOINT` | where mettr runs, `https://mettr.app` |

## Django

```python
INSTALLED_APPS = [..., "mettr.django"]

MIDDLEWARE = [
    ...,
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "mettr.django.MettrMiddleware",     # after auth, so events carry the user
    ...,
]

METTR = {"SECRET_KEY": env("METTR_SECRET_KEY"), "PUBLIC_KEY": env("METTR_PUBLIC_KEY")}
```

```django
{% load mettr %}
<head>{% mettr_script %}</head>
```

Sign-ins and sign-ups are sent as `login` and `signup`, staff
(`user.is_staff`) send nothing, and an app behind its own proxy sets
`"TRUST_FORWARDED": True`. Sync and async views alike.

```python
from mettr.django import get_mettr, visitor

get_mettr().event("export", {"format": "csv"}, visitor(request))
```

## FastAPI and Starlette

```python
from mettr import Mettr
from mettr.starlette import MettrMiddleware, visitor

mettr = Mettr()
app.add_middleware(MettrMiddleware, mettr=mettr)

@app.post("/signup")
def signup(request: Request):
    request.state.mettr_user_id = user.id      # the request's events carry it
    mettr.event("signup", {"plan": "pro"}, visitor(request))
```

Behind a proxy of your own, pass `trust_forwarded=True` (or run uvicorn
with `--proxy-headers`). In a Jinja template: `{{ mettr.script_tag()|safe }}`.

## Flask

```python
from mettr.flask import MettrFlask

mettr = MettrFlask(app)     # or MettrFlask().init_app(app)
```

```jinja
<head>{{ mettr_script() }}</head>
```

Flask-Login's user is read when it is installed; pass `user=` and `staff=`
otherwise. Behind a proxy, wrap the app in `ProxyFix`.

## Your own events

```python
from mettr import Mettr, Visitor

mettr = Mettr()
mettr.event("signup", {"plan": "pro"}, Visitor(user_id="42"))
mettr.revenue("order", 49.5, "EUR", {"items": 2})
mettr.error("PaymentFailed", {"provider": "stripe"})
```

Props are flat: up to 30, each a string, number, boolean or null. Events
wait a second to go together, sent from a background thread; a serverless
function (or a script) calls `mettr.flush()` before it ends.

## Subscriptions

For MRR when your billing is your own (anything but Stripe, Paddle or
Polar, which mettr reads itself), send each subscription whenever it
changes, and every one once for the history:

```python
mettr.subscription(
    "sub_1",
    "active",           # active, past_due, trialing, paused, canceled
    19,                 # each cycle, before tax, in the main unit
    "USD",
    interval="month",   # day, week, month, year
    user_id="42",
    plan="Pro",
)
```

## Your MCP server

If you run an MCP server over HTTP (FastMCP's `streamable_http_app()` or
`sse_app()`, or any other ASGI app), wrap it with `McpMiddleware`, outside
its auth, so the 401 that sends a client to sign in is counted too:

```python
from mettr.mcp import McpMiddleware

app = McpMiddleware(
    mcp.streamable_http_app(),
    mettr=mettr,
    user=lambda scope: scope["state"].get("user_id"),  # who signed in, from your auth
)
```

Each call an AI assistant makes is sent as an event: `mcp.connect` (the
handshake), `mcp.tool`, `mcp.resource` and `mcp.prompt`, with the tool's,
resource's or prompt's name, the client (Claude, ChatGPT, Cursor…), its
version, the protocol, how the call ended (`ok`, `tool_error`, `error`,
`sign_in`, `forbidden`, `throttled`, `failed`), the HTTP status of a
failure, the JSON-RPC error code and the time it took, streamed answers
included. Lists and pings are not sent. The MCP panels read them with
mettr's Pro plan.

The arguments and what came back are never sent; a failed call's message
only with `errors=True` (its first 200 characters), as it may quote what
the user's assistant sent. The client's address and user agent are not
sent: they are the assistant's servers', so mettr counts the person by
`user` (or a hash of the session). Requests through it are never sent as
crawler visits, 404s or response times by `MettrMiddleware`.

## History and deploys

```python
mettr.import_events(rows)      # each with ts and source_id: a second run adds nothing
mettr.annotation("Deployed v2.4", url="https://github.com/acme/app/releases/v2.4")
```

## What is sent on its own

- A crawler's request: its page and status, as a crawl (mettr names the
  crawler and checks it against its owner's network).
- A person's 404, as an error.
- An exception, by its class only, never its message; a client's error
  (a status under 500) is not one.
- One request in twenty's response time, by route.
- Nothing for `/up` (`ignore`), for staff, or while mettr is off.

Sending never raises into your app: a failed batch answers `False` and is
told to `on_error`, without its events.

## License

MIT
