Lesson 12

Find Shadow Servers

เขียน inventory.py ค้นหา .mcp.json ในทุกโฟลเดอร์ย่อยแล้วบอกว่าคำสั่ง npx กับ uvx ตัวไหนไม่ได้ล็อกเวอร์ชัน ใช้ lsof กับ curl หา server ที่เปิด port ค้างอยู่บนเครื่อง และดู policy ของ Claude Code ที่คุม server ทั้งองค์กร

shadow server คือ MCP server ที่ทำงานอยู่โดยไม่มีใครลงทะเบียนหรือ review ครับ (OWASP นับเป็น MCP09) server แบบนี้ไม่เคยผ่าน review_tools.py, การ pin หรือ audit log ของบทก่อน ๆ เลย บทนี้หาจากสองที่ในเครื่องตัวเองกับ repo ของทีม คือไฟล์ .mcp.json และ port ที่เปิดรออยู่

ทุกคำสั่งรันในโฟลเดอร์ cafe-mcp และตรวจแค่เครื่องตัวเองกับโฟลเดอร์ที่ clone repo ของทีมมา (การสแกนเครือข่ายเป็นงานของทีมที่ดูแลเครือข่ายและได้รับอนุญาต)

Where Servers Live

Claude Code เก็บ server ไว้สามที่ตาม scope

ScopeLoads inStored in
Localโปรเจกต์นี้~/.claude.json
Projectโปรเจกต์นี้ แชร์ผ่าน git.mcp.json ใน root ของโปรเจกต์
Userทุกโปรเจกต์~/.claude.json

ค่าเริ่มต้นใครใช้ Claude Code ก็ต่อ server อะไรก็ได้ .mcp.json ที่มากับ repo จะถามอนุมัติก่อนเฉพาะตอนเปิด claude แบบ interactive ส่วน claude -p กับ Agent SDK โหลดโดยไม่ถาม .mcp.json ใน repo ที่ clone มาเลยเป็นที่แรกที่ต้องดู

Inventory

  • inventory.py
  • โปรเจกต์ตัวอย่างสามโปรเจกต์
  • tests/test_inventory.py

inventory.py

inventory.py
"""List every MCP server declared in .mcp.json files under a folder.

  uv run python inventory.py ROOT
"""

import json
import re
import sys
from pathlib import Path
from urllib.parse import urlsplit

SKIPPED_FOLDERS = {"node_modules", ".venv", ".git"}
# A version after a package name: some-server@1.2.3 or some-server==1.2.3. A scope such as @1password/ is not a version.
PIN_PATTERN = re.compile(r"\S@\d|==\d")
LAUNCHERS_THAT_DOWNLOAD = {"npx", "uvx"}


def find_config_files(root: Path):
    for path in sorted(root.rglob(".mcp.json")):
        if not SKIPPED_FOLDERS & set(path.relative_to(root).parts):
            yield path


def describe(server: dict) -> tuple[str, str]:
    if "url" in server:
        parts = urlsplit(server["url"])
        # user:password@ and ?query can carry a token, so the printed URL keeps only scheme, host, port and path.
        url = parts._replace(netloc=parts.netloc.rpartition("@")[2], query="", fragment="").geturl()
        header_names = ",".join(server.get("headers", {}))
        return server.get("type", "http"), f"{url}  headers: {header_names or '-'}"
    command = [server["command"], *server.get("args", [])]
    floating = command[0] in LAUNCHERS_THAT_DOWNLOAD and not PIN_PATTERN.search(" ".join(command))
    env_names = ",".join(server.get("env", {}))
    return "stdio", f"{' '.join(command)}  env: {env_names or '-'}" + ("  FLOATING" if floating else "")


def main(root: Path) -> int:
    count = 0
    for config in find_config_files(root):
        servers = json.loads(config.read_text()).get("mcpServers", {})
        for name, server in servers.items():
            kind, detail = describe(server)
            print(f"{config.parent.relative_to(root)}  {name}  {kind}  {detail}")
            count += 1
    print(f"{count} servers")
    return 0


