Metadata-Version: 2.5
Name: lsquare
Version: 0.2.0b1
Summary: Record every tool call of an MCP server, and the agents inside them, for LSquare
License-Expression: MIT
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# lsquare

Record every tool call your MCP server handles, and the agent turns behind them, in LSquare.
Pre-release: LSquare is an invite-only beta, so [request access](https://lsquare.io) to get an API
key. During the beta, LSquare sends you a weekly report on your tool calls (the most used, failing
and slowest tools, missing tools and top intents), and exports on request.

- One line per MCP server. Nothing the SDK does can make a tool call fail, and it never raises.
- `capture()` never waits on the network, and `flush()` waits up to 2 seconds by default.
- Common private data is redacted, and long values shortened, before anything leaves your process.
- No runtime dependencies. Python 3.10 and later; the same events as LSquare's TypeScript SDK.
- Events are stored in the United States. If you serve customers in the EU, take that into account.

## Setup

```sh
pip install --pre lsquare
```

Set `LSQUARE_KEY` to your project key. Start with `LSQUARE_DRY_RUN=1`: nothing is sent, and the SDK
logs one line per event to standard error with its shape (fields, anything dropped, shortened or
redacted, and its size), never its content or IDs. Without a key, and outside dry run, the client is
disabled: `capture()` does nothing and `instrument()` leaves your servers exactly as they are, with
one warning.

## MCP servers

```python
import os
from lsquare import LSquare
from lsquare.mcp import instrument
from mcp.server.fastmcp import FastMCP

lsquare = LSquare(api_key=os.environ.get("LSQUARE_KEY"))   # once, at module level

mcp = FastMCP("orders")

@mcp.tool()
def search_orders(customer_id: str) -> str: ...

instrument(mcp, lsquare)                                     # the one line per server
```

`instrument()` takes a server of the official MCP Python SDK, 1.x (`FastMCP`, or a low-level
`Server`) or 2.x (`MCPServer`, or a low-level `Server`), or of fastmcp 3.x or 4.x (`FastMCP`). It
returns the server it was given, and instrumenting a server twice does nothing the second time.
Tools registered after it are covered too. Instrument a server before running it: a client that
listed its tools before keeps a copy without the extras (below) until it lists them again. On mcp
2.x, instrument after adding your own middleware to the server: replacing its `middleware` list
afterwards removes the wrapper.

Each call that reaches the server's `tools/call` dispatch becomes one `tool_call` event: the tool's
name, its arguments (`input`), its result, how it ended (`status`, and an `error` with its
`category`: `thrown`, `tool_error`, `protocol` or `timeout`), how long it took, the calling app and
protocol version, and the IDs below. Results are recorded as the SDK sends them, each string cut at
4,000 characters; turn inputs or results off everywhere, or for chosen tools, with `inputs` and
`results`. fastmcp's `call_tool()`, called from your own Python code, never reaches the dispatch and
makes no event.

The calling app is the name the MCP client gives itself. A client on a protocol version before
2026-07-28 gives it only in `initialize`, so on a stateless HTTP server its calls are recorded
without the calling app; their protocol version comes from the request's `MCP-Protocol-Version`
header, and a request without one is recorded without a version.

### What the defaults change in your server

On a high-level server three extras are on by default, so calls are grouped into tasks, each call
says why it was made, and agents can tell you what they couldn't find. They change what your server
shows its callers:

- every tool gains two optional inputs, `session_id` and `intent`, which the wrapper takes out of
  each call before the SDK checks it, so your code never sees them;
- some results gain one text block at the end, giving the agent a task ID;
- the server gains a tool, `get_more_tools`, which the wrapper answers itself.

Clients and scanners that flag changed tool definitions may warn your server's users once when you
add the SDK. Each extra can be turned off by itself, in your one `instrument()` call:

```python
instrument(mcp, lsquare, extras={
    "sessions": False,        # no session_id, no task ID line
    "intent": False,          # no intent
    "missing_tools": False,   # no get_more_tools
})                            # leave any of them out to keep it on
```

With all three off, the wrapper never changes arguments, results or errors. On a low-level `Server`
they're off ([below](#low-level-servers)). [The extras](#the-extras) says exactly what each one does.

### Agent details from inside a tool

When a tool runs an agent, `capture()` inside it adds the agent's details to the call's event. It
takes the event's own keys:

```python
lsquare.capture({"question": question, "answer": answer, "toolCalls": tool_calls,
                 "usage": {"inputTokens": 812, "outputTokens": 240, "costUsd": 0.004}})
```

- Call it on the client you passed to `instrument()`. A capture on another client goes as an event
  of its own, not linked to the call.
- The first `capture()` before the tool returns becomes the call's `agent` part, and its `orgId`,
  `userId` and `conversationId` fill the call's. Any other capture, before or after the tool
  returns, goes as its own `turn` event, linked by `callId`; `lsquare.current_call_id()` gives you
  the ID inside a tool, for a capture made later elsewhere.
- A sync tool's `capture()` is inside its call on every line, though mcp 2.x and fastmcp run sync
  tools in a worker thread. A thread your tool starts itself with `threading.Thread` doesn't carry
  the call by default (Python 3.14 can make it), and `ThreadPoolExecutor.submit` never does: pass
  `callId` there yourself.
- `flush()` inside a tool doesn't wait on itself: it sends everything else that's queued, and the
  call's own event is sent before its reply, within `flush_timeout_ms`. In an async tool use
  `await lsquare.aflush()`.

### Who the call is for: `identify`

```python
def identify(call):
    # call.tool_name, call.args, call.context, call.signal
    return {"orgId": ..., "userId": ..., "conversationId": ..., "metadata": {...}}

instrument(mcp, lsquare, identify=identify)
```

`identify` gets the tool name, the arguments as the client sent them (without the extras' inputs)
and the MCP SDK's request context (the session, the HTTP request), and returns the IDs you know, or
`None`. It may be a sync function, run on the client's own threads, or an async one, run on the
server's event loop; an async one needs asyncio, and on trio only a sync one runs. It runs alongside
the tool, never before it, so it adds no latency; the event waits for it at most a second after the
tool returns. At most 16 run at once (the client's `max_concurrent_hooks`); past that, it isn't
called. Its `signal` is aborted at its deadline (`signal.aborted`, `signal.wait(timeout)`,
`signal.add_listener(fn)`).

IDs from a `capture()` inside the call win over `identify`'s. If `identify` raises, takes longer,
is skipped at the limit or returns IDs that aren't valid strings or UUIDs, the call keeps its full event only
when a `capture()` inside it gave every ID field `identify` returned the last time it succeeded (a
`userId`, before it ever has). Otherwise it is sent as limited diagnostics: its ID, the tool's name,
its status, duration and error category, and nothing else. That keeps your call counts and error
rates complete, but these events aren't anonymous (their time and `callId` can be matched with other
records), and they can't be deleted by person. Each failure is reported to `on_error`.

On stateful HTTP, mcp 1.x and fastmcp 3.x run a session's handlers in the context of the request
that opened the session, so context variables your ASGI middleware sets (auth, tenants) hold the
first request's values there. Read the request from `call.context` (`call.context.request`) instead.

### `instrument()` options

| Option | Default | |
|---|---|---|
| `identify` | | `(call) -> {"orgId", "userId", "conversationId", "metadata"}` or `None`, sync or async |
| `inputs` | `True` | `False`, or `(tool_name) -> bool` |
| `results` | `True` | `False`, or `(tool_name) -> bool`. An `isError` result's text is result text too |
| `extras` | all on (high-level), off (low-level) | `{"sessions", "intent", "missing_tools"}` to booleans; one left out keeps its default. On a low-level server only `True` turns one on ([below](#low-level-servers)) |
| `wait_until` | | A callable taking an awaitable: each call's sending is handed to it ([serverless hosts](#serverless-hosts-and-shutting-down)) |
| `flush_before_reply` | `False` | Wait for each call's event to be sent, up to `flush_timeout_ms`, before replying |

In dry run, `instrument()` logs one line per server saying what the extras can change.

## The extras

### `session_id`: calls grouped into tasks

Every tool gets an optional `session_id` input, described to the agent as: "The ID of the task this
call belongs to. Leave it out on your first call. On every later call for the same task, send the ID
an earlier result gave you, and pass it to any subagent working on that task."

- A call with a valid ID (`ses_` and 22 letters, digits, `-` or `_`) is recorded with it. Any other
  value is taken out and ignored.
- A call whose tool called `capture()` with a `conversationId` is grouped by that.
- A call from a client on a protocol version before 2026-07-28 is grouped by its protocol session:
  a stateful HTTP server's `Mcp-Session-Id`, or one ID per stdio connection of a server run by its
  own `run_stdio_async()` (or fastmcp's `run()`). A stateless server has none, and neither has a
  low-level server you drive with your own `stdio_server()`.
- Any other call gets a new ID, in a text block at the end of the tool's own result: "Task ID:
  ses_…. Send it as session_id on later calls for this task, and pass it to any subagent working on
  it." The block goes at the end, so code that reads the first block still gets your tool's output,
  and the recorded result is your tool's, without it. Raised errors, results the SDK made instead
  (refused arguments, an output it couldn't convert), task acknowledgements and `input_required`
  rounds never get one.
- A result some middleware replaced gets no ID line: middleware that let the tool run and returned
  another result, or another `content` list (fastmcp's middleware included). One that edits a
  content block in place isn't noticed.
- Clients that read only `structuredContent` don't see the text block, so they never learn an ID
  to send back; their calls are still grouped by protocol session or `conversationId`.

### `intent`: why each call was made

Every tool gets an optional `intent` input, described as: "In one sentence, why you're calling this
tool and what the user is trying to do. No personal data or secrets." When it's a non-empty string
it's recorded, redacted and cut at 500 characters, whether or not the call's inputs are; anything
else sent as `intent` is taken out and ignored. It stays optional, so strict clients never refuse a
call that leaves it out.

### `get_more_tools`: what agents looked for

A server with at least one tool of its own gets one more tool, `get_more_tools`, marked read-only,
with a required `need` input (and the optional `session_id`): "Call this when none of the available
tools fits what you need, or one fits only in part. It doesn't return new tools: it tells the
server's developers what to add." The wrapper answers it ("Noted. No other tools are available
right now, and your request was passed on to the server's developers.") and records the request as
a `tool_call` event with `extra: "missing_tools"`, under the same `inputs` option as any tool. It's
added to the last page of a paged list. A server that registers its own `get_more_tools` keeps it,
and doesn't get LSquare's.

### Which tools get them

The wrapper reads each tool's definition as the server holds it, at every listing and call.

- A tool that already has an input called `session_id` or `intent` (by name, alias or validation
  alias) keeps it, untouched, and gets only the other. Each case is logged once.
- A tool gets the extras only when the SDK's validator for its arguments drops or refuses keys it
  doesn't declare, and nothing in it can read them: a plain pydantic model of fields (the one the
  SDK makes from your function's signature, or yours with `extra` set to `ignore` or `forbid`), or,
  on fastmcp, its function's own signature without `**kwargs`. A model with a model validator, its
  own `__init__` or `model_validate`, extra keys allowed, or a custom schema, could read any key, so
  that tool is left without the extras, logged once, and grouped only by its protocol session or
  `conversationId`.
- On fastmcp only plain `FunctionTool`s are read, and only while the server's tools are all its
  own: tools from mounted servers, proxies, OpenAPI providers or transforms (other than fastmcp's
  own enable and disable), tools injected by `ToolInjectionMiddleware`, and versions of a tool that
  disagree about these inputs leave those calls exactly as sent. Middleware of yours that answers a
  call with a tool of its own sees the arguments without the extras.
- A tool's listing shows an input only where its JSON Schema can take one more optional property
  without changing what it accepts: not, for instance, with a combinator, `const`, `enum`, a limit on
  the number of properties, or a recursive schema. The inputs are still taken out of its calls.

### Low-level servers

A low-level `Server` has no tool definitions the wrapper can read, so the extras are off. Turn each
on by passing it as `True`:

```python
instrument(server, lsquare, extras={"sessions": True, "intent": True, "missing_tools": True})
```

Do this only for a server whose instances list and serve their own tools, and list the same tools
to every request they serve, such as a stdio server, or a stateful one with an instance per session.
One request's listing decides another's calls, so don't turn them on for a server built per request,
or for one instance that lists different tools to different users.

- The wrapper calls your `tools/list` handler itself, every page, before changing anything (at most
  100 pages and 10,000 tools: a longer list leaves the extras off), in a copy of the context of the
  request that started the read, marked as a listing; its session and send functions are still that
  request's. It keeps what it lists until your server sends `notifications/tools/list_changed`, you
  replace the handler, or a client's listing shows a change. A tool removed from a list of several
  pages may go unnoticed until then. On mcp 1.x a session's notifications are seen from its first
  `tools/list` or `tools/call`; a change sent before that is caught when a client next lists.
- A tool gets the inputs only when its listed schema is a plain object of named properties
  (`additionalProperties` absent or `False`) that doesn't name them. A low-level handler can read any
  key, so by turning the extras on you let the listing speak for the tool: an input it doesn't name
  is taken out of the call.
- A call waits for that list at most 1 second after the wrapper started reading it. Past that, the
  call is passed on unchanged, and a strict tool may then refuse an `intent` an agent sends from an
  earlier listing. A read is given up after 10 seconds, whatever your handler does, and after one
  fails, none starts for 60 seconds unless your server sends `list_changed`.
- On mcp 2.x, a request on the 2026-07-28 protocol is passed on unchanged: change notifications go
  only to streams the wrapper can't see there.
- On mcp 1.x, the SDK turns a raised error, a failed input check and a failed output check alike
  into an `isError` result before the wrapper sees it: all are recorded as `tool_error`, and none
  gets the task ID line.

### A replaced `tools/call` handler

A high-level server whose `tools/call` handler you replace after `instrument()` (a later
`@server.call_tool()` on mcp 1.x, `add_request_handler("tools/call", ...)` on 2.x) is treated as a
low-level one from then on: only the extras passed as `True` stay on, read from its tool list as
above, its next listing included. One replaced before `instrument()` can't be told from the SDK's own
handler, so call `instrument()` first, or turn the extras off.

## Serverless hosts and shutting down

By default a call's event is sent by the client's own threads after the reply. On a host that stops
your process or its CPU once the reply is sent, pass one of:

- `wait_until`: a callable taking an awaitable, such as Vercel's ([below](#vercel)). Each call's
  sending is handed to it as a coroutine that ends once the event is sent or given up, without
  delaying the reply. The client's threads send the event either way: the coroutine only waits for
  that, so a host may start it after the reply.
- `flush_before_reply=True`, for hosts that stop the CPU after the reply, such as AWS Lambda or
  Cloud Run without always-on CPU: each call waits for its event to be sent, up to
  `flush_timeout_ms` (2 seconds by default, `identify` included), before replying, so each reply
  waits for one request to the ingestion, usually a short one. Past `flush_timeout_ms` the reply
  goes anyway, and the event is sent only if the process keeps running.

If both are set, `wait_until` is used, with one warning. Where neither is set, the wrapper warns once
per client on hosts it recognises: AWS Lambda, Cloud Run and Vercel. Cloudflare Python Workers have
no threads or sockets: the client stays disabled there, with one warning.

### FastAPI and Starlette

Mount the server's Streamable HTTP app, run its session manager from your app's lifespan (FastAPI
and Starlette don't run a mounted app's own), and shut the client down once the server has stopped:

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI

mcp_app = mcp.streamable_http_app()        # fastmcp: mcp_app = mcp.http_app()

@asynccontextmanager
async def lifespan(app):
    async with mcp.session_manager.run():   # fastmcp: async with mcp_app.lifespan(app):
        yield
    await lsquare.ashutdown()               # sends what's queued, within flush_timeout_ms

api = FastAPI(lifespan=lifespan)
api.mount("/orders", mcp_app)               # the MCP endpoint is /orders/mcp
```

For a stateless server pass `stateless_http=True`: to `FastMCP()` on mcp 1.x, to
`streamable_http_app()` on mcp 2.x, to `http_app()` on fastmcp. Neither a request nor an HTTP
session ending flushes: the lifespan's `ashutdown()` is what sends the events still queued when the
server stops.

### AWS Lambda, with Mangum

Mangum runs your app's lifespan around every invocation, so the recipe above breaks on the second
warm invocation: a session manager runs only once (mcp 1.x and 2.x refuse to start it again), and a
client shut down in the first invocation's lifespan drops the events of every later one. On Lambda,
keep the client at module level and never shut it down, serve statelessly with a new session
manager for each invocation, and pass `flush_before_reply=True`, so each call's event is sent while
its invocation still runs. On fastmcp, `http_app()` makes a new session manager each time its
lifespan runs, so Mangum can run it as it is:

```python
from mangum import Mangum

lsquare = LSquare(api_key=os.environ.get("LSQUARE_KEY"))   # at module level, never shut down
mcp = FastMCP("orders")                                      # fastmcp 3.x or 4.x
# register tools...
instrument(mcp, lsquare, flush_before_reply=True)
handler = Mangum(mcp.http_app(stateless_http=True, json_response=True))   # the endpoint is /mcp
```

On mcp 2.x each `streamable_http_app()` makes a new session manager, so make the app for each
invocation, with Mangum's lifespan off. mcp also refuses a `Host` header other than localhost's
(421) unless you name it, as for API Gateway:

```python
from mangum import Mangum
from mcp.server.transport_security import TransportSecuritySettings

security = TransportSecuritySettings(allowed_hosts=["abc123.execute-api.eu-west-1.amazonaws.com"])
mcp = MCPServer("orders")
# register tools...
instrument(mcp, lsquare, flush_before_reply=True)

async def app(scope, receive, send):
    asgi = mcp.streamable_http_app(stateless_http=True, json_response=True, transport_security=security)
    async with mcp.session_manager.run():
        await asgi(scope, receive, send)

handler = Mangum(app, lifespan="off")
```

On mcp 1.x, `FastMCP` keeps the one session manager it made, so build the server for each
invocation (the wrapper warns once per client, not once per server):

```python
def build():                                # security as above
    mcp = FastMCP("orders", stateless_http=True, json_response=True, transport_security=security)
    mcp.tool()(search_orders)
    return instrument(mcp, lsquare, flush_before_reply=True)

async def app(scope, receive, send):
    mcp = build()
    asgi = mcp.streamable_http_app()
    async with mcp.session_manager.run():
        await asgi(scope, receive, send)

handler = Mangum(app, lifespan="off")
```

### Vercel

Vercel's Python runtime serves your ASGI app as it is, and runs its lifespan as a server does, so
the [FastAPI recipe](#fastapi-and-starlette) works there. Pass the `wait_until` of Vercel's `vercel`
package: the invocation then keeps running after the reply until each call's event is sent.

```python
from vercel.functions import wait_until

instrument(mcp, lsquare, wait_until=wait_until)
```

Serve statelessly (`stateless_http=True`). `wait_until` finds the current request through a context
variable, and mcp 1.x and fastmcp 3.x run a stateful session's calls in the context of the request
that opened the session: the hand-off goes to that request, long finished, so it's refused and
nothing keeps the invocation running for the event. LSquare's tests check the app, the warning
and the hand-off against a stand-in for Vercel's runtime, not Vercel itself: how long an instance
keeps running work after a reply is up to Vercel, within the function's maximum duration. Vercel
gives cleanup at shutdown at most 500 ms, so there it's `wait_until`, not the lifespan's
`ashutdown()`, that sees each event sent.

### Sending what's queued when the process ends

- **A stdio server run by its own `run_stdio_async()`** (or `mcp.run()`, or fastmcp's `run()`)
  flushes when its client closes it, within `flush_timeout_ms`, before the event loop ends.
- **A low-level server you drive with `stdio_server()`**: await `lsquare.ashutdown()` after
  `server.run()` returns.
- **An HTTP app** (the SDK's own runner, or mounted in Starlette, FastAPI or any ASGI server): call
  `await lsquare.ashutdown()` in its lifespan's shutdown ([above](#fastapi-and-starlette)), except
  on Lambda, where Mangum runs the lifespan for each invocation ([above](#aws-lambda-with-mangum)).
  Neither a request nor an HTTP session ending flushes.
- **A script ending with `asyncio.run()`**: `await lsquare.ashutdown()` before it returns: pending
  async hooks are cancelled once the loop ends.
- At interpreter exit, an `atexit` handler sends what's still queued, within `flush_timeout_ms`.
  It doesn't run on `os._exit()`, `SIGKILL` or a signal's default action, so stop cleanly on
  `SIGTERM`:

  ```python
  import signal, sys
  signal.signal(signal.SIGTERM, lambda *_: (lsquare.shutdown(), sys.exit(0)))
  ```

`flush()` and `shutdown()` block the calling thread; on an event loop use `await lsquare.aflush()`
and `await lsquare.ashutdown()`. After `os.fork()`, the child starts with an empty client and the
parent sends what it had.

## Agent turns outside MCP

```python
lsquare = LSquare(api_key=os.environ.get("LSQUARE_KEY"))  # no key: disabled, never raises

# After an agent turn
lsquare.capture({
    "orgId": org_id, "userId": user_id, "conversationId": conversation_id, "turnId": turn_id,
    "question": question, "answer": answer, "toolCalls": tool_calls,
    "usage": {"inputTokens": 812, "outputTokens": 240, "costUsd": 0.004},
})
```

Every field is optional. A turn with a `conversationId` and a `turnId` gets the same event ID every
time it's sent, so a retry or a re-import is recognised as a duplicate. IDs (`orgId`, `userId`,
`conversationId`, `turnId`, `callId`, `apiKeyId`) are strings, or a `uuid.UUID`, sent as its string:
lowercase with hyphens, so the event is the one `str(uuid)` would make, and the UUID's `.hex` or an
uppercase string is a different ID. `turnId` may also be a safe integer.

## What leaves your process

- Python values become JSON as the TypeScript SDK's would: pydantic models by their fields (as
  `model_dump(by_alias=True)` names them, with no serializer run), dataclasses by their fields, UUIDs
  and pydantic URLs as strings, enums as their values, aware datetimes in UTC. Bytes, naive
  datetimes, `Decimal`, sets and other objects aren't JSON and are left out; a field with nothing
  JSON left in it is named in the event's `dropped`.
  `capture()` reads its data before it returns; a call's arguments and result are read when its
  event is built, at the reply, or up to a second later while `identify` runs.
- Strings in a call's `input` and `agent`, and in a turn, are cut at 16,000 characters, results at
  4,000 and `intent` at 500; a cut string ends with `…[+N chars]`, or `…[cut]` once an event's work
  budget for reading strings is spent. Lists and objects keep their first 100 entries, and nesting
  stops at 10 levels. Images, audio, binary resources and files sent as base64 text are kept as
  their size only.
- An event still over 256 KB loses parts, biggest and least needed first: a call its result, then its
  input, then its agent's tool calls, then its agent part; a turn its tool calls, then its answer,
  question, verification and latency. The event's `truncated` field names what was shortened or left
  out.
- Common formats of emails, phone numbers, card numbers, API keys and tokens, credentials in URLs,
  and IP addresses become numbered placeholders such as `[EMAIL_1]`, in inputs, results, errors,
  intents and agent details alike. Each pattern can be turned off: `redact={"ip": False}`, or
  `redact=False` for all.
- Values under secret key names (`password`, `token`, `apiKey` and the like) are replaced whole.
  `redact_keys=["name", "address"]` adds your own: matched ignoring case and punctuation, by the end
  of the key, so `name` also covers `firstName` and `fileName`; a narrower name such as `fullname`
  avoids that. Free text, such as a name inside a sentence, isn't caught.
- `before_send(event, signal)` sees every event before the patterns above are applied, and can
  change it or drop it by returning `None`; it may be sync or async. Values under secret key names
  are already replaced, and a string cut for length has had its kept part redacted. What it returns
  is shaped and redacted again. `event["kind"]` tells a `turn` from a `tool_call`.
- The wrapper never records HTTP headers, auth info, environment variables or anything else from the
  request context by itself, except MCP's own `MCP-Protocol-Version` header, as the call's protocol
  version. `identify` can read them; only what it returns is sent, its IDs and `metadata`, shaped
  and redacted like the rest.
- IDs (`orgId`, `userId`, `conversationId`, `turnId`, `sessionId`, `toolName`) are never redacted.
  Each must be at most 512 bytes, except `turnId`, which may be longer, or a safe integer.

## Privacy checklist

- Turn results off for tools that return customer records: `results=lambda tool: tool != "get_customer"`.
- Use `redact_keys` for personal data in structured inputs and results, and `before_send` for
  anything finer.
- Send `userId`, as an internal ID rather than an email address or phone number: LSquare deletes a
  person's events by it, and finds only events that carry it. A `userId` that looks like an email
  address or phone number is still sent as given, since masking it would stop deletion, and the SDK
  warns once.
- Keep retention short. It's set per project: ask for a short one, especially if you handle personal
  data, since events without a `userId`, and names written inside results, go only with retention.

## Sending

Events go in batches of up to 100, at most 4 requests at once, from the client's own daemon
threads; nothing waits on the network in your code. If your project reaches its daily limit, the
SDK stops sending until the limit resets (00:00 UTC), checks every 15 minutes whether it was raised,
and reports through `on_error` when it starts dropping events and how many it dropped.

## Client options

| Option | Default | |
|---|---|---|
| `api_key` | | Project key. Without it, the client is disabled. Never read from the environment by the SDK |
| `endpoint` | `LSQUARE_ENDPOINT`, then `https://ingest.lsquare.io` | https only, except localhost |
| `dry_run` | `LSQUARE_DRY_RUN=1` | Run everything but send nothing |
| `flush_timeout_ms` | `2000` | How long `flush()` waits. `0`: it doesn't |
| `before_send` | | Redact more, or drop an event |
| `before_send_timeout_ms` | `flush_timeout_ms`, or `2000` when that is `0` | Hook deadline |
| `max_concurrent_hooks` | `16` | `before_send` hooks running at once, and `identify` hooks, each |
| `max_concurrent_requests` | `4` | Requests in flight at once; other events wait, and go together |
| `redact` | all on | `False`, or `{"email", "phone", "card", "secret", "ip"}` to booleans |
| `redact_keys` | | More key names whose values are replaced whole |
| `on_error` | logs codes, once a minute | `(error, event=None)`. Receives a redacted copy; may be async |
| `logger` | standard error | A `logging.Logger`, or any object with `info` and `warn` or `warning`. Never stdout |

Errors given to `on_error` are an `LSquareError` with `code`, `message`, `event_id`, `paths`,
`status`, `resets_at` and `suppressed`. `flush()` returns a `FlushResult` with `sent`, `skipped`,
`failed` and `pending`. Its counts cover the work still outstanding when it starts: events already
finished aren't counted, so zero counts don't mean nothing was sent. The client's threads often send
an event before `flush()` is called, so the same code can report lower counts than in TypeScript,
where nothing is sent until the event loop is free.

## Compatibility

- Python 3.10 to 3.14. `lsquare.mcp` works with mcp 1.x and 2.x, and fastmcp 3.x and 4.x, and
  imports none of them itself.
- Sending needs no event loop. Async hooks (`before_send`, `identify`, `on_error`, the logger) need
  asyncio; on trio, through anyio, only sync ones run.
- Linking a `capture()` to its call uses a context variable of the client's own.
- The wrapper recognises a server by its shape and relies on parts of the MCP SDKs that aren't
  public API. A new SDK release can change them: the server keeps working, but its tool calls stop
  being recorded. LSquare tests new SDK releases weekly.

## Licence

MIT. `lsquare.mcp` includes code adapted from AgentCat's TypeScript SDK, also MIT: see
`THIRD_PARTY_NOTICES`.
