Skip to content

Add identity and enrichment

Two optional hooks add your own data to each call record: an identity resolver says who made the call, and an enricher adds fields of your choosing. Both may be plain functions or coroutines.

identity_resolver(context) gets the FastMCP MiddlewareContext and returns a dict. Three keys become columns of their own: user_sub, caller_kind and client_id. Anything else goes into the identity JSON column.

With FastMCP’s built-in auth, read the access token:

from fastmcp import FastMCP
from fastmcp.server.dependencies import get_access_token
from fastmcp_feedback.instrumentation import MemorySink, instrument
app = FastMCP("My Server")
def who(context):
"""Who made this call. Return {} for anonymous calls."""
token = get_access_token()
if token is None:
return {}
return {
"user_sub": token.claims.get("sub") or token.client_id,
"client_id": token.client_id,
"caller_kind": "oauth",
"scopes": token.scopes, # stored in the identity column
}
sink = MemorySink()
mw = instrument(app, [sink], identity_resolver=who)

user_sub is what feedback linking uses to match calls from clients that keep no session, so set it on any HTTP server that collects feedback.

The resolver runs before the tool. Events the tool records with record_event or record_llm_call get the same user_sub, caller_kind and client_id as the call’s row:

@app.tool
async def render(scene: str) -> dict:
mw.record_event("render.queued", key=scene) # carries the caller's user_sub
return {"queued": scene}

A value passed to record_event explicitly wins. An event recorded outside a call, including from a task the tool started that records after the tool returned, gets only what you pass.

Some tools make the very thing the resolver looks up: a registration that creates the client record a session maps to, or a login. Before such a tool runs, the resolver cannot know it. In two cases the resolver runs a second time after the tool, for the call’s own row:

  • its first answer was empty: no keys, only None values, or a run that raised or timed out;
  • its first answer lacks a key you list in late_identity_keys. The list is empty by default.

A missing user_sub, caller_kind or client_id on its own does not count, so a resolver that never returns one of them still runs once per call.

  • The second run happens alongside the enricher, so the row is ready no later than the slower of the two, and only for calls that are kept: a call that sampling drops gets no second run.
  • Its values fill the row’s gaps and replace None. Where both answers have a value, the first wins, so the row agrees with the events recorded during the call. Those events keep the first answer; nothing is rewritten.
  • Any other first answer means one run.

So a resolver that answers anything before the tool needs late_identity_keys to name what only appears afterwards. This one looks up a registered bus client by session, the way blender-mcp’s does:

from fastmcp import Context
registered: dict[str, str] = {} # session -> bus client
def who_on_bus(context):
out = {"user_sub": "user-1", "caller_kind": "addon", "client_id": "dcr-9"}
session = getattr(context.fastmcp_context, "session_id", None)
if session in registered:
out["bus_client_uuid"] = registered[session]
return out
bus_app = FastMCP("Bus")
bus_mw = instrument(
bus_app, [sink], identity_resolver=who_on_bus, late_identity_keys=["bus_client_uuid"]
)
@bus_app.tool
async def register_client(client_uuid: str, ctx: Context) -> str:
registered[ctx.session_id] = client_uuid
return "ok"

The register_client row’s identity holds bus_client_uuid. Without late_identity_keys the first answer is not empty, so there is no second run and the row does not have it. That is deliberate: the second run is opt-in for any resolver that answers.

The resolver is also called outside a tool call, when capture_recent_calls needs the current user. There it receives an object whose only useful attribute is fastmcp_context, so read identity from that or from FastMCP’s dependency helpers, as above, rather than from context.message.

enricher(tool, args, result, context) runs after the tool and returns extra fields for the extra JSON column. result is the payload the record stores: the structured content when the tool returned some, otherwise its content items, and None when the tool raised.

Pass it next to the resolver, in place of the earlier instrument call:

async def enrich(tool, args, result, context):
fields = {"server_version": "1.4.0"} # fills the server_version column
if isinstance(result, dict) and "job_id" in result:
fields["job_id"] = result["job_id"] # lets you join events by job id
return fields
mw = instrument(app, [sink], identity_resolver=who, enricher=enrich)

A server_version key goes to its own indexed column instead of extra. To set one version for every record, pass server_version="1.4.0" to instrument instead.

Writing a key such as job_id or speech_id into extra is how you join a call to the events it started.

  • Hook output is redacted like arguments.
  • An async hook that takes longer than hook_timeout (0.25 seconds by default) is skipped for that call. A hook that raises is logged and skipped. Neither changes what the client receives, but the resolver runs before the tool, so a slow async resolver delays the tool by up to hook_timeout. Keep it cheap: read state you already have rather than calling out.
  • Neither hook runs for excluded tools or in mode off. The enricher and the resolver’s second run do not run for calls that are sampled out; the resolver’s first run does, since it happens before anyone knows whether the call will fail or record an event.
  • Each run of the resolver is bounded by hook_timeout and redacted, and a second run that fails or times out leaves the first answer in place.