---
title: "Confirm Actions with Elicitation"
description: "ถ้า AI สั่งยกเลิกออร์เดอร์ผิดจะทำยังไง เพิ่ม tool ที่แก้ข้อมูล แล้วให้ server ถามเรายืนยันก่อนยกเลิกทุกครั้ง"
canonical_url: "https://iamthana.com/courses/mcp-server/orders"
---

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

`list_menu` แค่อ่านข้อมูล ถ้า AI เรียกผิดก็ไม่มีอะไรเสียหายครับ ต่อไปเป็น tool ที่แก้ข้อมูล คือ `create_order` สร้างออร์เดอร์ กับ `cancel_order` ยกเลิกออร์เดอร์

จบบทนี้เราจะสั่งให้ Claude Code ยกเลิกออร์เดอร์ แล้ว server จะขึ้นฟอร์มถามเราก่อนทุกครั้ง

ทุกคำสั่งรันในโฟลเดอร์ `cafe-mcp` เดิม ถ้า `http_server.py` จากบท [Intercept Requests and Responses](https://iamthana.com/courses/mcp-server/inspect-traffic) ยังรันค้างอยู่ให้หยุดก่อน เพราะมันยังใช้โค้ดเก่า

## What Is Elicitation

AI เรียก tool เองได้ ถ้ามันเลือกเลขออร์เดอร์ผิด ออร์เดอร์ของลูกค้าอีกคนก็จะโดนยกเลิกไปด้วย การยกเลิกเลยควรให้คนกดยืนยันก่อน

การที่ server ถามผู้ใช้ระหว่างที่ tool ทำงานเรียกว่า elicitation ผู้ใช้ตอบได้ 3 แบบ คือ `accept` (ตอบมาพร้อมข้อมูล), `decline` (ปฏิเสธ) และ `cancel` (ปิดหน้าต่างทิ้งโดยไม่ตอบ)

แบบ `2026-07-28` ให้ server ถามผู้ใช้ผ่าน result ที่มี `resultType: "input_required"` แล้วรอ request ซ้ำจาก client (ดู [Server-to-Client Requests](https://iamthana.com/courses/mcp-server/version-history))

`cancel_order` ทำงานตามนี้

<steps level="3">

### Tool Call

client เรียก `tools/call` ของ `cancel_order` ด้วย `order_id`

### Input Request

server ยังไม่ยกเลิก แต่ตอบ result ที่มี `resultType: "input_required"` พร้อมคำถามใน `inputRequests` และ `requestState` ที่ client ต้องเก็บไว้

### User Prompt

client โชว์คำถามให้ผู้ใช้ แล้วเก็บคำตอบ

### Repeated Request

client ส่ง `tools/call` เดิมซ้ำ แนบ `inputResponses` (คำตอบ) กับ `requestState` (ค่าที่ server ให้มา) กลับไป

### Final Result

คราวนี้ server มีคำตอบแล้ว tool ทำงานจนจบ และตอบ `resultType: "complete"`

</steps>

ฝั่ง server ไม่มีอะไรค้างอยู่ระหว่างสอง request ทุกอย่างที่ต้องจำอยู่ใน `requestState`

## Write the Code

โค้ดทั้งหมดอยู่ใน `cafe_server.py` เดิม `list_menu` จากบท [Build Your First Tool](https://iamthana.com/courses/mcp-server/first-tool) ไม่ต้องแก้ แค่เพิ่ม

- Imports ชุดใหม่
- Models กับ `load_order` ที่อ่านออร์เดอร์จาก Database
- `create_order`
- `cancel_order` กับฟังก์ชันที่สร้างคำถามยืนยัน

### 1. Imports

แทนที่ import ชุดบนสุดของไฟล์ด้วยชุดนี้

```python [cafe_server.py]tangle=imports
from typing import Annotated, TypedDict

from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolve
from mcp.server.mcpserver.exceptions import ToolError
from pydantic import BaseModel

from database import connect
```

### 2. Models and a Loader

เพิ่มต่อจาก `list_menu` (ก่อนบล็อก `if __name__`)

```python [cafe_server.py]tangle=before-main
class OrderItem(BaseModel):
    menu: str
    size: str
    quantity: int


class Order(TypedDict):
    id: int
    customer: str
    status: str
    total_thb: int
    items: list[OrderItem]


class Confirmation(BaseModel):
    confirm: bool


def load_order(order_id: int) -> Order | None:
    with connect() as db:
        row = db.execute("SELECT id, customer, status, total_thb FROM orders WHERE id = ?", (order_id,)).fetchone()
        if row is None:
            return None
        items = db.execute("SELECT menu, size, quantity FROM order_items WHERE order_id = ?", (order_id,)).fetchall()
    return {**dict(row), "items": [OrderItem(**dict(item)) for item in items]}
```

- `OrderItem` เป็น input หนึ่งรายการของออร์เดอร์ SDK แปลงเป็น `inputSchema` ให้เหมือน type hints ในบท [Build Your First Tool](https://iamthana.com/courses/mcp-server/first-tool)
- `Confirmation` เป็นหน้าตาของคำตอบที่ server ขอจากผู้ใช้ มี field เดียวคือ `confirm` (elicitation รับ schema แบบ field เรียบ ๆ เท่านั้น เช่น string, ตัวเลข, boolean)
- ทุก query ใน `load_order` ใช้ `?` placeholder (เขียน `?` ไว้ใน query แล้วส่งค่าแยกต่างหาก) ค่าที่ส่งแยกจะถูกใช้เป็นข้อมูลเสมอ ไม่ถูกรันเป็นคำสั่ง `order_id` ตรงนี้เป็น `int` อยู่แล้ว แต่ `create_order` ข้างล่างรับชื่อเมนูที่เป็นข้อความจาก AI ถ้าต่อ string เอง ข้อความนั้นอาจมีคำสั่ง SQL ปนมาแล้วถูกรันไปด้วย

### 3. create_order

เพิ่มต่อจาก `load_order` (ก่อนบล็อก `if __name__` เหมือนเดิม)

```python [cafe_server.py]tangle=before-main
@mcp.tool()
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."""
    if not items or not customer_name.strip():
        raise ToolError("An order needs a customer name and at least one item.")
    total = 0
    with connect() as db:
        for item in items:
            menu = db.execute("SELECT price_thb, available FROM menu WHERE name = ?", (item.menu,)).fetchone()
            size = db.execute("SELECT 1 FROM recipes WHERE menu = ? AND size = ?", (item.menu, item.size)).fetchone()
            if menu is None or not menu["available"] or size is None or item.quantity < 1:
                raise ToolError(f"Cannot order {item.quantity} x {item.menu} size {item.size}: check list_menu first.")
            total += menu["price_thb"] * item.quantity
        cursor = db.execute(
            "INSERT INTO orders (customer, status, total_thb, order_date) VALUES (?, 'open', ?, date('now'))",
            (customer_name, total),
        )
        db.executemany(
            "INSERT INTO order_items VALUES (?, ?, ?, ?)",
            [(cursor.lastrowid, item.menu, item.size, item.quantity) for item in items],
        )
    return load_order(cursor.lastrowid)
```

ลำดับในฟังก์ชันคือ ตรวจทุกรายการก่อน แล้วค่อยเขียน ถ้ารายการไหนไม่ผ่านจะ `raise ToolError` ก่อนถึงบรรทัด `INSERT` ออร์เดอร์เลยไม่ถูกสร้างครึ่งเดียว

ราคารวมคำนวณจากราคาใน Database เอง AI ไม่ได้ส่งราคามา เลยกำหนดราคาเองไม่ได้

`ToolError` ทำให้ client ได้ result ที่ `isError: true` พร้อมข้อความที่ AI อ่านแล้วแก้ input ได้

### 4. cancel_order

เพิ่มต่อจาก `create_order`

```python [cafe_server.py]tangle=before-main
def ask_cancel_confirmation(order_id: int) -> Elicit[Confirmation]:
    order = load_order(order_id)
    if order is None:
        raise ToolError(f"Order {order_id} not found.")
    return Elicit(f"Cancel order {order_id} for {order['customer']} ({order['total_thb']} THB)?", Confirmation)


@mcp.tool()
def cancel_order(
    order_id: int,
    answer: Annotated[ElicitationResult[Confirmation], Resolve(ask_cancel_confirmation)],
) -> str:
    """Cancel an order after the user confirms."""
    if not isinstance(answer, AcceptedElicitation) or not answer.data.confirm:
        return f"Order {order_id} was not cancelled."
    with connect() as db:
        db.execute("UPDATE orders SET status = 'cancelled' WHERE id = ?", (order_id,))
    return f"Order {order_id} cancelled."
```

`cancel_order` ต่างจาก tool ปกติ 3 จุด

- `ask_cancel_confirmation` คือฟังก์ชันที่ประกาศว่า "ต้องถามอะไร" มันอ่านออร์เดอร์จาก Database ใส่ชื่อลูกค้ากับยอดในคำถาม แล้วคืน `Elicit` ที่มีข้อความถามกับหน้าตาของคำตอบ (`Confirmation`) ผู้ใช้เลยเห็นว่ากำลังจะยกเลิกอะไร ถ้าไม่มีออร์เดอร์ก็ error ตั้งแต่ตรงนี้ ไม่ต้องถามอะไร
- `answer: Annotated[ElicitationResult[Confirmation], Resolve(...)]` บอก SDK ว่า `answer` คือคำตอบของผู้ใช้ SDK เลยไม่ใส่ไว้ใน `inputSchema` (AI เห็นแค่ `order_id`)
- body ของ tool รันเมื่อมีคำตอบแล้วเท่านั้น ถ้ายังไม่มี SDK จะตอบ `input_required` เองโดยไม่เข้า body เลย

ใน body ยกเลิกเฉพาะตอนที่ผู้ใช้ `accept` (คำตอบเป็น `AcceptedElicitation`) และติ๊ก `confirm` เป็นจริง ผู้ใช้ `decline`, `cancel` หรือตอบ `confirm: false` ได้ข้อความ `was not cancelled` ทั้งหมด

<note>

method `ctx.elicit()` ที่เห็นในตัวอย่างเก่า ๆ ใช้ไม่ได้ในโหมด `2026-07-28` บน SDK 2.3.0 มันพยายามส่งคำถามกลับไปหา client กลางทางแล้วขึ้น error ว่าไม่มีช่องทางกลับ (no back-channel) ใช้ `Resolve` แทน

</note>

## Test with curl

ทดสอบ 2 ชั้น ชั้นแรกเรียกใน process เดียวกันด้วย `Client` ชั้นที่สองส่ง HTTP ด้วย curl ให้เห็นข้อความดิบของ `input_required`

### In-Process Client

สร้างไฟล์ `try_orders.py`

```python [try_orders.py]
import asyncio

from mcp import Client
from mcp_types import ElicitResult

from cafe_server import mcp


def answer(action: str):
    async def callback(context, params):
        print(f"server asks: {params.message} -> user says {action}")
        return ElicitResult(action=action, content={"confirm": True} if action == "accept" else None)

    return callback


async def main() -> None:
    async with Client(mcp) as client:
        tools = await client.list_tools()
        print("tools:", [tool.name for tool in tools.tools])

        order = {"items": [{"menu": "iced latte", "size": "M", "quantity": 2}], "customer_name": "Somchai"}
        result = await client.call_tool("create_order", order)
        print("created:", result.structured_content)

        for menu in ("mocha", "thai tea"):
            bad = {"items": [{"menu": menu, "size": "M", "quantity": 1}], "customer_name": "Somchai"}
            result = await client.call_tool("create_order", bad)
            print(f"{menu}: is_error={result.is_error}", result.content[0].text)

    for action in ("accept", "decline"):
        async with Client(mcp, elicitation_callback=answer(action)) as client:
            result = await client.call_tool("cancel_order", {"order_id": 1})
            print(f"{action}:", result.content[0].text)


asyncio.run(main())
```

`mcp_types` ติดตั้งมากับ `mcp` อยู่แล้ว ส่วน `elicitation_callback` คือฟังก์ชันที่ทำหน้าที่แทนผู้ใช้

ตอน server ถาม SDK ฝั่ง client จะเรียกฟังก์ชันนี้ ในแอปอย่าง Claude Code ตรงนี้คือหน้าต่างถามผู้ใช้

ลบ `cafe.db` ก่อนเพื่อให้ได้ข้อมูลตั้งต้นชุดเดียวกับในบทนี้ แล้วรัน (`2>/dev/null` ซ่อน log ของ SDK ที่พิมพ์ทุกครั้งที่ tool ตอบ error)

```bash
rm -f cafe.db
uv run python try_orders.py 2>/dev/null
```

```text [$ uv run python try_orders.py]
tools: ['list_menu', 'create_order', 'cancel_order']
created: {'id': 3, 'customer': 'Somchai', 'status': 'open', 'total_thb': 130, 'items': [{'menu': 'iced latte', 'size': 'M', 'quantity': 2}]}
mocha: is_error=True Error executing tool create_order: Cannot order 1 x mocha size M: check list_menu first.
thai tea: is_error=True Error executing tool create_order: Cannot order 1 x thai tea size M: check list_menu first.
server asks: Cancel order 1 for Malee (125 THB)? -> user says accept
accept: Order 1 cancelled.
server asks: Cancel order 1 for Malee (125 THB)? -> user says decline
decline: Order 1 was not cancelled.
```

ออร์เดอร์ใหม่ได้ `id` 3 เพราะข้อมูลตั้งต้นมี 2 ออร์เดอร์อยู่แล้ว ส่วนยอด 130 บาทมาจากไอซ์ลาเต้ 65 × 2

### curl over HTTP

รอบ `accept` เมื่อกี้ยกเลิกออร์เดอร์ 1 ใน `cafe.db` ไปแล้ว เลยลบ Database อีกรอบ

แล้วเปิด server แบบ HTTP ในอีก terminal (`cd` เข้า `cafe-mcp` ก่อน) เหมือนบท [Intercept Requests and Responses](https://iamthana.com/courses/mcp-server/inspect-traffic)

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

กลับมาที่หน้าต่างเดิม ใช้ตัวแปร `URL` กับ `META` ชุดเดิมจากบท [Intercept Requests and Responses](https://iamthana.com/courses/mcp-server/inspect-traffic)

แต่ `META` ต้องเพิ่ม `"elicitation":{}` ใน `clientCapabilities` เพราะ client ต้องประกาศก่อนว่าถามผู้ใช้ได้ server ถึงจะส่งคำถามมา

```bash
URL=http://127.0.0.1:8765/mcp
META='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{"elicitation":{}}}'
```

#### Create an Order

```bash
curl -s $URL \
  -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: create_order' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"create_order\",\"arguments\":{\"customer_name\":\"Somchai\",\"items\":[{\"menu\":\"latte\",\"size\":\"M\",\"quantity\":2}]},$META}}" \
  | python3 -m json.tool
```

```json [$ curl -s $URL -H 'Mcp-Name: create_order']
{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "content": [
            {
                "text": "{\n  \"id\": 3,\n  \"customer\": \"Somchai\",\n  \"status\": \"open\",\n  \"total_thb\": 120,\n  \"items\": [\n    {\n      \"menu\": \"latte\",\n      \"size\": \"M\",\n      \"quantity\": 2\n    }\n  ]\n}",
                "type": "text"
            }
        ],
        "isError": false,
        "resultType": "complete",
        "structuredContent": {
            "id": 3,
            "customer": "Somchai",
            "status": "open",
            "total_thb": 120,
            "items": [
                {
                    "menu": "latte",
                    "size": "M",
                    "quantity": 2
                }
            ]
        },
        "_meta": {
            "io.modelcontextprotocol/serverInfo": {
                "name": "cafe",
                "version": ""
            }
        }
    }
}
```

ถ้าสั่งชาไทย (เมนูที่ `available = 0`) ด้วย request เดียวกัน เปลี่ยนเป็น `"menu":"thai tea"` กับ `"quantity":1` จะได้ result ที่ `isError` เป็น `true` กับข้อความเดียวกับที่ `try_orders.py` พิมพ์

HTTP status เป็น 200 เพราะ request ถูกรูปแบบ ส่วนที่บอกว่า tool Fail คือ `isError` AI อ่านข้อความแล้วเลือกเมนูใหม่หรือแจ้งผู้ใช้ได้

#### First Request: input_required

เรียก `cancel_order` ของออร์เดอร์ที่เพิ่งสร้าง (เก็บ response ไว้ในตัวแปร `FIRST` เพราะต้องหยิบ `requestState` ไปใช้ต่อ)

```bash
FIRST=$(curl -s $URL \
  -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: cancel_order' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_order\",\"arguments\":{\"order_id\":3},$META}}")
echo "$FIRST" | python3 -m json.tool
```

```json [$ curl -s $URL -H 'Mcp-Name: cancel_order']
{
    "jsonrpc": "2.0",
    "id": 3,
    "result": {
        "inputRequests": {
            "cafe_server:ask_cancel_confirmation": {
                "method": "elicitation/create",
                "params": {
                    "message": "Cancel order 3 for Somchai (120 THB)?",
                    "mode": "form",
                    "requestedSchema": {
                        "properties": {
                            "confirm": {
                                "title": "Confirm",
                                "type": "boolean"
                            }
                        },
                        "required": [
                            "confirm"
                        ],
                        "type": "object"
                    }
                }
            }
        },
        "requestState": "v1.A9O3LGVkpiZ-5Au0JBH-LnoTvyfGEuJnCzBxfOfbuI...",
        "resultType": "input_required",
        "_meta": {
            "io.modelcontextprotocol/serverInfo": {
                "name": "cafe",
                "version": ""
            }
        }
    }
}
```

(`requestState` ตัดให้สั้น ค่าจริงยาวกว่านี้มาก)

ยังไม่มีอะไรถูกยกเลิก server ส่งคำถามยืนยันกลับมาแทน

ใน `inputRequests` แต่ละคำถามมี key ของตัวเอง (`cafe_server:ask_cancel_confirmation`) ตอนตอบกลับต้องใช้ key นี้ ส่วน `requestedSchema` บอกว่าคำตอบต้องมี field อะไร

#### Second Request: The Answer

ดึง `requestState` ออกมา แล้วส่ง request เดิมซ้ำ เพิ่ม `inputResponses` กับ `requestState`

ลองตอบปฏิเสธก่อน

```bash
STATE=$(echo "$FIRST" | python3 -c 'import json,sys; print(json.load(sys.stdin)["result"]["requestState"])')
KEY=cafe_server:ask_cancel_confirmation

curl -s $URL \
  -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: cancel_order' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_order\",\"arguments\":{\"order_id\":3},\"inputResponses\":{\"$KEY\":{\"action\":\"decline\"}},\"requestState\":\"$STATE\",$META}}" \
  | python3 -m json.tool
```

ได้ `resultType: "complete"` กับข้อความ `Order 3 was not cancelled.` ทีนี้ใช้ `$STATE` ก้อนเดิม (`requestState` ใช้ซ้ำได้จนกว่าจะหมดอายุ) เปลี่ยนคำตอบเป็น `accept` พร้อม `"content":{"confirm":true}`

```bash
curl -s $URL \
  -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: cancel_order' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_order\",\"arguments\":{\"order_id\":3},\"inputResponses\":{\"$KEY\":{\"action\":\"accept\",\"content\":{\"confirm\":true}}},\"requestState\":\"$STATE\",$META}}" \
  | python3 -m json.tool
```

```json [$ curl -s $URL -H 'Mcp-Name: cancel_order' (accept)]
{
    "jsonrpc": "2.0",
    "id": 5,
    "result": {
        "content": [
            {
                "text": "Order 3 cancelled.",
                "type": "text"
            }
        ],
        "isError": false,
        "resultType": "complete",
        "structuredContent": {
            "result": "Order 3 cancelled."
        },
        "_meta": {
            "io.modelcontextprotocol/serverInfo": {
                "name": "cafe",
                "version": ""
            }
        }
    }
}
```

#### Client Without Elicitation

ลองเรียกด้วย `_meta` ที่ `clientCapabilities` เป็น `{}` (ไม่ประกาศว่าตอบคำถามผู้ใช้ได้)

```bash
NOCAP='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}'

curl -s -w '\nHTTP %{http_code}\n' $URL \
  -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: cancel_order' \
  -d "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_order\",\"arguments\":{\"order_id\":1},$NOCAP}}"
```

```json [$ curl -s -w '\nHTTP %{http_code}\n' $URL (clientCapabilities: {})][$ curl -s -w '\nHTTP %\n' $URL (clientCapabilities: {})]
{"jsonrpc":"2.0","id":6,"error":{"code":-32021,"message":"Client did not declare the form elicitation capability required by resolver 'cafe_server:ask_cancel_confirmation'","data":{"requiredCapabilities":{"elicitation":{"form":{}}}}}}
HTTP 400
```

server ไม่ส่งคำถามไปให้ client ที่ตอบไม่ได้ ตอบ error `-32021` บอกว่าขาด capability อะไร และ tool ไม่ทำงาน

## Try It in Claude Code

ใช้ server `cafe` แบบ stdio ที่ตั้งไว้ในบท [Build Your First Tool](https://iamthana.com/courses/mcp-server/first-tool) ได้เลย แต่ Claude Code เปิด server ไว้ตั้งแต่ตอนเริ่ม ต้องให้มันโหลดโค้ดใหม่ก่อน

<steps level="3">

### Reload the Server

ปิด `http_server.py` (Ctrl+C) แล้วลบ `cafe.db` อีกรอบด้วย `rm -f cafe.db` เลขออร์เดอร์จะเริ่มที่ 3 เหมือนในภาพ

จากนั้นออกจาก Claude Code (`/exit`) แล้วเปิด `claude` ใหม่ในโฟลเดอร์ `cafe-mcp` พิมพ์ `/mcp` ดู `cafe` ต้องขึ้น connected และมี 3 tools

![หน้า /mcp ของ Claude Code เลือก cafe แสดงสถานะ connected, Protocol 2026-07-28 และ Tools 3 tools](https://iamthana.com/images/courses/mcp-server/claude-orders-mcp-tools.webp)

### Ask for an Order

```text
สั่งลาเต้ไซส์ M 2 แก้วให้คุณสมชาย
```

Claude Code เรียก `list_menu` ก่อน แล้วเรียก `create_order` ด้วยชื่อลูกค้า `สมชาย` ได้ออร์เดอร์ยอด 120 บาท (ในโหมดปกติ Claude Code จะถามสิทธิ์ก่อนเรียกแต่ละ tool กดอนุญาต)

![Claude Code เรียก create_order ด้วย items ลาเต้ไซส์ M จำนวน 2 และชื่อลูกค้า สมชาย ได้ผลลัพธ์ id 3, status open, total_thb 120 แล้ว Claude ตอบเป็นภาษาไทยว่าออร์เดอร์ #3 ยอด 120 บาท](https://iamthana.com/images/courses/mcp-server/claude-create-order.webp)

### Ask It to Cancel

```text
ยกเลิกออร์เดอร์ที่เพิ่งสั่ง
```

Claude Code เรียก `cancel_order` ด้วย `order_id: 3` แล้วขึ้นฟอร์มจาก server ที่บอกชื่อลูกค้ากับยอดเงิน (`Cancel order 3 for สมชาย (120 THB)?`) กด Space เพื่อติ๊ก Confirm เลือก Accept แล้วกด Enter

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

### Result

หลังกด Accept `cancel_order` ได้ `Order 3 cancelled.` และ Claude แจ้งผู้ใช้ว่ายกเลิกแล้ว

![ผลลัพธ์ของ cancel_order เป็น {"result": "Order 3 cancelled."} และ Claude ยืนยันการยกเลิกเป็นภาษาไทย](https://iamthana.com/images/courses/mcp-server/claude-cancel-order-done.webp)

</steps>

## Pitfalls

- MCP Inspector CLI 2.16.0 เรียก `cancel_order` ไม่ได้ ข้อความ error ตรงกับ `-32021` (CLI พิมพ์ code เป็น `"error"`) เพราะ CLI ไม่ประกาศ capability นี้และไม่มี option ให้เปิด ใช้ curl หรือ client ที่ตอบคำถามได้
- `requestState` ต้องส่งกลับทั้งก้อนโดยไม่แก้ ถ้าส่งแต่ `inputResponses` จะได้ `input_required` ก้อนใหม่ ไม่มีอะไรถูกยกเลิก
- `cancel_order` ในบทนี้ยกเลิกได้ทุกออร์เดอร์ รวมออร์เดอร์ที่ `completed` แล้ว (ออร์เดอร์ 1 ในข้อมูลตั้งต้นเป็น `completed` แต่ตอนทดสอบด้วย `try_orders.py` ก็ถูกยกเลิกได้) ถ้าเอาไปใช้ให้เช็ก `status` ใน `ask_cancel_confirmation` ก่อนถาม

## Summary

`create_order` ตรวจเมนู สถานะ ขนาด และจำนวนก่อนเขียน และคำนวณยอดจาก Database เอง ส่วน `cancel_order` ใช้ `Resolve` ให้ server ถามผู้ใช้ก่อนยกเลิก

ตอนนี้ AI จะรู้ข้อมูลอะไรก็ต้องเรียก tool อย่างเดียว บทหน้า [Expose Data with Resources](https://iamthana.com/courses/mcp-server/resources) เปิดเมนู ออร์เดอร์ และสูตรเครื่องดื่มให้เราแนบเข้าไปในแชทได้เลย ไม่ต้องรอ AI เรียก tool ครับ

## References

- [Elicitation (spec 2026-07-28)](https://modelcontextprotocol.io/specification/2026-07-28/client/elicitation)
- [Changelog 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/changelog)
- [Understanding MCP servers: Tools](https://modelcontextprotocol.io/docs/2026-07-28/learn/server-concepts#tools)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)

## Sitemap

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