---
title: "Limit Tools by Scope"
description: "ให้ tool ที่แก้ข้อมูลเช็ก scope orders:write ก่อนทำงาน viewer ยกเลิกออร์เดอร์ไม่ได้และไม่เห็นคำถามยืนยันด้วย ทดสอบด้วย curl, pytest และ Claude Code"
canonical_url: "https://iamthana.com/courses/mcp-security/scopes"
---

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

บทที่แล้วทุก request ต้องมี token แล้ว แต่ยังมีช่องเหลืออยู่ครับ viewer ที่มีแค่ `orders:read` ยังเรียก `create_order` กับ `cancel_order` ได้ บทนี้ปิดช่องนั้น

เริ่มจากโฟลเดอร์ `cafe-mcp` ตอนจบบท [Require a Token](https://iamthana.com/courses/mcp-security/auth) ที่มี `auth.py`, `tokens.env` และ `cafe-auth` ใน `.mcp.json`

## What Scopes Do

บทนี้ใช้ scope สองตัว คือ `orders:read` สำหรับอ่าน กับ `orders:write` สำหรับ tool ที่แก้ข้อมูล

<table>
<thead>
  <tr>
    <th>
      Operation
    </th>
    
    <th>
      Needs
    </th>
    
    <th>
      Checked By
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      ทุก request ที่ <code>
        /mcp
      </code>
      
       ได้แก่ <code>
        list_menu
      </code>
      
      , resource, prompt และ completion
    </td>
    
    <td>
      <code>
        orders:read
      </code>
    </td>
    
    <td>
      SDK ที่ endpoint
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        create_order
      </code>
    </td>
    
    <td>
      <code>
        orders:write
      </code>
    </td>
    
    <td>
      <code>
        require_scope
      </code>
      
       ใน tool
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        cancel_order
      </code>
    </td>
    
    <td>
      <code>
        orders:write
      </code>
    </td>
    
    <td>
      <code>
        require_scope
      </code>
      
       ใน resolver ที่ถามยืนยัน
    </td>
  </tr>
</tbody>
</table>

`orders:write` ไม่ได้รวม `orders:read` ไว้ในตัว token ของ staff เลยต้องมีทั้งสองตัว

## Write the Code

- `require_scope` ใน `auth.py`
- เพิ่มการตรวจ scope ใน `cafe_server.py`

### 1. require_scope

`require_scope` เขียนไว้ใน `auth.py` ตั้งแต่บทที่แล้ว บทนี้เริ่มเรียกใช้

- อ่าน token ของ request ที่กำลังทำงานด้วย `get_access_token()` ถ้าไม่มี token (รันแบบ stdio หรือเรียกผ่าน `Client(mcp)` ในเทสต์) จะปล่อยผ่าน เพราะทาง HTTP ทุก request ต้องผ่าน endpoint ที่ตรวจ token มาก่อนแล้ว
- ถ้า token ไม่มี scope ที่ขอ จะ raise `ToolError` ซึ่ง SDK ส่งกลับเป็นผลของ tool ที่ `isError: true`

### 2. Scope Checks in cafe_server.py

เพิ่มบรรทัด `require_scope` ใน `create_order` กับ `ask_cancel_confirmation` (import ใส่ไว้แล้วในบท [Require a Token](https://iamthana.com/courses/mcp-security/auth))

```diff [cafe_server.py]
def create_order(items: list[OrderItem], customer_name: str) -> Order:
     """Create an order for a customer. Each item needs a menu name, a size (S, M or L) and a quantity."""
+    require_scope("orders:write")
     if not items or not customer_name.strip():
```

```diff [cafe_server.py]
def ask_cancel_confirmation(order_id: int) -> Elicit[Confirmation]:
+    require_scope("orders:write")  # resolvers run before the tool body, so this refuses before any question
     order = load_order(order_id)
```

ทำไมไม่แก้ที่ `cancel_order` ตรง ๆ? เพราะ `ask_cancel_confirmation` เป็น resolver ที่ SDK เรียกก่อนเข้า body ของ tool ถ้าเช็กใน body viewer จะได้เห็นคำถามยืนยันก่อนแล้วค่อยโดนปฏิเสธ เช็กที่ resolver เลยปฏิเสธได้ก่อนมีคำถามเกิดขึ้น

## Test with curl

- viewer ลองสร้างและยกเลิก
- staff ลองยกเลิก
- เอาคำตอบของคนอื่นมาใช้

### Start the Server

หยุด server ของบทที่แล้ว (`Ctrl+C`) ลบ `cafe.db` แล้วรันใหม่ด้วยคำสั่งเดิม server จะได้โหลดโค้ดที่มี `require_scope` และเลขออร์เดอร์เริ่มนับจากข้อมูลตั้งต้น

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

หน้าต่าง curl ใช้ `URL`, `META` กับ `call_tool` ชุดเดิมจากบทที่แล้ว ถ้าปิดไปแล้วให้ตั้งใหม่ตามบท [Require a Token](https://iamthana.com/courses/mcp-security/auth)

### Viewer Token

token ของ viewer มีแค่ `orders:read` ลองสั่ง `create_order` ก่อน แล้วตามด้วย `cancel_order`

```bash
call_tool "$CAFE_VIEWER_TOKEN" create_order '{"customer_name":"Somchai","items":[{"menu":"latte","size":"M","quantity":1}]}'
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}'
```

`create_order` ได้ error `missing scope orders:write` แบบเดียวกับ `cancel_order` ข้างล่าง

```text [$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}'][$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '']
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"Error executing tool cancel_order: This token cannot change orders: missing scope orders:write.","type":"text"}],"isError":true,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

สังเกตว่าไม่มี `input_required` เลย server ปฏิเสธก่อนถามยืนยัน ส่วน HTTP status เป็น `200` เพราะนับเป็นผลของ tool (ทำไมไม่เป็น `403` อยู่ใน Pitfalls)

### Staff Token

```bash
call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":1}' | sed -E 's/"requestState":"[^"]*"/"requestState":"..."/'
```

```text [$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":1}'][$ 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 order 1 for Malee (125 THB)?","mode":"form","requestedSchema":{"properties":{"confirm":{"title":"Confirm","type":"boolean"}},"required":["confirm"],"type":"object"}}}},"requestState":"...","resultType":"input_required","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

staff ผ่าน scope แล้วเจอคำถามยืนยันตามเดิม (`sed` ย่อ `requestState` ให้สั้น)

### Replayed Answers

ถ้า viewer แอบเอา `requestState` ของ staff มาตอบแทนล่ะ? เก็บ state ของ staff สำหรับออร์เดอร์ 2 ไว้ก่อน

```bash
STATE=$(call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":2}' | grep -o '"requestState":"[^"]*"')
ANSWER='"inputResponses":{"cafe_server:ask_cancel_confirmation":{"action":"decline"}}'
```

ส่งคำตอบพร้อม state นั้นด้วย token ของ viewer

```bash
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":2}' "$STATE,$ANSWER,"
```

```text [$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":2}' "$STATE,$ANSWER,"][$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '' "$STATE,$ANSWER,"]
HTTP/1.1 400 Bad Request
{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid or expired requestState","data":{"reason":"invalid_request_state"}}}
```

ส่งด้วย token ของ staff เอง

```bash
call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":2}' "$STATE,$ANSWER,"
```

```text [$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":2}' "$STATE,$ANSWER,"][$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '' "$STATE,$ANSWER,"]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"Order 2 was not cancelled.","type":"text"}],"isError":false,"resultType":"complete","structuredContent":{"result":"Order 2 was not cancelled."},"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

viewer โดนปฏิเสธ ส่วน staff เจ้าของ state ใช้ได้ปกติ เพราะ SDK ผูก `requestState` ไว้กับ 3 อย่าง

- เจ้าของ token (`client_id`) log ของ server เขียนว่า `rejected ... principal`
- ชื่อ method กับ arguments state ของออร์เดอร์ 2 เอาไปใช้กับออร์เดอร์ 1 ไม่ได้
- เวลา หมดอายุใน 600 วินาที

แล้วถ้าส่งคำตอบ `accept` มาเลยโดยไม่มี state? ลองสามแบบ

```bash
ACCEPT='"inputResponses":{"cafe_server:ask_cancel_confirmation":{"action":"accept","content":{"confirm":true}}}'
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}' "$ACCEPT,"
```

```text [$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}' "$ACCEPT,"][$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '' "$ACCEPT,"]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"content":[{"text":"Error executing tool cancel_order: This token cannot change orders: missing scope orders:write.","type":"text"}],"isError":true,"resultType":"complete","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

resolver ทำงานทุกรอบ รวมทั้งรอบที่ส่งคำตอบมา viewer เลยโดน `require_scope` ปฏิเสธเหมือนเดิม

```bash
call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}' "\"requestState\":\"garbage\",$ACCEPT,"
```

```text [$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '{"order_id":1}' ""requestState":"garbage",$ACCEPT,"][$ call_tool "$CAFE_VIEWER_TOKEN" cancel_order '' ""requestState":"garbage",$ACCEPT,"]
HTTP/1.1 400 Bad Request
{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid or expired requestState","data":{"reason":"invalid_request_state"}}}
```

state ปลอมถูกปฏิเสธก่อนเข้าโค้ดของเรา

```bash
call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":1}' "$ACCEPT," | sed -E 's/"requestState":"[^"]*"/"requestState":"..."/'
```

```text [$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '{"order_id":1}' "$ACCEPT,"][$ call_tool "$CAFE_STAFF_TOKEN" cancel_order '' "$ACCEPT,"]
HTTP/1.1 200 OK
{"jsonrpc":"2.0","id":1,"result":{"inputRequests":{"cafe_server:ask_cancel_confirmation":{"method":"elicitation/create","params":{"message":"Cancel order 1 for Malee (125 THB)?","mode":"form","requestedSchema":{"properties":{"confirm":{"title":"Confirm","type":"boolean"}},"required":["confirm"],"type":"object"}}}},"requestState":"...","resultType":"input_required","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

staff ส่ง `accept` โดยไม่มี state ก็ไม่นับเหมือนกัน server ถามใหม่

### Staff Create

token ของ staff สร้างออร์เดอร์ได้

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

```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  \"items\": [\n    {\n      \"menu\": \"latte\",\n      \"size\": \"M\",\n      \"quantity\": 1\n    }\n  ]\n}","type":"text"}],"isError":false,"resultType":"complete","structuredContent":{"id":3,"customer":"Somchai","status":"open","total_thb":60,"items":[{"menu":"latte","size":"M","quantity":1}]},"_meta":{"io.modelcontextprotocol/serverInfo":{"name":"cafe","version":""}}}}
```

### Database Check

ตรวจว่าการปฏิเสธทั้งหมดไม่ได้เขียนอะไรลง Database

```bash
sqlite3 cafe.db "SELECT id, customer, status FROM orders"
```

```text [$ sqlite3 cafe.db "SELECT id, customer, status FROM orders"]
1|Malee|completed
2|Preecha|completed
3|Somchai|open
```

ออร์เดอร์ 1 กับ 2 สถานะเดิม ออร์เดอร์ 3 เป็นของ staff ไม่มีออร์เดอร์ที่ viewer สร้าง และไม่มีอะไรถูกยกเลิก

## Run the Tests

### test_auth.py

เทสต์ใหม่อยู่ใน `tests/test_auth.py` มีสองแบบ เทสต์ของ tool จำลองว่าใคร login อยู่ ส่วนเทสต์ของ endpoint ส่ง request เข้า app ตรง ๆ

```python [tests/test_auth.py]
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.shared.exceptions import MCPError
from mcp_types import ElicitResult
from starlette.testclient import TestClient