if __name__ == "__main__":
    sys.exit(main(Path(sys.argv[1])))
  • ข้าม node_modules, .venv และ .git แล้วพิมพ์ server ละบรรทัด คือโฟลเดอร์ ชื่อ ชนิด และคำสั่งหรือ URL
  • env กับ headers พิมพ์แค่ชื่อ ไม่พิมพ์ค่า เพราะไฟล์พวกนี้มักมี token
  • URL ถูกตัด user:password@ กับ query string ออก ด้วยเหตุผลเดียวกับที่บท Audit Tool Calls ไม่เก็บ query string

Demo Projects

สร้างโปรเจกต์ตัวอย่างสามโปรเจกต์ใน demo-projects/ (ค่าใน env กับ header เป็นข้อความตัวอย่าง ใช้ไม่ได้จริง)

bash
mkdir -p demo-projects/{cafe-site,research-notebook,old-prototype/server,old-prototype/node_modules/pkg}
cat > demo-projects/cafe-site/.mcp.json <<'EOF'
{
  "mcpServers": {
    "cafe": { "type": "stdio", "command": "uv", "args": ["run", "python", "cafe_server.py"] },
    "currency": { "command": "uvx", "args": ["--from", "currency-mcp==1.4.0", "currency-mcp"] }
  }
}
EOF
cat > demo-projects/research-notebook/.mcp.json <<'EOF'
{
  "mcpServers": {
    "notes-search": {
      "command": "npx",
      "args": ["-y", "notes-search-mcp"],
      "env": { "NOTES_API_KEY": "placeholder-not-a-real-key" }
    }
  }
}
EOF
cat > demo-projects/old-prototype/server/.mcp.json <<'EOF'
{
  "mcpServers": {
    "crm": {
      "type": "http",
      "url": "http://10.0.4.17:8080/mcp",
      "headers": { "Authorization": "Bearer placeholder-not-a-real-token" }
    }
  }
}
EOF
cat > demo-projects/old-prototype/node_modules/pkg/.mcp.json <<'EOF'
{ "mcpServers": { "vendored": { "command": "node", "args": ["server.js"] } } }
EOF
find demo-projects -name .mcp.json | sort
ผลลัพธ์จาก find demo-projects -name .mcp.json | sort
demo-projects/cafe-site/.mcp.json
demo-projects/old-prototype/node_modules/pkg/.mcp.json
demo-projects/old-prototype/server/.mcp.json
demo-projects/research-notebook/.mcp.json
bash
uv run python inventory.py demo-projects
ผลลัพธ์จาก uv run python inventory.py demo-projects
cafe-site  cafe  stdio  uv run python cafe_server.py  env: -
cafe-site  currency  stdio  uvx --from currency-mcp==1.4.0 currency-mcp  env: -
old-prototype/server  crm  http  http://10.0.4.17:8080/mcp  headers: Authorization
research-notebook  notes-search  stdio  npx -y notes-search-mcp  env: NOTES_API_KEY  FLOATING
4 servers

สี่ไฟล์ script อ่านสาม (ข้าม node_modules) ได้สี่ server สองตัวที่ต้องถามต่อคือ crm ที่ชี้ไป host อื่นในเครือข่ายซึ่งไม่มีใครจำได้ว่าคืออะไร และ notes-search ที่ดาวน์โหลดเวอร์ชันล่าสุดทุกครั้ง แถมส่ง NOTES_API_KEY ให้ด้วย

Run the Tests

tests/test_inventory.py
import json

import inventory


def write_config(folder, servers):
    folder.mkdir(parents=True, exist_ok=True)
    (folder / ".mcp.json").write_text(json.dumps({"mcpServers": servers}))


def run(root, capsys) -> str:
    inventory.main(root)
    return capsys.readouterr().out


def test_lists_stdio_and_http_servers(tmp_path, capsys):
    write_config(tmp_path / "shop", {"cafe": {"command": "uv", "args": ["run", "cafe_server.py"]}})
    write_config(tmp_path / "lab", {"remote": {"type": "http", "url": "http://10.0.0.5:8080/mcp"}})
    output = run(tmp_path, capsys)
    assert "shop  cafe  stdio  uv run cafe_server.py" in output
    assert "lab  remote  http  http://10.0.0.5:8080/mcp" in output
    assert "2 servers" in output


