> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Defenses and the Audit Trail

> Explains essential audit logs, their contents, risks of log tampering, and practical defenses to harden logging, governance, and stdio-based protocol considerations.

We saw earlier that a tool call was executed without explicit approval. Alan checked the logs and found nothing. This article explains what a reliable audit trail should contain, why it matters, and concrete steps to harden logging so an attacker can't hide in or corrupt your records.

Most defenses try to stop a bad call before it happens — consent gates, short-lived tokens, and verifying request origins. The audit log is different: its job begins once a call has already gone through. When other defenses fail, the audit trail provides an authoritative record of who approved what and when. That was the layer Alan was missing.

What should have been recorded? There are six essential categories to log.

## Six essential audit events

| Event category | What to record | Why it matters |
| - | - | - |
| Tools / tool calls | Which tool was invoked, timestamp, actor. Redact or omit sensitive values such as API keys, passwords, and tokens before writing inputs to the log. | Ties operations to concrete actions and enables post-incident reconstruction. |
| Consent decisions | Who approved what and when (user identity, timestamp, decision). | Links a tool call back to an explicit human decision for accountability. |
| Connection & request lifecycle | When a connection opened and closed, session identifiers, request metadata. | Helps detect long-lived or unexpected connections and resource exhaustion. |
| Errors | Error codes and concise stack or handler location (no secret dumps). | Speeds troubleshooting and shows where failures originated. |
| Authorization events | Every token check and its result (accepted/rejected), with redacted token context. | Reveals authorization attempts and suspicious failures. |
| Notifications & tool-catalog changes | Events like `notifications/tools/list_changed` and which tool versions changed. | Detects configuration drift or unauthorized tool swaps after approval. |

Redact secrets and retain only the minimum context needed for auditing. Prefer structured logs (timestamp, event\_type, actor, resource, outcome) so searching, alerting, and forensic analysis are reliable without exposing sensitive fields.

## Example consolidated audit log (sensitive values redacted)

```text theme={null}
audit.log
1  09:41:07  tools/call    get_shipment    alan    api_key=[redacted]
2  09:41:05  consent       get_shipment    approved  alan <alan@acme.io>
3  09:40:58  connection    open            shipment-tracker
   09:52:13  connection    close           shipment-tracker
4  09:41:09  error         -32602 invalid params    stack: handler server.py:4
5  09:41:06  auth          token           accepted  token=[redacted]
   09:43:31  auth          token           rejected
6  09:45:02  notifications/tools/list_changed    shipment-tracker
```

## Logs are an attack surface

Logs themselves can be targeted. An attacker who can write to logs can:

* Read secrets and personal data if logs are stored in plaintext.
* Overwrite or flood logs with junk so important events are buried.
* Inject control characters, very long lines, format-strings, or SQL fragments to manipulate parsers, storage, or ingestion pipelines.

Example of malicious log content (abbreviated):

```text theme={null}
\x00\x00\x00\x00...AAAAAAAAAAAAAAAAAAAAA
%s%s%s%s%s%s%n%n%n%n... ' OR 1=1 -- ' OR 1=1 --
```

## Defenses for your logging pipeline — practical checklist

* Never log credentials or other secrets in plaintext. Redact or replace with stable identifiers.
* Avoid logging unnecessary personal data (PII) unless there is a clear audit need and retention policy.
* Enforce maximum log line length — truncate or reject overly long lines to prevent disk exhaustion and obscure important events.
* Protect the log store from unauthorized read and write access (fine-grained IAM, network controls, and integrity protections).
* Monitor for abnormal write patterns (spikes, repeated failures, or writes from unexpected actors).
* Use append-only storage or cryptographic integrity checks for high-value audit trails.

## Stdio-based protocols (JSON-RPC) — stdout vs stderr

If your server communicates over stdio (for example, JSON-RPC; see [https://www.jsonrpc.org/specification](https://www.jsonrpc.org/specification)), log messages must go to standard error (stderr). Stdout is reserved strictly for the JSON-RPC stream; writing arbitrary log lines to stdout can corrupt the protocol conversation.

Example JSON-RPC responses (these must be delivered cleanly on stdout):

```json theme={null}
{"jsonrpc":"2.0","id":9,"result":{}}
{"jsonrpc":"2.0","id":7,"result":{}}
{"jsonrpc":"2.0","id":8,"result":{}}
```

Do not send log output to stdout when using stdio-based protocols. Logs on stdout can break or desynchronize the protocol and lead to parser failures or lost messages.

## Log levels and per-request logging control

Older revisions allowed setting a single log level for an entire connection with `logging/setLevel`. That method has been removed. Log level now travels per-request inside a `_meta` field. If a client sends a request without a log level, the server should avoid producing logs for that request.

Severity levels follow RFC 5424 ([https://datatracker.ietf.org/doc/html/rfc5424](https://datatracker.ietf.org/doc/html/rfc5424)) with eight levels: debug, info, notice, warning, error, critical, alert, emergency — debug is lowest, error/emergency are highest. Use these to drive structured observability and to control what gets persisted versus what remains ephemeral.

## Governance: who reads logs and how to own them

Before you assign reading permissions, decide what is allowed to appear in logs at all. Governance — deciding which servers implementing the protocol your team runs, who checks them, and how often — is enabled by three basic habits:

1. Keep an inventory of every server you run. If a server is not on the list, no one is responsible for it and changes may go unnoticed.
2. Review any new server before trusting it, not after.
3. Periodically review and revise permissions granted to clients. Permissions granted months ago may no longer be appropriate.

Put these habits together with well-structured logs and the question of who approved what and when always has an answer.

![A dark-themed dashboard titled "Governance – Three Habits" showing three habit buttons (keep a list, review before trust, revise permissions). The left panel lists servers with access badges (shipment-tracker, warehouse-db, support-queue, billing-api-v2) and the right side shows a review checklist and a log icon.](https://mintcdn.com/kodekloud-c4ac6d9a/0UyWJzvxepsOrybu/images/Model-Context-Protocol-Associate-MCPA-Certification/Trust-Boundaries-and-Attacks/Defenses-and-the-Audit-Trail/governance-three-habits-access-servers-checklist.jpg?fit=max\&auto=format\&n=0UyWJzvxepsOrybu\&q=85\&s=0dcf9c8df805279062936bc5094d6b83)

Okay, so let's talk about the six roles in the rollout and who owns what.

## Links and references

* JSON-RPC specification: [https://www.jsonrpc.org/specification](https://www.jsonrpc.org/specification)
* RFC 5424 (Syslog Protocol): [https://datatracker.ietf.org/doc/html/rfc5424](https://datatracker.ietf.org/doc/html/rfc5424)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/model-context-protocol-associate-mcpa-certification/module/31dedbc5-6173-4700-b50e-7a581095c897/lesson/256f989b-c95a-40aa-bfb0-aef7cdd3cfde)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.