from cafe_server import mcp as cafe

VIEWER_SCOPES = ["orders:read"]
STAFF_SCOPES = ["orders:read", "orders:write"]
ONE_LATTE = {"items": [{"menu": "latte", "size": "M", "quantity": 1}], "customer_name": "Somchai"}


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


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

`sign_in_with` ทำแบบเดียวกับ middleware ของ SDK ตอน token ผ่าน คือใส่ผู้ใช้ลงใน `auth_context_var` ที่ `get_access_token()` อ่าน ส่วน fixture `autouse` ล้างค่าหลังเทสต์แต่ละตัว

เทสต์ของ tool

```python [tests/test_auth.py]tangle=append
async def test_viewer_cannot_create_order():
    sign_in_with(VIEWER_SCOPES)
    async with Client(cafe) as client:
        result = await client.call_tool("create_order", ONE_LATTE)
        assert result.is_error
        assert "missing scope orders:write" in result.content[0].text
        with pytest.raises(MCPError):
            await client.read_resource("cafe://orders/3")


async def test_viewer_cancel_is_refused_before_the_question():
    sign_in_with(VIEWER_SCOPES)
    questions = []

    async def record_question(context, params):
        questions.append(params.message)
        return ElicitResult(action="accept", content={"confirm": True})

    async with Client(cafe, elicitation_callback=record_question) as client:
        result = await client.call_tool("cancel_order", {"order_id": 1})
    assert result.is_error
    assert questions == []


async def test_staff_is_asked_before_cancelling():
    sign_in_with(STAFF_SCOPES)
    questions = []

    async def decline(context, params):
        questions.append(params.message)
        return ElicitResult(action="decline")

    async with Client(cafe, elicitation_callback=decline) as client:
        result = await client.call_tool("cancel_order", {"order_id": 1})
    assert len(questions) == 1
    assert result.content[0].text == "Order 1 was not cancelled."
```

