AI Hints
Home›MCP Tutorial›Limits and Audits
MCP · Lesson 101 of 120

Auditing

Log every call.

⏱ 2 min read▶ Video at 1:30:34🎓 Free
Watch this lesson in the MCP courseWatch on YouTube ↗Full MCP course

When something goes wrong, you need to know what happened. An audit log records every tool call. Which tool, which arguments, and whether it worked.

Auditing
From the video: Auditing
  • What happened?
  • An audit log
  • Every call

audit_server.py

Audited wraps a tool function. After the tool runs, it writes one JSON line, with the tool name, arguments, and result. Stacking it under the tool decorator logs every call.

audit_server.pypython
import json, functools
from mcp.server.mcpserver import MCPServer

mcp = MCPServer("northwind")

def audited(fn):
    @functools.wraps(fn)
    def wrapper(**args):
        result = fn(**args)
        with open("audit.jsonl", "a") as log:
            log.write(json.dumps({"tool": fn.__name__, "args": args, "result": result}) + "\n")
        return result
    return wrapper

@mcp.tool()
@audited
def order_status(order_id: int) -> str:
    """Look up an order."""
    return {1042: "shipped", 1043: "packing"}.get(order_id, "unknown")

Reading the log

We call the audited tool twice, then read the log. Run it. Each call is one line, with its tool, arguments, and result.

read_audit.pypython
from audit_server import mcp
from tester import call

for order_id in [1042, 1043]:
    call(mcp, "order_status", {"order_id": order_id})

print(open("audit.jsonl").read())
Output
{"tool": "order_status", "args": {"order_id": 1042}, "result": "shipped"}
{"tool": "order_status", "args": {"order_id": 1043}, "result": "packing"}
Also uses tester.py
import asyncio
from mcp import Client

def call(server, tool, args=None, **options):
    async def go():
        async with Client(server, **options) as client:
            return await client.call_tool(tool, args or {})
    return asyncio.run(go())

def tools(server):
    async def go():
        async with Client(server) as client:
            return (await client.list_tools()).tools
    return asyncio.run(go())
Also uses audit_server.py
import json, functools
from mcp.server.mcpserver import MCPServer

mcp = MCPServer("northwind")

def audited(fn):
    @functools.wraps(fn)
    def wrapper(**args):
        result = fn(**args)
        with open("audit.jsonl", "a") as log:
            log.write(json.dumps({"tool": fn.__name__, "args": args, "result": result}) + "\n")
        return result
    return wrapper

@mcp.tool()
@audited
def order_status(order_id: int) -> str:
    """Look up an order."""
    return {1042: "shipped", 1043: "packing"}.get(order_id, "unknown")

Summary

Log every tool call, with its arguments and result, but never secrets. Next, the security quiz.

Key takeaways
  • audit.jsonl
  • Tool + args
  • No secrets
Next up: Security Quiz — test yourself