def test_flags_unpinned_downloads_only(tmp_path, capsys):
    write_config(
        tmp_path,
        {
            "floating": {"command": "npx", "args": ["-y", "some-mcp-server"]},
            "pinned": {"command": "npx", "args": ["-y", "some-mcp-server@1.2.3"]},
            "pinned-uvx": {"command": "uvx", "args": ["--from", "some-server==1.2.3", "run"]},
            "local": {"command": "uv", "args": ["run", "server.py"]},
            "scoped": {"command": "npx", "args": ["-y", "@1password/mcp"]},
        },
    )
    flagged = [line.split()[1] for line in run(tmp_path, capsys).splitlines() if line.endswith("FLOATING")]
    assert flagged == ["floating", "scoped"]


def test_prints_names_never_secret_values(tmp_path, capsys):
    write_config(
        tmp_path,
        {
            "a": {"command": "uv", "args": ["run", "a.py"], "env": {"API_KEY": "value-one"}},
            "b": {"type": "http", "url": "https://x.example/mcp", "headers": {"Authorization": "value-two"}},
            "c": {"type": "http", "url": "https://user:value-three@y.example:8443/mcp?api_key=value-four"},
        },
    )
    output = run(tmp_path, capsys)
    assert not any(value in output for value in ("value-one", "value-two", "value-three", "value-four"))
    assert "API_KEY" in output and "Authorization" in output and "https://y.example:8443/mcp" in output


def test_skips_dependency_folders(tmp_path, capsys):
    write_config(tmp_path / "node_modules" / "pkg", {"hidden": {"command": "x"}})
    assert "0 servers" in run(tmp_path, capsys)
  • เทสต์ที่สองมี @1password/mcp ที่ @ เป็นชื่อ scope ไม่ใช่เวอร์ชัน ตัวนี้ต้องขึ้น FLOATING ด้วย
  • เทสต์ที่สามเช็กว่าค่าใน env, header, รหัสผ่านใน URL และ query string ไม่โผล่ แต่ชื่อยังอยู่
bash
uv run pytest tests/test_inventory.py -q
ผลลัพธ์จาก uv run pytest tests/test_inventory.py -q
....                                                                     [100%]
4 passed in 0.02s

ลองให้ script รั่ว ใน describe เปลี่ยน env_names = ",".join(server.get("env", {})) เป็น env_names = str(server.get("env", {})) ให้พิมพ์ dict ทั้งก้อน

bash
uv run pytest tests/test_inventory.py -q 2>&1 | grep -E '^(E +assert|FAILED)|passed|failed'
ผลลัพธ์จาก uv run pytest tests/test_inventory.py -q 2>&1 | grep -E '^(E +assert|FAILED)|passed|failed'
E       assert not True
FAILED tests/test_inventory.py::test_prints_names_never_secret_values - asser...
1 failed, 3 passed in 0.03s

คืนบรรทัดนั้น แล้วลองเปลี่ยน url = parts._replace(...) เป็น url = server["url"] ก็ Fail ที่เทสต์เดียวกัน คืนโค้ดเดิมแล้วรันทั้งชุด

bash
uv run pytest -q
ผลลัพธ์จาก uv run pytest -q
......................................................                   [100%]
54 passed in 0.36s

50 ตัวจากบท Audit Tool Calls บวก 4 ตัวของบทนี้

Listening Ports

  • เปิด server แล้วหา PID
  • ดู port ที่ process นั้นเปิด
  • ลองเรียก /mcp

lsof -nP -iTCP -sTCP:LISTEN แสดง port ที่รอรับการเชื่อมต่อของทุก process ในเครื่อง ตัวอย่างนี้กรองด้วย PID ของ server ที่เราเปิดเอง

Start and Find

