Lesson 10
Audit Tool Calls
เพิ่ม audit log แบบ JSON lines ให้ HTTP server ของ cafe-mcp บันทึกว่าใครเรียก tool ไหนด้วย argument อะไรและผลเป็นอย่างไร โดยซ่อนชื่อลูกค้าและไม่เก็บ token แล้วใช้ jq หาว่าใครยกเลิกออร์เดอร์
ทุกบทที่ผ่านมาเราลองโจมตีแล้วดูผลทันที แต่ตอนใช้งานจริงไม่มีใครนั่งดู ถ้ามีคนยกเลิกออร์เดอร์หรือลองแทรกคำสั่งเข้ามา เราต้องย้อนดูได้ทีหลังครับ บทนี้เพิ่ม audit log ให้ cafe-mcp บันทึก request ละหนึ่งบรรทัด JSON ใน audit.log ว่าใครเรียกอะไร ด้วย argument อะไร และผลเป็นอย่างไร
ทุกคำสั่งรันในโฟลเดอร์ cafe-mcp และต้องมี tokens.env จากบท Require a Token
What to Log
OWASP นับการไม่มี log ว่าเป็น MCP08 Lack of Audit and Telemetry log ต้องบอกได้ว่าใครเรียกเมื่อไหร่ และ MCP01 ให้ซ่อน secret ก่อนเขียนลง log ด้วย
Fields
| Field | Value |
|---|---|
ts | เวลา UTC ระดับมิลลิวินาที |
request_id | เลขสุ่ม 12 ตัวของแต่ละบรรทัด |
principal | client_id ของ token เช่น staff-demo, anonymous เมื่อไม่มี token ที่ชั้น HTTP หรือ stdio เมื่อเรียกแบบ stdio |
method | tools/call, resources/read ฯลฯ หรือ http |
name | ชื่อ tool, URI ของ resource หรือ POST /mcp |
arguments | argument ที่ซ่อนค่าแล้ว |
answers | action ของคำตอบ elicitation เช่น accept |
outcome | ผลของ request ตามตารางข้างล่าง |
outcome เป็นแค่สรุป ไม่เก็บ response ทั้งก้อน เพราะ create_order ตอบกลับมาพร้อมชื่อลูกค้า
| Outcome | Meaning |
|---|---|
ok | tool ทำงานสำเร็จ |
error | tool ตอบ isError หรือ request Fail ในชั้น MCP |
refused | require_scope ปฏิเสธเพราะ token ไม่มี orders:write |
input_required | server ส่งคำถามยืนยันกลับไปรอคำตอบ |
http_401, http_403, http_400 | HTTP ตอบสถานะนั้นก่อนถึง MCP |
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
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.dumpsescape 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 ได้anonymouswrapper อ่านแค่ method กับ path ไม่แตะ headers หรือ query string
2. Wiring
from audit import audit_middleware
...
mcp = MCPServer("cafe", auth=AUTH_SETTINGS, token_verifier=DemoTokenVerifier(), middleware=[audit_middleware])
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 ครอบ เช่นตอนเรียกฟังก์ชันตรง ๆ ในเทสต์
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 และบรรทัดสุดท้าย
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 เช็กว่าใน 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 ตอนเรียกครั้งแรก)
rm -f cafe.db audit.log
source tokens.env
uv run python http_server.py
อีกหน้าต่างใช้ URL, META และ call_tool ชุดเดิมจากบท Require a Token แล้วเพิ่มฟังก์ชันที่ส่ง request โดยไม่มี header Authorization กับคำตอบ accept ของ elicitation
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 (cut ตัดบรรทัดให้สั้นลง)
call_tool "$CAFE_STAFF_TOKEN" create_order '{"customer_name":"Somchai","items":[{"menu":"latte","size":"M","quantity":1}]}' | cut -c1-150
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
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":"[^"]*"')
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"inputRequests":{"cafe_server:ask_cancel_confirmation":{"method":"elicitation/create","params":{"message":"Cancel or
call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":3}' "$STATE,$ACCEPT," | cut -c1-150
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
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 และ Limit Tools by Scope คือ 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 อยู่แล้ว)
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
uv run python -c "import uvicorn; from cafe_server import mcp; uvicorn.run(mcp.streamable_http_app(), port=8766)"
no_auth_header "http://127.0.0.1:8766/mcp?access_token=not-a-real-token"
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
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 ด้วย
jq -c 'select(.name == "cancel_order" and .arguments.order_id == 3 and .answers == ["accept"] and .outcome == "ok") | {ts, principal}' audit.log
{"ts":"2026-11-24T12:26:55.174+00:00","principal":"staff-demo"}
requestState ผูกกับ principal ที่เปิดคำถาม (บท Limit Tools by Scope) คนที่กดยืนยันเลยเป็นคนเดียวกับที่ขอยกเลิก
Refusals
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}
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
CAFE_STAFF_TOKEN: 0
CAFE_VIEWER_TOKEN: 0
CAFE_GUEST_TOKEN: 0
CAFE_FOREIGN_TOKEN: 0
0
Run the Tests
tests/test_audit.py6 ตัว- ให้ log เก็บ argument ดิบ header และ query string แล้วดูเทสต์ Fail
- ถอดการเติม
scope_refusalsแล้วดูเทสต์ Fail
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และ principalstdio send_requests_with_every_tokenใช้served_configจากบท Defend the HTTP Server รันhttp_server.pyตัวจริงโดยไม่เปิด port เลยทดสอบHttpAuditตามที่ต่อไว้จริง แล้วส่ง token ปลอมทั้งสี่ตัว request ที่ไม่มี token และ token ใน query string- สามตัวหลังตรวจว่าไม่มีค่า token ใน log, principal ของบรรทัด HTTP ถูก และชื่อลูกค้าถูกซ่อน
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
headers={key.decode(): value.decode() for key, value in scope["headers"]},
query=scope["query_string"].decode(),
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
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 คืนบรรทัดนั้นแล้วรันทั้งชุด
uv run pytest -q
.................................................. [100%]
50 passed in 0.32s
44 ตัวจากบท Shell Commands from Tool Input บวก 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 ดูว่าล็อกพวกนี้ยังไงครับ