- เทสต์แรกเช็กข้อความ error และว่าออร์เดอร์ 3 ไม่ถูกสร้าง
- เทสต์ที่สอง callback ตอบ `accept` ทุกคำถาม ถ้า viewer หลุดด่านไปได้ ออร์เดอร์จะถูกยกเลิกจริง เทสต์เลยเช็กว่าได้ error และไม่มีคำถามเข้ามาเลย
- เทสต์ที่สามเช็กว่า staff ยังโดนถามก่อนยกเลิก ไม่ได้โดนปฏิเสธไปด้วย

เทสต์ของ endpoint

```python [tests/test_auth.py]tangle=append
@pytest.mark.parametrize(
    "token_variable, expected_status",
    [(None, 401), ("CAFE_NO_SUCH_TOKEN", 401), ("CAFE_FOREIGN_TOKEN", 401), ("CAFE_GUEST_TOKEN", 403), ("CAFE_VIEWER_TOKEN", 200)],
)
def test_endpoint_status_by_token(monkeypatch, token_variable, expected_status):
    for variable in ("CAFE_STAFF_TOKEN", "CAFE_VIEWER_TOKEN", "CAFE_GUEST_TOKEN", "CAFE_FOREIGN_TOKEN"):
        monkeypatch.setenv(variable, f"secret-for-{variable}")
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "tools/list",
    }
    if token_variable:
        headers["Authorization"] = f"Bearer secret-for-{token_variable}"
    body = {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list",
        "params": {"_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": {}}},
    }
    with TestClient(cafe.streamable_http_app(), base_url="http://127.0.0.1:8765") as http:
        response = http.post("/mcp", headers=headers, json=body)
    assert response.status_code == expected_status
```