ถ้า http_server.py จากบท Audit Tool Calls ยังรันอยู่ ให้หยุดก่อน (Ctrl+C) เพราะ port 8765 เปิดซ้ำไม่ได้ แล้วเปิด http_server.py ไว้เบื้องหลัง รอสักครู่ให้มันเปิด port แล้วค่อยรันสองบรรทัดหลัง ซึ่งเก็บ PID ของ process ที่ฟัง port 8765

bash
(source tokens.env; uv run python http_server.py &)
PID=$(lsof -nP -iTCP:8765 -sTCP:LISTEN -t)
lsof -nP -iTCP -sTCP:LISTEN -a -p $PID | awk '{print $1, $2, $9, $10}'
ผลลัพธ์จาก lsof -nP -iTCP -sTCP:LISTEN -a -p $PID | awk '{print $1, $2, $9, $10}'
COMMAND PID NAME 
python3.1 44844 127.0.0.1:8765 (LISTEN)

Probe

port ที่เปิดอยู่ไม่ได้บอกว่าเป็น MCP ต้องลองเรียก path ที่ MCP ใช้ ถ้า /mcp ตอบต่างจาก path ที่ไม่มีอยู่ ก็น่าสงสัยแล้ว

bash
for port in $(lsof -nP -iTCP -sTCP:LISTEN -a -p $PID -Fn | sed -n 's/^n.*:\([0-9]*$\)/\1/p'); do
  echo "port $port  POST /mcp -> $(curl -s -o /dev/null -w '%{http_code}' -m 2 -X POST http://127.0.0.1:$port/mcp)  GET /nope -> $(curl -s -o /dev/null -w '%{http_code}' -m 2 http://127.0.0.1:$port/nope)"
done
ผลลัพธ์จาก for port in $(lsof ...); do echo "port $port ..."; done
port 8765  POST /mcp -> 401  GET /nope -> 404

401 ที่ /mcp กับ 404 ที่ path อื่น แปลว่ามี server ที่รู้จัก /mcp และบังคับ token ถ้าเจอ server ที่ตอบ 200 โดยไม่ต้องมี token ใครต่อถึง port นี้ได้ก็เรียก tool ได้ ปิด server แล้วเช็กว่า port ว่าง

bash
kill $PID
lsof -nP -iTCP:8765 -sTCP:LISTEN | wc -l | tr -d ' '
ผลลัพธ์จาก lsof -nP -iTCP:8765 -sTCP:LISTEN | wc -l | tr -d ' '
0

After Discovery

server ที่เจอแล้วก็เข้าขั้นตอนเดิมของคอร์สนี้ review_tools.py review กับ pin ก่อนอนุมัติ (บท Defend Against Tool Attacks) และถ้าเป็น server ของเราเองก็ต้องมี audit log

ฝั่งองค์กร Claude Code มี policy ให้แอดมินคุม

  • managed-mcp.json ให้ Claude Code โหลดเฉพาะ server ที่ไฟล์นี้กำหนด
  • managedMcpServers ส่ง server ให้ทุกคน โดยผู้ใช้ยังเพิ่มของตัวเองได้
  • allowedMcpServers กับ deniedMcpServers คัดกรอง server ที่ผู้ใช้ตั้งเอง
Platformmanaged-mcp.json
macOS/Library/Application Support/ClaudeCode/managed-mcp.json
Linux and WSL/etc/claude-code/managed-mcp.json
WindowsC:\Program Files\ClaudeCode\managed-mcp.json

allowlist ที่อนุญาตแค่ currency ของ demo-projects/cafe-site เขียนด้วย serverCommand แล้วใส่ใน managed settings คู่กับ allowManagedMcpServersOnly: true ซึ่งกันไม่ให้ allowlist ใน settings ของผู้ใช้เพิ่ม server เข้ามาได้อีก

managed-settings.json
{
  "allowManagedMcpServersOnly": true,
  "allowedMcpServers": [
    { "serverCommand": ["uvx", "--from", "currency-mcp==1.4.0", "currency-mcp"] }
  ]
}

