Skip to main content

Audit logging for an MCP server

An MCP server lets other people's agents act on your customers' data. The log needs to answer: which client connected for which user, which tools ran and how they ended, what was refused, and whether a tool's definition changed. One trail carries every server you run; the server id and the session id tell the rows apart.

This guide audits a server you run; to let an agent read and write trails through Santati's own MCP server, see MCP server.

Before you start: a trail named mcp and a write key in SANTATI_API_KEY (Quickstart), Node 22+, and npm install @santati/node. The samples use @modelcontextprotocol/sdk 1.x.

What to record​

MomentActionRequired metadata
A client is authorizedmcp.client.authorizedNone
A session opens or closesmcp.session.started, mcp.session.endedNone
A tool is calledmcp.tool.calledgen_ai.tool.name, result
A tool call is refusedmcp.tool.deniedgen_ai.tool.name
A resource is readmcp.resource.readmcp.resource.uri
A prompt is retrievedmcp.prompt.retrievedgen_ai.prompt.name
A tool's definition changesmcp.tool.definition_changedgen_ai.tool.name, definition_sha256

MCP servers lists every action's fields. mcp.client.authorized is emitted where your token check accepts a client, and it may carry scopes and client_name; mcp.session.ended may carry a duration_ms. mcp.tool.denied carries a reason for the refusal, and mcp.tool.definition_changed may carry previous_definition_sha256 so a reader sees both sides of the change. mcp.server.registered, mcp.server.updated, mcp.server.enabled, mcp.server.disabled and mcp.server.removed cover the server's own lifecycle, emitted by whoever changed it.

Identify the caller​

// Resolved from the verified access token on each request.
export type Caller = {
organizationId: string;
userId: string;
clientId: string;
sessionId: string;
};

Your token verifier already knows the customer, the user and the client. Verify the token once per request: every handler of that request shares the same resolved caller. organization_id is the customer whose data the token grants, taken from the token and never from tool arguments. The actor is the connecting client: an agent acting on behalf of the user (agents acting for someone). The two on_behalf_of fields go together; the standard schemas refuse one without the other. A client that opens no session gets the sessionId stateless, so its calls still group together.

Wrap every tool​

mcp-audit.ts
import { Santati, type EventInput } from "@santati/node";

const santati = new Santati({ apiKey: process.env.SANTATI_API_KEY!, trail: "mcp" });

const SERVER = { type: "mcp_server", id: "mcps_billing", name: "Billing MCP" };

// Resolved from the verified access token on each request.
export type Caller = {
organizationId: string;
userId: string;
clientId: string;
sessionId: string;
};

async function emit(event: EventInput): Promise<void> {
try {
await santati.events.emit(event);
} catch (error) {
console.error("audit event not recorded", event.event, error);
}
}

function base(caller: Caller) {
return {
organizationId: caller.organizationId,
actor: {
type: "agent",
id: caller.clientId,
metadata: { on_behalf_of_type: "user", on_behalf_of_id: caller.userId },
},
};
}

export function audited<Args, Result>(
toolName: string,
handler: (args: Args, caller: Caller) => Promise<Result>,
) {
const tool = { type: "tool", id: `tool_${toolName}`, name: toolName };

return async (args: Args, caller: Caller, requestId: string): Promise<Result> => {
const started = Date.now();
const record = (result: "success" | "error") =>
emit({
...base(caller),
event: "mcp.tool.called",
targets: [SERVER, { type: "mcp_session", id: caller.sessionId }, tool],
metadata: {
"gen_ai.tool.name": toolName,
result,
duration_ms: String(Date.now() - started),
request_id: requestId,
},
data: { arguments: args },
});

try {
const result = await handler(args, caller);
await record("success");
return result;
} catch (error) {
await record("error");
throw error;
}
};
}
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
import { z } from "zod";

import { audited, type Caller } from "./mcp-audit.js";

// Yours to write: map the verified access token to the customer, the user and the client.
function callerFrom(extra: { authInfo?: AuthInfo; sessionId?: string }): Caller {
const auth = extra.authInfo;
if (!auth) throw new Error("unauthenticated MCP request");
return {
organizationId: String(auth.extra?.organization_id),
userId: String(auth.extra?.user_id),
clientId: auth.clientId,
sessionId: extra.sessionId ?? "stateless",
};
}

const server = new McpServer({ name: "billing", version: "1.4.0" });

const searchInvoices = audited("search_invoices", async (args: { query: string }, caller) => {
const invoices = await billing.search(caller.organizationId, args.query);
return { content: [{ type: "text" as const, text: JSON.stringify(invoices) }] };
});

server.registerTool(
"search_invoices",
{ description: "Search this customer's invoices.", inputSchema: { query: z.string() } },
(args, extra) => searchInvoices(args, callerFrom(extra), String(extra.requestId)),
);

result and duration_ms are strings, because every metadata value is a string. request_id is the JSON-RPC request id. Arguments go in data, which is stored verbatim and is not indexed, and a team administrator can redact secrets in them under Audit Log → Redaction. An event may name at most 10 targets; the calls here name three or four. The SDK generates an idempotency key per emit and retries transport failures, 500, 502, 503, 504 and 429 (except quota_exceeded), so a retried request never stores a tool call twice. The tool call never fails because the audit emit failed: the wrapper rethrows the handler's own error unchanged.