`TestClient` ของ Starlette ส่ง request เข้า app ได้โดยไม่ต้องเปิด port ส่วน `monkeypatch.setenv` ตั้ง token ปลอมให้ verifier ไม่แตะ `tokens.env` ของเรา ต้องตั้ง `base_url` เป็น `127.0.0.1` ด้วยนะ เพราะ SDK ตรวจ header `Host` ของ server ที่ bind localhost และค่าเริ่มต้นของ `TestClient` (`testserver`) จะโดนปฏิเสธ

### Full Run

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

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

14 ตัวเดิมกับ 8 ตัวใหม่ (ตัวสุดท้ายเป็น parametrize 5 แบบ)

### Break a Check

เอา `require_scope` ออกจาก `ask_cancel_confirmation` (ลบบรรทัดเดียว)

```text [$ uv run pytest -q (require_scope removed from ask_cancel_confirmation)]
.F....................                                                   [100%]
=================================== FAILURES ===================================
______________ test_viewer_cancel_is_refused_before_the_question _______________

    async def test_viewer_cancel_is_refused_before_the_question():
        sign_in_with(VIEWER_SCOPES)
        questions = []
    
        async def record_question(context, params):
            questions.append(params.message)
            return ElicitResult(action="accept", content={"confirm": True})
    
        async with Client(cafe, elicitation_callback=record_question) as client:
            result = await client.call_tool("cancel_order", {"order_id": 1})
>       assert result.is_error
E       AssertionError: assert False
E        +  where False = CallToolResult(meta={'io.modelcontextprotocol/serverInfo': {'name': 'cafe', 'version': ''}}, content=[TextContent(type...tations=None, meta=None)], structured_content={'result': 'Order 1 cancelled.'}, is_error=False, result_type='complete').is_error

tests/test_auth.py:48: AssertionError
=========================== short test summary info ============================
FAILED tests/test_auth.py::test_viewer_cancel_is_refused_before_the_question
1 failed, 21 passed in 0.17s
```

