MCP Logging and Observability: What to Record
Build useful MCP logs without leaking secrets. Learn the event schema, correlation fields, denied-call tracking, retention, alerts, and incident workflow.
MCP logging needs to answer operational questions
An MCP server can expose a harmless documentation lookup or a tool that changes production data. Logging both as generic HTTP requests is not enough.
A useful MCP log should let an operator answer five questions:
- Who or what initiated the request?
- Which MCP server, connection, and tool were involved?
- What policy decision was made before execution?
- What happened at the backend?
- Can related events be reconstructed without exposing credentials or sensitive results?
That requires more than application error messages. Production MCP observability should combine structured events, metrics, traces, and a reviewable history of security-relevant decisions.
Logs, metrics, traces, and audit events are different
These signals overlap, but they serve different jobs.
| Signal | Best for | Example |
|---|---|---|
| Structured logs | Debugging individual events | Tool call failed because an upstream API returned 429 |
| Metrics | Detecting trends and thresholds | Error rate, p95 latency, denied calls per minute |
| Traces | Following one request across services | Client request → gateway → MCP tool → PostgreSQL |
| Audit events | Reviewing security and administrative actions | Link revoked, permission denied, policy changed |
Do not call every log line an audit log. An audit trail needs stable identity, timestamps, outcomes, and controlled access. A debug log may be temporary, verbose, and unsafe to retain for the same period.
The minimum MCP event schema
Use structured fields rather than composing one long message. The exact storage format can be JSON, a database table, or an observability platform, but the event model should remain consistent.
| Field | Why it matters | Example |
|---|---|---|
timestamp | Establishes event order | ISO 8601 in UTC |
event_id | Identifies one immutable event record | UUID |
request_id | Correlates logs for one request | Generated at ingress |
session_id | Groups related MCP requests | MCP session or application session |
actor_id | Identifies the authenticated principal | User, service account, or API key owner |
client_id | Distinguishes Cursor, ChatGPT, or another client configuration | Registered client or link identifier |
server_id | Identifies the MCP endpoint | Hosted server or deployment ID |
connection_id | Identifies the downstream system | PostgreSQL or OpenAPI connection ID |
tool_name | Shows the MCP capability requested | query or call_endpoint |
operation | Describes the backend action | SELECT, GET /orders, or policy update |
decision | Records authorization before execution | allowed or denied |
status | Records the final outcome | success, failed, partial, or timeout |
duration_ms | Supports latency analysis | End-to-end or stage-specific duration |
error_code | Makes failures aggregatable | Stable internal code, not only text |
policy_version | Explains why a decision was made | Link policy revision or hash |
Keep identifiers stable enough to join events, but avoid placing secrets or personal data inside identifiers.
What to log across the request path
Think in layers instead of relying on one component.
At the MCP client boundary
Record connection attempts, authentication failures, selected server, and user approval decisions when the client exposes those signals. The client may also know which human initiated the action, but its local logs should not be treated as the only source of truth because users can disable or delete them.
At the MCP gateway or server
Record authentication outcome, tool name, authorization decision, connection, request and session identifiers, execution status, duration, and a safe error classification. This is the best place to connect MCP identity to the downstream operation.
At the backend
Keep database or API-provider logs as an independent record. PostgreSQL can show the role and statement that reached the database; an API gateway can show method, route, response status, and rate-limit behavior. Backend logs confirm what actually crossed the final boundary, not merely what the MCP layer intended to execute.
Record denied calls, not only successful ones
Denied operations are often the earliest signal of a bad configuration or attempted escalation.
Useful denial fields include:
- actor, client, MCP link, and connection identifiers
- requested tool and operation
- policy rule or scope that rejected the request
- timestamp, request ID, and session ID
- a stable reason code such as
method_not_allowedortable_not_permitted - whether execution was stopped before the backend was reached
Avoid returning the complete internal policy to the client. The operator needs enough detail to investigate; the caller only needs a safe explanation of what was denied.
Track denial rate separately from ordinary application errors. A spike can mean a new prompt is using the wrong tool, a permission rollout is incomplete, or a compromised client is probing its boundaries.
Log administrative changes as audit events
Tool execution is only half the story. Access often changes before an incident.
Create audit events for:
- MCP link creation, deletion, activation, and revocation
- API key issuance and revocation
- OAuth client or redirect configuration changes
- permission preset and custom-scope changes
- connection creation and deletion
- backend credential rotation
- retention or export-policy changes
- organization membership and administrator changes
For each change, record the actor, previous value, new value, target resource, timestamp, and reason or ticket when your workflow supports one. Do not store the secret value itself.
What not to put in MCP logs
More data does not automatically create better observability. It can create a second sensitive database.
Do not log:
- bearer tokens, API keys, cookies, passwords, or complete MCP URLs containing credentials
- raw authorization headers
- database connection strings
- private keys or client secrets
- unrestricted query results or API response bodies
- complete prompts by default when they may contain customer data
- SQL literals containing email addresses, tokens, or regulated data unless policy explicitly requires and protects them
Prefer hashes, counts, route templates, schema names, redacted statements, and allowlisted metadata. If raw SQL is retained for investigation, restrict access and apply a retention period appropriate to the data it may contain.
Correlation makes logs usable
Without correlation, an operator sees separate records from the client, gateway, MCP server, and backend but cannot prove they belong to the same action.
Generate a request ID when the call enters the controlled boundary. Propagate it to internal services and include it in downstream metadata where safe. Keep a session ID for related calls, but do not use an MCP session ID as authentication.
The minimum useful relationship is:
actor → client or MCP link → session → request → tool call → backend operation
A single request can trigger multiple downstream operations, so use child span or operation identifiers rather than reusing one event ID everywhere.
Build metrics from structured events
Once events use consistent fields, derive a small set of operational metrics:
- requests by server, tool, connection, client, and outcome
- authentication failure rate
- authorization denial rate
- tool and backend error rate
- p50, p95, and p99 latency by tool
- timeout and cancellation counts
- active clients and sessions
- backend response-size or row-count distributions
Start with service-level indicators that change an operator's decision. A dashboard with fifty charts but no owner or threshold is decoration, not observability.
Alert on behavior, not every error
Individual failures are normal. Alert when a pattern suggests customer impact or security risk.
| Pattern | Possible meaning | First response |
|---|---|---|
| Authentication failures jump suddenly | Expired credentials, broken rollout, or credential probing | Group by client and source, then check recent key changes |
| Permission denials spike for one link | Prompt drift, wrong policy, or attempted escalation | Inspect requested tools and recent permission changes |
| One tool's p95 latency increases | Backend degradation or inefficient operation | Compare gateway and backend timing |
| Response sizes grow sharply | Unbounded query or endpoint behavior | Review row limits, pagination, and tool scope |
| A revoked link continues succeeding | Revocation failure or cached authorization | Disable the path and investigate immediately |
Never send credentials, raw prompts, query results, or sensitive SQL in alert payloads. Link responders to the protected event record instead.
Choose retention by purpose and sensitivity
Operational logs may need days; security investigations may need months. Keeping everything forever increases cost and exposure.
Define retention separately for:
- high-volume debug logs
- request and error events
- security denials
- administrative audit events
- exports created for an incident or legal process
Also define who can read each class, whether exports are recorded, how deletion works, and which fields require redaction. Retention is not only a storage setting—it is part of the data-governance model.
A practical MCP incident workflow
When an alert or report arrives, use logs to move through a repeatable sequence.
1. Identify the affected identity
Find the actor, client, API key or OAuth identity, MCP link, sessions, and connections involved.
2. Establish the timeline
Sort successful, failed, and denied operations by timestamp. Correlate permission changes, key issuance, and revocation events with tool calls.
3. Determine the backend impact
Compare MCP events with PostgreSQL or upstream API logs. Confirm which operations reached the backend and whether data was returned or changed.
4. Contain access
Revoke the narrowest affected identity first. Reduce permissions or disable the connection if the scope is uncertain. Rotate backend credentials only when exposure or gateway compromise makes it necessary.
5. Preserve and export evidence
Export the relevant records under controlled access, note the time range and filters, and avoid moving sensitive data into an unprotected ticket or chat.
6. Fix the control and verify it
Update the permission, prompt, tool implementation, or authentication configuration. Re-run a safe test and confirm both the allowed path and denial path produce the expected events.
How datamcp logging works today
datamcp currently records PostgreSQL query activity and permission denials. The activity table shows timestamp, activity type, action, status, and connection. Query details can include query text, execution time, row count, result size, and permission-check outcome when those fields are available.
The visible activity page can be downloaded as CSV or JSON. CSV includes timestamp, type, action, status, connection ID, and session ID. Current retention is 7 days on Free, 30 days on Pro, and 365 days on Enterprise.
This is a precise description of the current product, not a claim of native SIEM streaming, immutable audit storage, or automated security alerting. If your operating model requires those controls, keep the backend's own logs and document the additional export or ingestion process you control.
For the access-control architecture around these events, see the hosted MCP gateway. The MCP authorization guide separates OAuth identity, scopes, resource policy, backend grants, denial handling, and revocation. Use the MCP governance guide to assign owners, review access, and connect logs to an incident process, then apply the MCP security checklist to the complete production boundary.
Production review checklist
Before relying on MCP logs, verify:
- Every event has a timestamp, request ID, actor or client identity, tool, connection, decision, and outcome
- Authentication failures and authorization denials are distinguishable
- Administrative access changes are recorded separately from tool calls
- Tokens, passwords, cookies, and authorization headers are redacted
- Raw prompts, SQL, and results follow an explicit data policy
- MCP events can be correlated with backend logs
- Metrics have owners, thresholds, and response actions
- Revocation can be tested and observed in the logs
- Retention differs by purpose and sensitivity
- Export access and exported evidence are controlled
- An incident can be reconstructed from a known test case
Logging is complete only when it changes how the team detects, investigates, and contains an event. Start with a small structured schema, preserve denied operations, and test the full trail before production access depends on it.
Related articles
MCP Gateway vs MCP Server: Architecture, Security, and When You Need Each
An MCP server exposes tools. An MCP gateway controls how clients reach them. Compare architecture, auth, permissions, operations, and production tradeoffs.
SecurityMCP Authentication and Authorization Explained
Learn how MCP authentication works with OAuth 2.1 and API keys, how authorization differs, and how to enforce scopes, permissions, and revocation.
Need a controlled remote MCP layer?
Create a hosted link with separate client authentication, source-specific permissions, and independent revocation.
Create MCP linkExplore the DataMCP gateway · Questions? Read the docs or view pricing.