Record sessions and refusals​

export const sessionStarted = (caller: Caller, client: { name: string; version: string }) =>
emit({
...base(caller),
event: "mcp.session.started",
targets: [
{ type: "mcp_session", id: caller.sessionId },
{ type: "mcp_client", id: caller.clientId, name: client.name },
SERVER,
],
metadata: {
client_name: client.name,
client_version: client.version,
transport: "streamable_http",
},
});

export const toolDenied = (caller: Caller, toolName: string, reason: string) =>
emit({
...base(caller),
event: "mcp.tool.denied",
targets: [
SERVER,
{ type: "mcp_session", id: caller.sessionId },
{ type: "tool", id: `tool_${toolName}`, name: toolName },
],
metadata: { "gen_ai.tool.name": toolName, reason },
});

sessionStarted and toolDenied belong in mcp-audit.ts, beside audited. Call sessionStarted from the transport's onsessioninitialized callback with the client's name and version from server.server.getClientVersion(). Emit mcp.session.ended where the session closes, with its own targets and an optional duration_ms, so a session's lifetime brackets its tool calls. mcp.session.started may also carry mcp.protocol.version. Call toolDenied where your authorization check refuses a tool, before the handler runs, so a refused call is never logged as a failed one. Put the refusal in reason: the scope that was missing, the policy that fired, or the client the tool list does not include.

mcp.resource.read requires mcp.resource.uri and mcp.prompt.retrieved requires gen_ai.prompt.name; wrap them the same way when your server exposes resources or prompts.

Detect tool-definition drift​

A client decides what to call from a tool's name, description and input schema, so a changed definition changes what agents do without any of your handlers changing. The hash covers all three, so a renamed parameter or a reworded description counts as a change. At deploy time list the tools as a client sees them (tools/list), hash each definition, compare with the hash stored at the previous deploy and emit when it differs:

import { createHash } from "node:crypto";

type ToolDefinition = { name: string; description?: string; inputSchema: unknown };

export function definitionSha256(tool: ToolDefinition): string {
return createHash("sha256")
.update(JSON.stringify([tool.name, tool.description ?? "", tool.inputSchema]))
.digest("hex");
}

// `previous` is the hash you stored at the last deploy; store the returned one for the next.
export async function recordDrift(tool: ToolDefinition, previous: string | undefined): Promise<string> {
const current = definitionSha256(tool);
if (previous !== undefined && previous !== current) {
await emit({
event: "mcp.tool.definition_changed",
organizationId: "platform",
actor: { type: "system", id: "deploy" },
targets: [SERVER, { type: "tool", id: `tool_${tool.name}`, name: tool.name }],
metadata: {
"gen_ai.tool.name": tool.name,
definition_sha256: current,
previous_definition_sha256: previous,
},
});
}
return current;
}

On the first deploy there is no previous hash and nothing is emitted. The pack also covers mcp.elicitation.requested, when your server asks the user for input, and mcp.sampling.requested, when it requests a model completion from the client; emit them the same way. Server-wide events have no customer: send them under one organization_id reserved for your own operations, platform here.

Enforce the shape​

Team administrators open Actions & Schemas → Add standard events and tick "MCP servers", or call POST /api/v0/standard-events/install/ with {"packs": ["mcp"]} and a manage key.

warning

On a team with no definitions this turns enforcement on, and every action outside the catalog is then refused with unknown_action (Event definitions).

Installed actions also enforce their target types: an extra type is refused with schema_validation_failed on targets.<i>.type.

Answer questions from the log​

Every call below uses the one filter vocabulary shared by the list endpoint and exports (Search events). Filters are exact and case-sensitive, target_type and target_id must hold of the same target row, and each metadata.<key> pair matches the exact string value. The list returns events newest first by producer timestamp. A timestamp filter must carry a UTC offset, or be a bare date read as midnight UTC. The same vocabulary in an export's query writes a full download (Export events).

Refused calls for one customer since a date:

curl -G https://api.santati.io/api/v0/events/ \
-H "Authorization: Api-Key $SANTATI_API_KEY" \
--data-urlencode "trail=mcp" \
--data-urlencode "event=mcp.tool.denied" \
--data-urlencode "organization_id=org_acme" \
--data-urlencode "created_after=2026-11-01"

Everything in one session:

curl -G https://api.santati.io/api/v0/events/ \
-H "Authorization: Api-Key $SANTATI_API_KEY" \
--data-urlencode "target_type=mcp_session" \
--data-urlencode "target_id=3f2c9a1e-6b7d-4c8e-9f10-2a3b4c5d6e7f"

Every call of one tool, using the exact-match metadata.<key> filter:

curl -G https://api.santati.io/api/v0/events/ \
-H "Authorization: Api-Key $SANTATI_API_KEY" \
--data-urlencode "event=mcp.tool.called" \
--data-urlencode "metadata.gen_ai.tool.name=search_invoices"

Next steps​

Deployed AI agents for the caller's side of the same actions, Chain verification to make the trail tamper-evident, and MCP servers for every action's fields.