`'Order 1 cancelled.'` คือ viewer ยกเลิกออร์เดอร์ได้สำเร็จ (callback ในเทสต์ตอบ `accept` ให้) ถ้าลบที่ `create_order` ก็จะเห็น `test_viewer_cannot_create_order` Fail แบบเดียวกัน ใส่บรรทัดกลับแล้วรันอีกรอบ

```text [$ uv run pytest -q (restored)]
......................                                                   [100%]
22 passed in 0.13s
```

## Try It in Claude Code

- staff สร้างแล้วยกเลิกออร์เดอร์ผ่าน `cafe-auth`
- เปลี่ยนเป็น token ของ viewer แล้วลองยกเลิก
- ใส่ `cafe` แบบ stdio กลับ

<steps level="3">

### Reset the Data

หยุด server ลบ `cafe.db` แล้วรันใหม่ด้วยคำสั่งเดียวกับหัวข้อ Start the Server ออร์เดอร์ที่ Claude Code สร้างจะได้เลข 3

### Staff Confirm

เปิด `claude` จาก shell ที่ `source tokens.env` แล้ว ถามให้สร้างออร์เดอร์แล้วยกเลิก

```text
สั่งลาเต้ไซส์ M 1 แก้วให้คุณสมชาย แล้วยกเลิกออร์เดอร์นั้น
```

token ของ staff ผ่านทั้งสอง tool `create_order` ได้ออร์เดอร์ 3 ยอด 60 บาท แล้ว `cancel_order` ขึ้นฟอร์มยืนยัน

