---
title: "Audit Tool Calls"
description: "เพิ่ม audit log แบบ JSON lines ให้ HTTP server ของ cafe-mcp บันทึกว่าใครเรียก tool ไหนด้วย argument อะไรและผลเป็นอย่างไร โดยซ่อนชื่อลูกค้าและไม่เก็บ token แล้วใช้ jq หาว่าใครยกเลิกออร์เดอร์"
canonical_url: "https://iamthana.com/courses/mcp-security/audit-log"
---

> Index of every page on this site: [llms.txt](https://iamthana.com/llms.txt)

ทุกบทที่ผ่านมาเราลองโจมตีแล้วดูผลทันที แต่ตอนใช้งานจริงไม่มีใครนั่งดู ถ้ามีคนยกเลิกออร์เดอร์หรือลองแทรกคำสั่งเข้ามา เราต้องย้อนดูได้ทีหลังครับ บทนี้เพิ่ม audit log ให้ `cafe-mcp` บันทึก request ละหนึ่งบรรทัด JSON ใน `audit.log` ว่าใครเรียกอะไร ด้วย argument อะไร และผลเป็นอย่างไร

ทุกคำสั่งรันในโฟลเดอร์ `cafe-mcp` และต้องมี `tokens.env` จากบท [Require a Token](https://iamthana.com/courses/mcp-security/auth)

## What to Log

OWASP นับการไม่มี log ว่าเป็น MCP08 Lack of Audit and Telemetry log ต้องบอกได้ว่าใครเรียกเมื่อไหร่ และ MCP01 ให้ซ่อน secret ก่อนเขียนลง log ด้วย

### Fields

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      Value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ts
      </code>
    </td>
    
    <td>
      เวลา UTC ระดับมิลลิวินาที
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        request_id
      </code>
    </td>
    
    <td>
      เลขสุ่ม 12 ตัวของแต่ละบรรทัด
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        principal
      </code>
    </td>
    
    <td>
      <code>
        client_id
      </code>
      
       ของ token เช่น <code>
        staff-demo
      </code>
      
      , <code>
        anonymous
      </code>
      
       เมื่อไม่มี token ที่ชั้น HTTP หรือ <code>
        stdio
      </code>
      
       เมื่อเรียกแบบ stdio
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        method
      </code>
    </td>
    
    <td>
      <code>
        tools/call
      </code>
      
      , <code>
        resources/read
      </code>
      
       ฯลฯ หรือ <code>
        http
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        name
      </code>
    </td>
    
    <td>
      ชื่อ tool, URI ของ resource หรือ <code>
        POST /mcp
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        arguments
      </code>
    </td>
    
    <td>
      argument ที่ซ่อนค่าแล้ว
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        answers
      </code>
    </td>
    
    <td>
      <code>
        action
      </code>
      
       ของคำตอบ elicitation เช่น <code>
        accept
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        outcome
      </code>
    </td>
    
    <td>
      ผลของ request ตามตารางข้างล่าง
    </td>
  </tr>
</tbody>
</table>

`outcome` เป็นแค่สรุป ไม่เก็บ response ทั้งก้อน เพราะ `create_order` ตอบกลับมาพร้อมชื่อลูกค้า

<table>
<thead>
  <tr>
    <th>
      Outcome
    </th>
    
    <th>
      Meaning
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ok
      </code>
    </td>
    
    <td>
      tool ทำงานสำเร็จ
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        error
      </code>
    </td>
    
    <td>
      tool ตอบ <code>
        isError
      </code>
      
       หรือ request Fail ในชั้น MCP
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        refused
      </code>
    </td>
    
    <td>
      <code>
        require_scope
      </code>
      
       ปฏิเสธเพราะ token ไม่มี <code>
        orders:write
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        input_required
      </code>
    </td>
    
    <td>
      server ส่งคำถามยืนยันกลับไปรอคำตอบ
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        http_401
      </code>
      
      , <code>
        http_403
      </code>
      
      , <code>
        http_400
      </code>
    </td>
    
    <td>
      HTTP ตอบสถานะนั้นก่อนถึง MCP
    </td>
  </tr>
</tbody>
</table>

### Redaction

`audit.py` เก็บค่าเฉพาะ argument ที่มีชื่ออยู่ใน allowlist ที่เหลือเป็น `[redacted]`

- `order_id`, `items` (`menu`, `size`, `quantity`), `day`, `max_price_thb` เก็บตามจริง เพราะต้องใช้ตอบว่าออร์เดอร์ไหนถูกแตะ
- `customer_name` เป็น `[redacted]` ชื่อ argument ยังอยู่ใน log เลยรู้ว่ามีส่งมา แต่ไม่เห็นค่า
- argument ที่เพิ่มทีหลังเป็น `[redacted]` เองจนกว่าจะใส่ชื่อลง allowlist ถ้าใช้ denylist argument ใหม่จะหลุดเข้า log ทันที

header `Authorization`, query string, `_meta`, `requestState` และตัว response ไม่เข้า log เลย

### Hook Point

จะเขียน log ที่จุดไหนถึงจะเห็นครบทุก request?

`MCPServer(middleware=[...])` ของ SDK เห็นทุก request ของ MCP ทั้ง HTTP และ stdio พร้อม method, params และ token แต่ไม่เห็น request ที่ชั้น HTTP ตอบไปก่อน เช่น `401` บทนี้เลยใช้ middleware ของ SDK เป็นตัวหลัก แล้วเสริม wrapper เล็ก ๆ ที่ชั้น HTTP เก็บเฉพาะ response ที่สถานะ 400 ขึ้นไป

## Write the Code

- `audit.py`
- ต่อ `auth.py`, `cafe_server.py`, `http_server.py` เข้ากับ audit
- `.gitignore` กับ `tests/conftest.py`

### 1. audit.py

```python [audit.py]
import json
from contextvars import ContextVar
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4

from mcp.server.auth.middleware.auth_context import get_access_token

AUDIT_LOG = Path(__file__).parent / "audit.log"

# Argument names whose values are recorded as sent. Every other argument, such as customer_name, becomes "[redacted]".
LOGGED_ARGUMENTS = {"order_id", "items", "menu", "size", "quantity", "max_price_thb", "day"}

# require_scope adds the missing scope here, so the middleware can tell a refusal from other tool errors.
scope_refusals: ContextVar[list[str]] = ContextVar("scope_refusals")


def write_audit(**fields) -> None:
    record = {"ts": datetime.now(UTC).isoformat(timespec="milliseconds"), "request_id": uuid4().hex[:12]}
    record.update({name: value for name, value in fields.items() if value is not None})
    with AUDIT_LOG.open("a", encoding="utf-8") as log:
        log.write(json.dumps(record, ensure_ascii=False) + "\n")


def redact(value):
    if isinstance(value, dict):
        return {name: redact(item) if name in LOGGED_ARGUMENTS else "[redacted]" for name, item in value.items()}
    if isinstance(value, list):
        return [redact(item) for item in value]
    return value


async def audit_middleware(ctx, call_next):
    if ctx.request_id is None:
        return await call_next(ctx)
    params = ctx.params or {}
    access_token = get_access_token()
    refusals: list[str] = []
    scope_refusals.set(refusals)
    outcome = "error"
    try:
        result = await call_next(ctx)
        if refusals:
            outcome = "refused"
        elif result.get("isError"):
            outcome = "error"
        elif result.get("resultType") == "input_required":
            outcome = "input_required"
        else:
            outcome = "ok"
        return result
    finally:
        # params are raw client JSON here: this runs before validation, so check each type before reading it.
        arguments = params.get("arguments")
        responses = params.get("inputResponses")
        write_audit(
            principal=access_token.client_id if access_token else "stdio",
            method=ctx.method,
            name=params.get("name") or params.get("uri"),
            arguments=redact(arguments) if isinstance(arguments, dict) else None,
            answers=[r.get("action") for r in responses.values() if isinstance(r, dict)] if isinstance(responses, dict) else None,
            outcome=outcome,
        )


class HttpAudit:
    """Records every response with status 400 or above, including requests that never reach MCP. Reads the path, never the query string or headers."""

    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        async def send_and_record(message):
            if message["type"] == "http.response.start" and message["status"] >= 400:
                user = scope.get("user")
                write_audit(
                    principal=user.access_token.client_id if user and hasattr(user, "access_token") else "anonymous",
                    method="http",
                    name=f"{scope['method']} {scope['path']}",
                    outcome=f"http_{message['status']}",
                )
            await send(message)

        await self.app(scope, receive, send_and_record if scope["type"] == "http" else send)
```

- `write_audit` เปิดไฟล์แบบ append และ `json.dumps` escape newline ในค่า argument ให้ ไฟล์เลยมีหนึ่ง record ต่อบรรทัดเสมอ
- `redact` ไล่ลงไปทุกชั้นของ `items` ชื่อที่ไม่อยู่ใน `LOGGED_ARGUMENTS` เป็น `[redacted]` ไม่ว่าอยู่ชั้นไหน
- `audit_middleware` ข้าม notification เพราะไม่มีผลให้บันทึก `try/finally` ทำให้ request ที่ Fail กลางทางมีบรรทัดด้วย โดย `outcome` เป็น `error`
- SDK แปลง `ToolError` เป็น `isError: true` ก่อนถึง middleware การปฏิเสธเพราะ scope เลยดูเหมือน error ทั่วไป `scope_refusals` คือ list ที่ middleware สร้างไว้ให้ `require_scope` เติมชื่อ scope ที่ขาด
- `params` เป็น JSON ดิบจาก client เพราะ middleware ทำงานก่อน validation เลยต้องเช็กชนิดก่อนอ่านทุกช่อง
- `HttpAudit` ดัก `http.response.start` เพื่ออ่านสถานะ `scope["user"]` ถูกตั้งโดย `AuthenticationMiddleware` ของ SDK token ที่ถูกแต่สิทธิ์ไม่พอ (`403`) เลยได้ `principal` ส่วนที่ไม่มี token ได้ `anonymous` wrapper อ่านแค่ method กับ path ไม่แตะ headers หรือ query string

### 2. Wiring

```python [cafe_server.py]
from audit import audit_middleware
...
mcp = MCPServer("cafe", auth=AUTH_SETTINGS, token_verifier=DemoTokenVerifier(), middleware=[audit_middleware])
```

```python [auth.py]
from audit import scope_refusals
...
    if access_token is not None and scope not in access_token.scopes:
        scope_refusals.get([]).append(scope)
        raise ToolError(f"This token cannot change orders: missing scope {scope}.")
```

`scope_refusals.get([])` ได้ list ว่างเมื่อไม่มี middleware ครอบ เช่นตอนเรียกฟังก์ชันตรง ๆ ในเทสต์

```python [http_server.py]
import uvicorn

from audit import HttpAudit
from auth import TRANSPORT_SECURITY
from cafe_server import mcp

app = mcp.streamable_http_app(transport_security=TRANSPORT_SECURITY)
app.add_middleware(HttpAudit)

# access_log=False: uvicorn's access log prints the full URL, including any query string.
uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=8765, access_log=False)).run()
```

`mcp.run` ไม่รับ middleware ของ Starlette เลยต้องสร้าง app ด้วย `streamable_http_app` เองแล้วรันด้วย uvicorn ที่ port เดิม ส่วน `access_log=False` อธิบายในหัวข้อ Query String

เพิ่ม `audit.log` ต่อท้าย `.gitignore` แล้วแก้ `tests/conftest.py` สามจุดให้เทสต์เขียน log ลงโฟลเดอร์ชั่วคราว คือ `import audit` parameter `tmp_path_factory` และบรรทัดสุดท้าย

```python [tests/conftest.py]
import pytest

import audit
import database
import notify_server
import stock_server


@pytest.fixture(autouse=True)
def fresh_databases(tmp_path, tmp_path_factory, monkeypatch):
    monkeypatch.setattr(database, "DB_PATH", tmp_path / "cafe.db")
    monkeypatch.setattr(stock_server, "DB_PATH", tmp_path / "stock.db")
    monkeypatch.setattr(notify_server, "DB_PATH", tmp_path / "notify.db")
    monkeypatch.setattr(audit, "AUDIT_LOG", tmp_path_factory.mktemp("audit") / "audit.log")
```

ใช้ `tmp_path_factory.mktemp` แทน `tmp_path` เพราะเทสต์ของบท [Shell Commands from Tool Input](https://iamthana.com/courses/mcp-security/command-injection) เช็กว่าใน `tmp_path` มีแค่ `cafe.db`

## Run It

- staff สร้างและยกเลิกออร์เดอร์
- viewer, guest และ state ที่ไม่ใช่ของตัวเอง
- request ที่ไม่มี token และ token ใน query string

### Start the Server

หยุด server เก่า ลบ `cafe.db` กับ `audit.log` แล้วเปิดใหม่ (Database ถูกสร้างพร้อมออร์เดอร์ 1 กับ 2 ตอนเรียกครั้งแรก)

```bash
rm -f cafe.db audit.log
source tokens.env
uv run python http_server.py
```

อีกหน้าต่างใช้ `URL`, `META` และ `call_tool` ชุดเดิมจากบท [Require a Token](https://iamthana.com/courses/mcp-security/auth) แล้วเพิ่มฟังก์ชันที่ส่ง request โดยไม่มี header `Authorization` กับคำตอบ `accept` ของ elicitation

```bash
no_auth_header() {
  curl -s -o /dev/null -w '%{http_code}\n' "$1" \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json, text/event-stream' \
    -H 'MCP-Protocol-Version: 2026-07-28' \
    -H 'Mcp-Method: tools/call' \
    -H 'Mcp-Name: list_menu' \
    -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"list_menu\",\"arguments\":{},$META}}"
}

ACCEPT='"inputResponses":{"cafe_server:ask_cancel_confirmation":{"action":"accept","content":{"confirm":true}}}'
```

### Staff Orders

staff สร้างออร์เดอร์ แล้วยกเลิกสองรอบแบบบท [Confirm Actions with Elicitation](https://iamthana.com/courses/mcp-server/orders) (`cut` ตัดบรรทัดให้สั้นลง)

```bash
call_tool "$CAFE_STAFF_TOKEN" create_order '{"customer_name":"Somchai","items":[{"menu":"latte","size":"M","quantity":1}]}' | cut -c1-150
```

```text [$ call_tool "$CAFE_STAFF_TOKEN" create_order ...]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"{\n  \"id\": 3,\n  \"customer\": \"Somchai\",\n  \"status\": \"open\",\n  \"total_thb\": 60,\n
```

```bash
RESPONSE=$(call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":3}'); echo "$RESPONSE" | sed -E 's/"requestState":"[^"]*"/"requestState":"..."/' | cut -c1-150; STATE=$(echo "$RESPONSE" | grep -o '"requestState":"[^"]*"')
```

```text [$ RESPONSE=$(call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":3}'); ...][$ RESPONSE=$(call_tool "$CAFE_STAFF_TOKEN" cancel_order ''); ...]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"inputRequests":{"cafe_server:ask_cancel_confirmation":{"method":"elicitation/create","params":{"message":"Cancel or
```

```bash
call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":3}' "$STATE,$ACCEPT," | cut -c1-150
```

```text [$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":3}' "$STATE,$ACCEPT,"][$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '' "$STATE,$ACCEPT,"]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"Order 3 cancelled.","type":"text"}],"isError":false,"resultType":"complete","structuredContent":
```

### Refused and Replayed Calls

viewer ลองยกเลิกและสร้างออร์เดอร์ เอา `STATE` ของ staff ไปใช้ แล้ว guest เรียก `list_menu`

```bash
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}' | cut -c1-150
call_tool "$CAFE_VIEWER_TOKEN" create_order '{"customer_name":"Malee","items":[{"menu":"latte","size":"M","quantity":1}]}' | cut -c1-150
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":3}' "$STATE,$ACCEPT,"
call_tool "$CAFE_GUEST_TOKEN" list_menu '{}'
```

ได้ผลแบบเดียวกับบท [Require a Token](https://iamthana.com/courses/mcp-security/auth) และ [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes) คือ `200` ที่มี `missing scope orders:write` สองครั้ง `400 Invalid or expired requestState` และ `403 insufficient_scope` ส่วนที่ใหม่คือสิ่งที่ log บันทึกไว้

### Query String

ส่งสองแบบที่ไม่มี header `Authorization` แบบแรกไม่มี token แบบที่สองใส่ token ใน query string (ใช้ค่าปลอม `not-a-real-token` เพราะ token ใน URL ผิด spec อยู่แล้ว)

```bash
no_auth_header $URL
no_auth_header "$URL?access_token=not-a-real-token"
```

ได้ `401` ทั้งคู่ และ terminal ของ `http_server.py` ไม่มีบรรทัด request โผล่เลย ลองเทียบกับ uvicorn ที่ตั้งค่าเริ่มต้น เปิด server ตัวที่สองที่ port 8766 ในอีก terminal โดยไม่ปิด access log

```bash
uv run python -c "import uvicorn; from cafe_server import mcp; uvicorn.run(mcp.streamable_http_app(), port=8766)"
```

```bash
no_auth_header "http://127.0.0.1:8766/mcp?access_token=not-a-real-token"
```

```text [terminal ที่รัน server port 8766]
INFO:     127.0.0.1:49776 - "POST /mcp?access_token=not-a-real-token HTTP/1.1" 401 Unauthorized
```

uvicorn เขียน URL เต็มลง log รวมค่าหลัง `?` ถ้าเป็น token ที่ใช้ได้ มันก็อยู่ใน log ของ server ทันที `http_server.py` เลยตั้ง `access_log=False` (ถ้ารันจาก command line ใช้ `--no-access-log`) หยุด server port 8766 ด้วย `Ctrl+C` ก่อนไปต่อ

## Query the Log

```bash
cat audit.log
```

```text [$ cat audit.log]
{"ts": "2026-11-24T12:26:55.148+00:00", "request_id": "7e22c9358030", "principal": "staff-demo", "method": "tools/call", "name": "create_order", "arguments": {"customer_name": "[redacted]", "items": [{"menu": "latte", "size": "M", "quantity": 1}]}, "outcome": "ok"}
{"ts": "2026-11-24T12:26:55.158+00:00", "request_id": "86eb359eb35b", "principal": "staff-demo", "method": "tools/call", "name": "cancel_order", "arguments": {"order_id": 3}, "outcome": "input_required"}
{"ts": "2026-11-24T12:26:55.174+00:00", "request_id": "e40f07719a99", "principal": "staff-demo", "method": "tools/call", "name": "cancel_order", "arguments": {"order_id": 3}, "answers": ["accept"], "outcome": "ok"}
{"ts": "2026-11-24T12:26:55.185+00:00", "request_id": "c883a5e6b8f6", "principal": "viewer-demo", "method": "tools/call", "name": "cancel_order", "arguments": {"order_id": 1}, "outcome": "refused"}
{"ts": "2026-11-24T12:26:55.195+00:00", "request_id": "bf12775d8723", "principal": "viewer-demo", "method": "tools/call", "name": "create_order", "arguments": {"customer_name": "[redacted]", "items": [{"menu": "latte", "size": "M", "quantity": 1}]}, "outcome": "refused"}
{"ts": "2026-11-24T12:26:55.204+00:00", "request_id": "7c76ec0e50db", "principal": "viewer-demo", "method": "http", "name": "POST /mcp", "outcome": "http_400"}
{"ts": "2026-11-24T12:26:55.211+00:00", "request_id": "c28a16fae5ee", "principal": "guest-demo", "method": "http", "name": "POST /mcp", "outcome": "http_403"}
{"ts": "2026-11-24T12:26:55.218+00:00", "request_id": "c64e40a66bd5", "principal": "anonymous", "method": "http", "name": "POST /mcp", "outcome": "http_401"}
{"ts": "2026-11-24T12:26:55.224+00:00", "request_id": "f5f5b51a3289", "principal": "anonymous", "method": "http", "name": "POST /mcp", "outcome": "http_401"}
```

- เก้าบรรทัดตรงกับเก้า request ตามลำดับ
- ไม่มีชื่อ `Somchai` กับ `Malee` แต่ `"customer_name": "[redacted]"` บอกว่ามีส่งมา
- viewer ได้ `refused` ทั้งที่ HTTP ตอบ `200`
- `requestState` ที่ viewer ขโมยมาใช้ถูก SDK ปฏิเสธก่อนถึง middleware ของเรา เลยมีแค่บรรทัด `http_400` จากชั้น HTTP

### Who Cancelled

`cancel_order` ที่ได้ `ok` อาจแปลว่ายกเลิกแล้ว หรือผู้ใช้ตอบ `decline` (tool ตอบ `Order N was not cancelled.` ก็ได้ `ok` เหมือนกัน) เลยต้องดู `answers` ด้วย

```bash
jq -c 'select(.name == "cancel_order" and .arguments.order_id == 3 and .answers == ["accept"] and .outcome == "ok") | {ts, principal}' audit.log
```

```text [$ jq -c 'select(.name == "cancel_order" and .arguments.order_id == 3 and .answers == ["accept"] and .outcome == "ok") | {ts, principal}' audit.log][$ jq -c 'select(.name == "cancel_order" and .arguments.order_id == 3 and .answers == ["accept"] and .outcome == "ok") | ' audit.log]
{"ts":"2026-11-24T12:26:55.174+00:00","principal":"staff-demo"}
```

`requestState` ผูกกับ principal ที่เปิดคำถาม (บท [Limit Tools by Scope](https://iamthana.com/courses/mcp-security/scopes)) คนที่กดยืนยันเลยเป็นคนเดียวกับที่ขอยกเลิก

### Refusals

```bash
jq -r 'select(.outcome == "refused") | [.ts, .principal, .name] | @tsv' audit.log
```

```text [$ jq -r 'select(.outcome == "refused") | [.ts, .principal, .name] | @tsv' audit.log]
2026-11-24T12:26:55.185+00:00   viewer-demo cancel_order
2026-11-24T12:26:55.195+00:00   viewer-demo create_order
```

### Secret Check

หาค่าของ token ทั้งสี่ตัวในไฟล์ด้วย `grep -F` (shell เป็นคนขยายตัวแปร ค่าจริงไม่โผล่บนจอ) แล้วหาคำที่บอกว่า header หรือ query string หลุดเข้ามา คำสั่งแรกเขียนแบบ bash ถ้าใช้ zsh (ค่าเริ่มต้นของ macOS) เปลี่ยน `${!variable}` เป็น `${(P)variable}`

```bash
for variable in CAFE_STAFF_TOKEN CAFE_VIEWER_TOKEN CAFE_GUEST_TOKEN CAFE_FOREIGN_TOKEN; do echo "$variable: $(grep -cF "${!variable}" audit.log)"; done
grep -ciE 'authorization|bearer|access_token' audit.log
```

```text [$ for variable in CAFE_STAFF_TOKEN ...; do echo "$variable: $(grep -cF "${!variable}" audit.log)"; done][$ for variable in CAFE_STAFF_TOKEN ...; do echo "$variable: $(grep -cF "$" audit.log)"; done]
CAFE_STAFF_TOKEN: 0
CAFE_VIEWER_TOKEN: 0
CAFE_GUEST_TOKEN: 0
CAFE_FOREIGN_TOKEN: 0
```

```text [$ grep -ciE 'authorization|bearer|access_token' audit.log]
0
```

## Run the Tests

- `tests/test_audit.py` 6 ตัว
- ให้ log เก็บ argument ดิบ header และ query string แล้วดูเทสต์ Fail
- ถอดการเติม `scope_refusals` แล้วดูเทสต์ Fail

```python [tests/test_audit.py]
import json

import pytest
from mcp import Client
from mcp.server.auth.middleware.auth_context import auth_context_var
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
from mcp.server.auth.provider import AccessToken
from mcp_types import ElicitResult
from starlette.testclient import TestClient

import audit
from cafe_server import mcp as cafe
from test_transport_security import served_config

ONE_LATTE = {"items": [{"menu": "latte", "size": "M", "quantity": 1}], "customer_name": "Somchai Secretname"}
TOKEN_VARIABLES = ("CAFE_STAFF_TOKEN", "CAFE_VIEWER_TOKEN", "CAFE_GUEST_TOKEN", "CAFE_FOREIGN_TOKEN")


def audit_records() -> list[dict]:
    return [json.loads(line) for line in audit.AUDIT_LOG.read_text().splitlines()]


def sign_in_with(scopes: list[str]):
    auth_context_var.set(AuthenticatedUser(AccessToken(token="unused", client_id="test", scopes=scopes)))


@pytest.fixture(autouse=True)
def no_signed_in_user():
    yield
    auth_context_var.set(None)


async def test_refused_call_is_logged_as_refused():
    sign_in_with(["orders:read"])
    async with Client(cafe) as client:
        await client.call_tool("cancel_order", {"order_id": 1})
    record = audit_records()[-1]
    assert (record["principal"], record["name"], record["arguments"], record["outcome"]) == ("test", "cancel_order", {"order_id": 1}, "refused")


async def test_confirmed_cancel_logs_input_required_then_ok():
    sign_in_with(["orders:read", "orders:write"])

    async def accept(context, params):
        return ElicitResult(action="accept", content={"confirm": True})

    async with Client(cafe, elicitation_callback=accept) as client:
        await client.call_tool("cancel_order", {"order_id": 1})
    cancels = [record for record in audit_records() if record.get("name") == "cancel_order"]
    assert [(record["outcome"], record.get("answers")) for record in cancels] == [("input_required", None), ("ok", ["accept"])]


async def test_call_without_token_is_logged_as_stdio():
    async with Client(cafe) as client:
        await client.call_tool("list_menu", {})
    assert audit_records()[-1]["principal"] == "stdio"


def send_requests_with_every_token(monkeypatch) -> None:
    for variable in TOKEN_VARIABLES:
        monkeypatch.setenv(variable, f"secret-for-{variable}")
    base = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "tools/call",
        "Mcp-Name": "create_order",
    }
    meta = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}
    body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "create_order", "arguments": ONE_LATTE, "_meta": meta}}
    with TestClient(served_config(monkeypatch).app, base_url="http://127.0.0.1:8765") as http:
        for variable in TOKEN_VARIABLES:
            http.post("/mcp", headers={**base, "Authorization": f"Bearer secret-for-{variable}"}, json=body)
        http.post("/mcp", headers=base, json=body)
        http.post("/mcp?access_token=secret-for-CAFE_STAFF_TOKEN", headers=base, json=body)


def test_no_token_value_reaches_the_log(monkeypatch):
    send_requests_with_every_token(monkeypatch)
    log = audit.AUDIT_LOG.read_text()
    assert "secret-for-" not in log
    assert not any(word in log.lower() for word in ("authorization", "bearer", "access_token"))


def test_http_layer_logs_rejected_requests_with_principal(monkeypatch):
    send_requests_with_every_token(monkeypatch)
    http_records = [(record["principal"], record["outcome"]) for record in audit_records() if record["method"] == "http"]
    assert http_records == [("guest-demo", "http_403"), ("anonymous", "http_401"), ("anonymous", "http_401"), ("anonymous", "http_401")]


def test_customer_name_is_redacted(monkeypatch):
    send_requests_with_every_token(monkeypatch)
    log = audit.AUDIT_LOG.read_text()
    assert "Somchai" not in log
    assert '"customer_name": "[redacted]"' in log
```

- สามตัวแรกเรียก `cafe` ใน process เดียวกัน ตรวจ `refused`, ลำดับ `input_required` แล้ว `ok` พร้อม `answers` และ principal `stdio`
- `send_requests_with_every_token` ใช้ `served_config` จากบท [Defend the HTTP Server](https://iamthana.com/courses/mcp-security/http-defenses) รัน `http_server.py` ตัวจริงโดยไม่เปิด port เลยทดสอบ `HttpAudit` ตามที่ต่อไว้จริง แล้วส่ง token ปลอมทั้งสี่ตัว request ที่ไม่มี token และ token ใน query string
- สามตัวหลังตรวจว่าไม่มีค่า token ใน log, principal ของบรรทัด HTTP ถูก และชื่อลูกค้าถูกซ่อน

```bash
uv run pytest tests/test_audit.py -q
```

```text [$ uv run pytest tests/test_audit.py -q]
......                                                                   [100%]
6 passed in 0.09s
```

ทีนี้ทำให้ log รั่ว ใน `audit.py` เปลี่ยน `arguments=redact(arguments) if isinstance(arguments, dict) else None` เป็น `arguments=arguments` แล้วเพิ่มสองบรรทัดใต้ `name=f"{scope['method']} {scope['path']}",` ใน `HttpAudit`

```python
headers={key.decode(): value.decode() for key, value in scope["headers"]},
                    query=scope["query_string"].decode(),
```

```bash
uv run pytest tests/test_audit.py -q | grep -E '^E +assert|^FAILED|^[0-9]+ (passed|failed)|^[0-9]+ failed'
```

```text [$ uv run pytest tests/test_audit.py -q | grep -E '^E +assert|^FAILED|^[0-9]+ (passed|failed)|^[0-9]+ failed']
E       assert 'secret-for-' not in '{"ts": "202...http_401"}\n'
E       assert 'Somchai' not in '{"ts": "202...http_401"}\n'
FAILED tests/test_audit.py::test_no_token_value_reaches_the_log - assert 'sec...
FAILED tests/test_audit.py::test_customer_name_is_redacted - assert 'Somchai'...
2 failed, 4 passed in 0.11s
```

คืนโค้ดทั้งสองจุด แล้วลบบรรทัด `scope_refusals.get([]).append(scope)` ออกจาก `require_scope`

```bash
uv run pytest tests/test_audit.py -q | grep -E '^FAILED|^[0-9]+ (passed|failed)|^[0-9]+ failed'
```

```text [$ uv run pytest tests/test_audit.py -q | grep -E '^FAILED|^[0-9]+ (passed|failed)|^[0-9]+ failed']
FAILED tests/test_audit.py::test_refused_call_is_logged_as_refused - Assertio...
1 failed, 5 passed in 0.11s
```

พอไม่มีบรรทัดนี้ middleware เห็นแค่ `isError` เลยบันทึกการปฏิเสธเป็น `error` คืนบรรทัดนั้นแล้วรันทั้งชุด

```bash
uv run pytest -q
```

```text [$ uv run pytest -q]
..................................................                       [100%]
50 passed in 0.32s
```

44 ตัวจากบท [Shell Commands from Tool Input](https://iamthana.com/courses/mcp-security/command-injection) บวก 6 ตัวของบทนี้

## Pitfalls

- allowlist คุมชื่อ argument ไม่ได้คุมเนื้อหา ถ้า client ยัดข้อมูลอื่นลงช่อง `day` มันก็เข้า log
- `principal` คือ `client_id` ของ token ถ้าหลายคนใช้ token เดียวกัน log ก็บอกได้แค่ว่า token ไหน ไม่ใช่คนไหน
- ถ้าเขียน log ไม่ได้ (ดิสก์เต็ม โฟลเดอร์หาย) `write_audit` ใน `finally` จะ Fail หลัง tool ทำงานไปแล้ว `create_order` ได้ `-32603 Internal server error` ทั้งที่ออร์เดอร์ลง Database แล้ว client ที่ลองใหม่เลยสร้างออร์เดอร์ซ้ำ ถ้า server ต้องไม่แก้ข้อมูลตอนบันทึกไม่ได้ ให้เขียนหนึ่งบรรทัดก่อน `call_next` แล้วค่อยเขียนผลใน `finally`
- `401` ที่ใครก็ส่งได้เขียนไฟล์ทุกครั้ง ต้อง rotate ไฟล์และกำหนดอายุเก็บ และ log ที่อยู่เครื่องเดียวกับ server ใครมีสิทธิ์ของ process ก็แก้หรือลบได้ ถ้าต้องกันตรงนี้ให้ส่ง log ไปเก็บที่ระบบอื่น
- `MCPServer.middleware` ใน SDK 2.3.0 ยังเป็น provisional (signature อาจเปลี่ยนใน 2.x) อัปเดต SDK แล้วรัน `test_audit.py` ก่อนใช้งาน

## Summary

`audit.log` บอกได้ว่า `staff-demo` เป็นคนยืนยันการยกเลิกออร์เดอร์ 3 และ viewer ถูกปฏิเสธสองครั้ง โดยไม่มีชื่อลูกค้าหรือ token อยู่ในไฟล์ middleware ของ SDK เก็บ request ของ MCP ส่วน `HttpAudit` เก็บ request ที่ถูกปฏิเสธก่อนถึง MCP และ `access_log=False` กันไม่ให้ uvicorn เขียน query string ลง log เทสต์ชุด 6 ตัวนี้ Fail เมื่อ log เริ่มเก็บของที่ไม่ควรเก็บ

ถึงตรงนี้เราดูแลโค้ดของเราเองครบแล้ว แต่ `cafe-mcp` ยังรันโค้ดของคนอื่นอีกเยอะ ทั้ง SDK และ dependency ที่ติดมาด้วย บทหน้า [Lock Dependencies and Pin Servers](https://iamthana.com/courses/mcp-security/supply-chain) ดูว่าล็อกพวกนี้ยังไงครับ

## References

- [MCP08:2025 Lack of Audit and Telemetry (OWASP MCP Top 10)](https://github.com/OWASP/www-project-mcp-top-10/blob/165fe0f78ef104459237b4a8e0f6e78db9b02391/2025/MCP08-2025%E2%80%93Lack-of-Audit-and-Telemetry.md)
- [MCP01:2025 Token Mismanagement & Secret Exposure (OWASP MCP Top 10)](https://github.com/OWASP/www-project-mcp-top-10/blob/165fe0f78ef104459237b4a8e0f6e78db9b02391/2025/MCP01-2025-Token-Mismanagement-and-Secret-Exposure.md)
- [Uvicorn: Settings](https://uvicorn.dev/settings/)
- [jq Manual](https://jqlang.org/manual/)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)

## Sitemap

See the full [sitemap](https://iamthana.com/sitemap.md) for all pages.