serverCommand ต้องตรงทุก argument ตามลำดับ เลขเวอร์ชันก็ต้องตรง อย่าใช้ serverName เพราะชื่อเป็นป้ายที่ใครเขียน .mcp.json ก็ตั้งได้ และ allowlist แค่กรอง server ไม่ได้เป็นทะเบียนว่ามี server อะไรบ้าง รายการที่บอกว่าแต่ละ server มีเจ้าของคือใคร ใช้ทำอะไร เวอร์ชันไหน ต้องเก็บไว้ที่อื่น

Try It in Claude Code

  • เปิด claude ในโปรเจกต์ที่มี .mcp.json
  • ล้างการอนุมัติ

Read Before Approving

copy demo-projects/cafe-site ไปไว้นอกโฟลเดอร์ cafe-mcp แล้วเปิด claude ในนั้น

bash
cp -r demo-projects/cafe-site /tmp/cafe-site
cd /tmp/cafe-site
claude

หน้าอนุมัติแสดงแค่ชื่อ cafe กับ currency แบบเดียวกับที่เห็นในบท Run Tool Attacks ไม่มีคำสั่งให้ดู ผลของ inventory.py เลยเป็นที่เดียวที่เห็นว่า currency จะรัน uvx --from currency-mcp==1.4.0 ไม่ต้องเปิดใช้ตัวไหนเลย (กด Esc) เพราะ server ในตัวอย่างไม่ได้มีไว้รันจริง ดูเสร็จแล้ว cd กลับไปที่ cafe-mcp แล้วลบด้วย rm -r /tmp/cafe-site

Reset Choices

ถ้าตอบไปแล้วอยากให้ถามใหม่

bash
claude mcp reset-project-choices

Pitfalls

  • inventory.py อ่านแค่ .mcp.json server ใน ~/.claude.json และไฟล์ managed ไม่อยู่ในรายการ ดูต่อด้วย claude mcp list หรือ /mcp ในแต่ละโปรเจกต์
  • ชื่อ server เป็นป้ายที่คนเขียนไฟล์ตั้ง server ชื่อ cafe อาจชี้ไป URL ข้างนอกก็ได้ ดูคอลัมน์คำสั่งหรือ URL แทนชื่อ
  • PIN_PATTERN นับตัวเลขหลัง @ หรือ == เป็นการล็อกทั้งหมด some-mcp-server@1 ที่ล็อกแค่ major ก็ผ่าน
  • args ถูกพิมพ์ตามที่เขียน ถ้า server รับ token ทาง argument (--api-key ...) ค่าจะโผล่ใน output ด้วย อ่านก่อนส่งให้คนอื่น และย้าย token ไปไว้ใน env เพราะใครก็เห็น argument ของ process ได้จาก ps
  • lsof กับ curl หาได้แค่ server ที่เปิด port ส่วน server แบบ stdio ไม่เปิด port ต้องหาจาก .mcp.json กับรายการ process
  • serverCommand ไม่ได้เทียบ env ถ้าต้องคุม env ด้วย ให้นิยาม server ไว้ใน managed-mcp.json เลย

Summary

inventory.py เจอสี่ server จากสามโปรเจกต์ ขึ้น FLOATING ที่ notes-search และไม่พิมพ์ค่า secret ออกมา (เทสต์ Fail ทันทีที่พิมพ์) lsof กับ curl เจอ server ที่ 127.0.0.1:8765 ซึ่งตอบ 401 ที่ /mcp และถ้าต้องคุมทั้งองค์กร Claude Code มี managed-mcp.json กับ allowlist ที่เทียบด้วย serverCommand

จบคอร์สนี้ cafe-mcp มี token กับ scope ที่ทางเข้า HTTP, Host กับ Origin ที่ระบุเอง, การ review กับ pin tool ของคนอื่น, sandbox, การเรียกโปรแกรมโดยไม่ผ่าน shell, audit log, lock ของ dependency และ inventory ของ server แล้วครับ ตาราง OWASP MCP Top 10 ที่บอกว่าแต่ละข้ออยู่บทไหนอยู่ในบท Set Up the Security Lab

References

Copyright © 2026