![Claude Code เรียก cafe-auth cancel_order ด้วย order_id 3 ขึ้นข้อความ Fulfilling input required by tools/call (round 1) แล้วแสดงฟอร์ม MCP server cafe-auth requests your input ถามว่า Cancel order 3 for สมชาย (60 THB)? มีช่อง Confirm และตัวเลือก Accept กับ Decline](https://iamthana.com/images/courses/mcp-security/claude-auth-staff-confirm.webp)

เลือก Accept ผลที่ได้คือ `Order 3 cancelled.`

### Viewer Refusal

ออกจาก Claude Code (`/exit`) แล้วเปลี่ยน server ให้ใช้ token ของ viewer

```bash
claude mcp remove --scope project cafe-auth
claude mcp add-json cafe-auth '{"type":"http","url":"http://127.0.0.1:8765/mcp","headers":{"Authorization":"Bearer ${CAFE_VIEWER_TOKEN}"}}' --scope project
claude
```

Claude Code ไม่ถามอนุมัติ server ซ้ำ เพราะชื่อ `cafe-auth` เป็นชื่อเดิม ถามให้ยกเลิกออร์เดอร์

```text
ยกเลิกออร์เดอร์ 1
```

![Claude Code เรียก cafe-auth cancel_order ด้วย order_id 1 ได้ข้อความสีแดง Error executing tool cancel_order: This token cannot change orders: missing scope orders:write ไม่มีฟอร์มยืนยัน แล้ว Claude ตอบว่าออร์เดอร์ 1 ยังไม่ถูกยกเลิกเพราะ token ไม่มีสิทธิ์ orders:write](https://iamthana.com/images/courses/mcp-security/claude-auth-viewer-refused.webp)

ได้ error เดียวกับที่ curl ได้ และไม่มีฟอร์มยืนยันขึ้นเลย เช็กใน `cafe.db` ออร์เดอร์ 1 ยังเป็น `completed` ส่วนออร์เดอร์ 3 ที่ staff ยกเลิกไปเป็น `cancelled`

### Restore the stdio Server

ถอด `cafe-auth` แล้วใส่ `cafe` แบบ stdio กลับ บทถัดไปใช้ตัวนี้

```bash
claude mcp remove --scope project cafe-auth
claude mcp add --scope project cafe -- uv run --directory "$(pwd)" python cafe_server.py
```

</steps>

## Pitfalls

- spec แนะนำให้ตอบ `403` กับ `scope="..."` เมื่อสิทธิ์ไม่พอ แต่ SDK 2.3.0 ทำได้แค่ระดับ endpoint ทั้งก้อน การปฏิเสธราย tool เลยเป็น `200` กับ `isError: true` client ที่ทำ OAuth เองจะไม่รู้ว่าต้องไปขอ `orders:write` เพิ่ม เห็นแค่ข้อความ error
- `require_scope` ปล่อยผ่านเมื่อไม่มี token ซึ่งปลอดภัยก็ต่อเมื่อทุกทาง HTTP ผ่าน endpoint ที่ตรวจ token ระวัง route ที่เพิ่มด้วย `@mcp.custom_route` ไม่ผ่านการตรวจนี้ ถ้าเรียกโค้ดของ tool จาก route แบบนั้นต้องตรวจ token เอง
- `requestState` ใช้ซ้ำได้จนกว่าจะหมดอายุ ถ้าเป็นคนเดิม `cancel_order` ยกเลิกซ้ำแล้วผลเหมือนเดิมเลยไม่เป็นไร แต่ tool อย่างตัดเงินหรือใช้คูปอง ต้องจดไว้ฝั่ง server ว่า state ไหนใช้ไปแล้ว (spec บังคับ MUST สำหรับกรณีนี้)

## Summary

ตอนนี้ tool ที่แก้ข้อมูลเช็ก `orders:write` แล้วครับ viewer สร้างหรือยกเลิกออร์เดอร์ไม่ได้ ไม่เห็นแม้แต่คำถามยืนยัน และเอาคำตอบที่ค้างของ staff มาใช้แทนก็ไม่ได้ เทสต์ทั้งหมด 22 ตัว

token กับ scope กันคนที่ไม่มีสิทธิ์ได้ แต่ถ้าตัว server ที่เราติดตั้งเป็นฝ่ายเล่นไม่ซื่อเองล่ะ? บทถัดไป [Run Tool Attacks](https://iamthana.com/courses/mcp-security/tool-attacks) ลองติดตั้ง server ที่แอบซ่อนคำสั่งไว้ใน tool

## References

- [Authorization (spec 2026-07-28)](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
- [Multi Round-Trip Requests (spec 2026-07-28)](https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr)
- [OWASP MCP Top 10](https://owasp.org/projects/mcp-top-10)

## Sitemap

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