Lesson 9
Add Stock and Notify Servers
ร้านไม่ได้มีระบบเดียว เพิ่ม server สต็อกกับ server แจ้งเตือนเป็นไฟล์แยก (จำลองโดยบันทึกลง Database ในเครื่อง) พร้อมตรวจและปฏิเสธคำขอผิด ๆ ก่อนถามผู้ใช้
นอกจากออร์เดอร์ ร้านยังต้องดูวัตถุดิบและคอยแจ้งพนักงานด้วยครับ บทนี้เพิ่ม server อีกสองตัวข้าง cafe คือ stock กับ notify
ทั้งสองตัวมี Database ของตัวเอง ไม่แตะ cafe.db
จบบทนี้เราจะมี server สองตัวที่ปฏิเสธคำขอผิด ๆ ได้เอง และถามผู้ใช้ก่อนสั่งของหรือส่งข้อความ บทหน้าค่อยให้ Claude Code ใช้ทั้งสามตัวต่อกัน
ทุกคำสั่งรันในโฟลเดอร์ cafe-mcp ที่ทำค้างไว้จากบทที่แล้ว
Why Split into Multiple Servers
จะใส่ check_stock กับ send_message เพิ่มใน cafe_server.py ตัวเดียวก็ทำได้ แต่บทนี้แยกเป็น server ละชุดข้อมูล คือร้าน สต็อก และแจ้งเตือน เพราะจะถอดหรือเพิ่มตัวไหนก็ไม่ต้องแก้ตัวอื่น
server แต่ละตัวมองไม่เห็นกัน และอ่านบทสนทนาทั้งหมดไม่ได้ เพราะ host สร้าง client แยกให้ทีละตัว (ภาพ architecture ในบท Meet MCP and Set Up)
stock เลยไม่รู้ว่ามี cafe อยู่ และ notify ไม่รู้ว่าข้อความที่ได้รับมาจากไหน ข้อมูลข้ามระหว่าง server ผ่านตัว AI ทั้งหมด AI อ่านผลจาก server หนึ่งแล้วใส่เป็น argument ของอีก server เอง
| Server | Tool | Resource | Data |
|---|---|---|---|
cafe | list_menu, create_order, cancel_order | เมนู ออร์เดอร์ ยอดขาย สูตร | cafe.db |
stock | check_stock, reorder | stock://ingredients/{name} | stock.db |
notify | send_message | notify://channels | notify.db |
send_message ของ notify เขียนข้อความลงตาราง messages ใน notify.db แทนการเรียก API ของแอปแชท ถ้าจะต่อ LINE หรือ Telegram ให้เปลี่ยนบรรทัด INSERT ในฟังก์ชันนั้นเป็นการเรียก API และจัดการกรณีส่งไม่สำเร็จ ส่วนที่เหลือใช้เหมือนเดิม
ถ้าต่อระบบจริง reorder จะสั่งของที่ร้านต้องจ่ายเงิน ส่วน send_message จะส่งข้อความหาคนอื่นที่เรียกคืนไม่ได้ ทั้งสองตัวเลยถามผู้ใช้ยืนยันด้วย elicitation เหมือน cancel_order ในบท Confirm Actions with Elicitation
ก่อนถาม server จะตรวจคำขอ ถ้าทำไม่ได้ก็ปฏิเสธเลย ผู้ใช้จะได้ไม่ต้องตอบคำถามของคำขอที่ทำไม่ได้ การตรวจแบบนี้เรียกว่า guard
ส่วน check_stock กับ resource อ่านอย่างเดียว ไม่ถาม
Write the Code
สร้างไฟล์ใหม่สองไฟล์ในโฟลเดอร์ cafe-mcp ไม่ต้องแก้ cafe_server.py
stock_server.pynotify_server.py
1. Stock Server
import sqlite3
from pathlib import Path
from typing import Annotated, TypedDict
from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolve
from mcp.server.mcpserver.exceptions import ResourceNotFoundError, ToolError
from pydantic import BaseModel
DB_PATH = Path(__file__).parent / "stock.db"
MAX_REORDER = 100_000
SCHEMA = """
CREATE TABLE stock (
ingredient TEXT PRIMARY KEY, amount REAL NOT NULL, unit TEXT NOT NULL, reorder_level REAL NOT NULL
);
CREATE TABLE reorders (
id INTEGER PRIMARY KEY AUTOINCREMENT, ingredient TEXT NOT NULL, amount REAL NOT NULL,
status TEXT NOT NULL, created_at TEXT NOT NULL
);
INSERT INTO stock VALUES
('milk', 800, 'ml', 1000),
('coffee beans', 3000, 'g', 1000),
('ice', 4000, 'g', 2000),
('thai tea', 600, 'g', 200);
"""
def connect() -> sqlite3.Connection:
is_new = not DB_PATH.exists()
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
if is_new:
connection.executescript(SCHEMA)
return connection
mcp = MCPServer("stock")
class Ingredient(TypedDict):
ingredient: str
amount: float
unit: str
reorder_level: float
is_low: bool
class Confirmation(BaseModel):
confirm: bool
def load_ingredient(name: str) -> Ingredient | None:
with connect() as db:
row = db.execute("SELECT * FROM stock WHERE ingredient = ?", (name,)).fetchone()
return None if row is None else {**dict(row), "is_low": row["amount"] <= row["reorder_level"]}
@mcp.tool()
def check_stock(ingredient: str) -> Ingredient:
"""Current stock of an ingredient, with is_low true when it is at or below its reorder level."""
found = load_ingredient(ingredient)
if found is None:
raise ToolError(f"Unknown ingredient '{ingredient}'.")
return found
def ask_reorder_confirmation(ingredient: str, amount: float) -> Elicit[Confirmation]:
found = load_ingredient(ingredient)
if found is None or not 0 < amount <= MAX_REORDER:
raise ToolError(f"Cannot reorder {amount} of '{ingredient}': amount must be between 0 and {MAX_REORDER}.")
with connect() as db:
pending = db.execute("SELECT 1 FROM reorders WHERE ingredient = ? AND status = 'open'", (ingredient,)).fetchone()
if pending:
raise ToolError(f"'{ingredient}' already has an open reorder.")
return Elicit(f"Order {amount:g} {found['unit']} of {ingredient} from the supplier?", Confirmation)
@mcp.tool()
def reorder(
ingredient: str,
amount: float,
answer: Annotated[ElicitationResult[Confirmation], Resolve(ask_reorder_confirmation)],
) -> str:
"""Place a supplier reorder for an ingredient after the user confirms. Records an open reorder; stock does not change until delivery."""
if not isinstance(answer, AcceptedElicitation) or not answer.data.confirm:
return f"Reorder of {ingredient} was not placed."
with connect() as db:
cursor = db.execute(
"INSERT INTO reorders (ingredient, amount, status, created_at) VALUES (?, ?, 'open', datetime('now'))",
(ingredient, amount),
)
return f"Reorder #{cursor.lastrowid}: {amount:g} of {ingredient}."
@mcp.resource("stock://ingredients/{name}", mime_type="application/json")
def ingredient_resource(name: str) -> Ingredient:
"""Stock level of one ingredient."""
found = load_ingredient(name)
if found is None:
raise ResourceNotFoundError(f"Unknown ingredient '{name}'")
return found
if __name__ == "__main__":
mcp.run()
connect()สร้างstock.dbพร้อมข้อมูลตั้งต้น 4 วัตถุดิบตอนเรียกครั้งแรก เหมือนdatabase.pyของcafeแต่เป็นไฟล์แยก นมตั้งไว้ที่ 800 ml ต่ำกว่าจุดสั่งซื้อ 1000 ml เพื่อให้งานในบทหน้ามีของให้สั่งreorderไม่แก้ตารางstockแค่เพิ่มแถวopenในreordersของจะเข้าร้านเมื่อไรเป็นเรื่องของ supplierask_reorder_confirmationคือ guard ของreorderชื่อวัตถุดิบที่ไม่มี จำนวนที่ไม่อยู่ในช่วง 0 ถึง 100000 หรือวัตถุดิบที่มีใบสั่งเปิดค้างอยู่ จะได้ToolErrorทันที- ใบสั่งที่เปิดค้างกันไม่ให้ AI สั่งนมซ้ำ ถ้าเราสั่งงานเดียวกันสองรอบในบทหน้า
2. Notify Server
import sqlite3
from pathlib import Path
from typing import Annotated
from mcp.server.mcpserver import AcceptedElicitation, Elicit, ElicitationResult, MCPServer, Resolve
from mcp.server.mcpserver.exceptions import ToolError
from pydantic import BaseModel
DB_PATH = Path(__file__).parent / "notify.db"
MAX_TEXT_LENGTH = 500
SCHEMA = """
CREATE TABLE channels (id TEXT PRIMARY KEY, description TEXT NOT NULL);
CREATE TABLE messages (
id INTEGER PRIMARY KEY AUTOINCREMENT, channel TEXT NOT NULL, text TEXT NOT NULL, sent_at TEXT NOT NULL
);
INSERT INTO channels VALUES ('staff-group', 'Barista group chat'), ('owner', 'Owner daily digest');
"""
def connect() -> sqlite3.Connection:
is_new = not DB_PATH.exists()
connection = sqlite3.connect(DB_PATH)
connection.row_factory = sqlite3.Row
if is_new:
connection.executescript(SCHEMA)
return connection
mcp = MCPServer("notify")
class Confirmation(BaseModel):
confirm: bool
@mcp.resource("notify://channels", mime_type="application/json")
def channels_resource() -> list[dict]:
"""Channels that send_message can reach."""
with connect() as db:
return [dict(row) for row in db.execute("SELECT id, description FROM channels ORDER BY id")]
def ask_send_confirmation(channel: str, text: str) -> Elicit[Confirmation]:
with connect() as db:
known = db.execute("SELECT 1 FROM channels WHERE id = ?", (channel,)).fetchone()
if known is None:
raise ToolError(f"Unknown channel '{channel}'. Read notify://channels first.")
if not text.strip() or len(text) > MAX_TEXT_LENGTH:
raise ToolError(f"A message needs 1 to {MAX_TEXT_LENGTH} characters.")
return Elicit(f"Send to {channel}: {text}", Confirmation)
@mcp.tool()
def send_message(
channel: str,
text: str,
answer: Annotated[ElicitationResult[Confirmation], Resolve(ask_send_confirmation)],
) -> str:
"""Send a message to a channel after the user confirms. Stand-in: stores the message in notify.db."""
if not isinstance(answer, AcceptedElicitation) or not answer.data.confirm:
return f"Message to {channel} was not sent."
with connect() as db:
cursor = db.execute(
"INSERT INTO messages (channel, text, sent_at) VALUES (?, ?, datetime('now'))", (channel, text)
)
return f"Sent message #{cursor.lastrowid} to {channel}."
if __name__ == "__main__":
mcp.run()
- ช่องที่ส่งได้มีแค่แถวในตาราง
channels(staff-group,owner) ชื่อช่องอื่นที่ AI คิดเองได้ToolErrorที่ชี้ไปอ่านnotify://channels - ข้อความห้ามว่าง และยาวไม่เกิน 500 ตัวอักษร (กันไม่ให้ AI ส่งข้อความยาวเกินอ่านในแชทกลุ่ม)
- คำถามยืนยันมีข้อความเต็มที่จะถูกส่ง (
Send to staff-group: ...) ผู้ใช้เห็นสิ่งที่จะออกไปก่อนกดตอบ ข้อความนี้ AI เป็นคนเขียนจากข้อมูลของ server อื่น ผู้ใช้เลยเป็นด่านสุดท้าย
Test with a Client
server ทั้งสองรันแบบ stdio ซึ่ง curl ต่อไม่ได้ เลยทดสอบด้วย Client ใน process เดียวกันเหมือนบท Confirm Actions with Elicitation
try_guards.py ทดสอบทีละ server รวมทุกกรณีที่ guard ปฏิเสธ
Guards
สร้างไฟล์ try_guards.py
import asyncio
from mcp import Client
from mcp.shared.exceptions import MCPError
from mcp_types import ElicitResult
import notify_server
import stock_server
def user_says(action: str):
async def callback(context, params):
print(f" server asks: {params.message} -> {action}")
return ElicitResult(action=action, content={"confirm": True} if action == "accept" else None)
return callback
async def attempt(client, tool: str, arguments: dict) -> None:
result = await client.call_tool(tool, arguments)
shown = {key: (value[:30] + "..." if isinstance(value, str) and len(value) > 30 else value) for key, value in arguments.items()}
text = result.content[0].text
text = text.splitlines()[0] if result.is_error else " ".join(text.split())
print(f"{tool} {shown}: is_error={result.is_error}", text)
async def main() -> None:
print("## stock")
async with Client(stock_server.mcp, elicitation_callback=user_says("accept")) as client:
print("tools:", [tool.name for tool in (await client.list_tools()).tools])
print("templates:", [item.uri_template for item in (await client.list_resource_templates()).resource_templates])
for name in ("milk", "ice", "mocha", "' OR 1=1 --"):
await attempt(client, "check_stock", {"ingredient": name})
print("resource:", (await client.read_resource("stock://ingredients/milk")).contents[0].text.replace("\n", ""))
for bad in (
{"ingredient": "mocha", "amount": 5},
{"ingredient": "milk", "amount": 0},
{"ingredient": "milk", "amount": -3},
{"ingredient": "milk", "amount": 1e9},
{"ingredient": "milk", "amount": float("nan")},
):
await attempt(client, "reorder", bad)
await attempt(client, "reorder", {"ingredient": "milk", "amount": 5000})
await attempt(client, "reorder", {"ingredient": "milk", "amount": 5000})
for action in ("decline", "cancel"):
async with Client(stock_server.mcp, elicitation_callback=user_says(action)) as client:
await attempt(client, "reorder", {"ingredient": "ice", "amount": 3000})
print("## notify")
async with Client(notify_server.mcp, elicitation_callback=user_says("accept")) as client:
print("tools:", [tool.name for tool in (await client.list_tools()).tools])
print("channels:", (await client.read_resource("notify://channels")).contents[0].text.replace("\n", ""))
for bad in (
{"channel": "general", "text": "hi"},
{"channel": "staff-group", "text": " "},
{"channel": "staff-group", "text": "x" * 501},
{"channel": "' OR 1=1 --", "text": "hi"},
):
await attempt(client, "send_message", bad)
await attempt(client, "send_message", {"channel": "staff-group", "text": "'); DROP TABLE messages; --"})
async with Client(notify_server.mcp, elicitation_callback=user_says("decline")) as client:
await attempt(client, "send_message", {"channel": "owner", "text": "declined test"})
async with Client(notify_server.mcp) as client:
try:
await attempt(client, "send_message", {"channel": "owner", "text": "no callback"})
except MCPError as error:
print(f"client without elicitation: error {error.code}: {error.message}")
asyncio.run(main())
รันจากข้อมูลตั้งต้น แล้วดูว่าตารางที่เขียนมีอะไรบ้าง
rm -f stock.db notify.db
uv run python try_guards.py 2>/dev/null
sqlite3 -header stock.db "SELECT * FROM reorders"
sqlite3 -header notify.db "SELECT * FROM messages"
## stock
tools: ['check_stock', 'reorder']
templates: ['stock://ingredients/{name}']
check_stock {'ingredient': 'milk'}: is_error=False { "ingredient": "milk", "amount": 800.0, "unit": "ml", "reorder_level": 1000.0, "is_low": true }
check_stock {'ingredient': 'ice'}: is_error=False { "ingredient": "ice", "amount": 4000.0, "unit": "g", "reorder_level": 2000.0, "is_low": false }
check_stock {'ingredient': 'mocha'}: is_error=True Error executing tool check_stock: Unknown ingredient 'mocha'.
check_stock {'ingredient': "' OR 1=1 --"}: is_error=True Error executing tool check_stock: Unknown ingredient '' OR 1=1 --'.
resource: { "ingredient": "milk", "amount": 800.0, "unit": "ml", "reorder_level": 1000.0, "is_low": true}
reorder {'ingredient': 'mocha', 'amount': 5}: is_error=True Error executing tool reorder: Cannot reorder 5.0 of 'mocha': amount must be between 0 and 100000.
reorder {'ingredient': 'milk', 'amount': 0}: is_error=True Error executing tool reorder: Cannot reorder 0.0 of 'milk': amount must be between 0 and 100000.
reorder {'ingredient': 'milk', 'amount': -3}: is_error=True Error executing tool reorder: Cannot reorder -3.0 of 'milk': amount must be between 0 and 100000.
reorder {'ingredient': 'milk', 'amount': 1000000000.0}: is_error=True Error executing tool reorder: Cannot reorder 1000000000.0 of 'milk': amount must be between 0 and 100000.
reorder {'ingredient': 'milk', 'amount': nan}: is_error=True Error executing tool reorder: 1 validation error for reorderArguments
server asks: Order 5000 ml of milk from the supplier? -> accept
reorder {'ingredient': 'milk', 'amount': 5000}: is_error=False Reorder #1: 5000 of milk.
reorder {'ingredient': 'milk', 'amount': 5000}: is_error=True Error executing tool reorder: 'milk' already has an open reorder.
server asks: Order 3000 g of ice from the supplier? -> decline
reorder {'ingredient': 'ice', 'amount': 3000}: is_error=False Reorder of ice was not placed.
server asks: Order 3000 g of ice from the supplier? -> cancel
reorder {'ingredient': 'ice', 'amount': 3000}: is_error=False Reorder of ice was not placed.
## notify
tools: ['send_message']
channels: [ { "id": "owner", "description": "Owner daily digest" }, { "id": "staff-group", "description": "Barista group chat" }]
send_message {'channel': 'general', 'text': 'hi'}: is_error=True Error executing tool send_message: Unknown channel 'general'. Read notify://channels first.
send_message {'channel': 'staff-group', 'text': ' '}: is_error=True Error executing tool send_message: A message needs 1 to 500 characters.
send_message {'channel': 'staff-group', 'text': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...'}: is_error=True Error executing tool send_message: A message needs 1 to 500 characters.
send_message {'channel': "' OR 1=1 --", 'text': 'hi'}: is_error=True Error executing tool send_message: Unknown channel '' OR 1=1 --'. Read notify://channels first.
server asks: Send to staff-group: '); DROP TABLE messages; -- -> accept
send_message {'channel': 'staff-group', 'text': "'); DROP TABLE messages; --"}: is_error=False Sent message #1 to staff-group.
server asks: Send to owner: declined test -> decline
send_message {'channel': 'owner', 'text': 'declined test'}: is_error=False Message to owner was not sent.
client without elicitation: error -32021: Client did not declare the form elicitation capability required by resolver 'notify_server:ask_send_confirmation'
id|ingredient|amount|status|created_at
1|milk|5000.0|open|2026-11-24 08:12:21
id|channel|text|sent_at
1|staff-group|'); DROP TABLE messages; --|2026-11-24 08:12:21
- เคสที่ guard ปฏิเสธไม่มีบรรทัด
server asksคือผู้ใช้ไม่ถูกถามเลย nanไม่ถึงโค้ดของเรา เพราะ JSON ส่งnanไม่ได้ (กลายเป็นnull) แล้ว schema ของamountปฏิเสธก่อน- ข้อความ
'); DROP TABLE messages; --ถูกเก็บเป็นข้อความธรรมดาเพราะส่งผ่าน?placeholder ตารางmessagesยังอยู่
Pitfalls
- ถ้าเปลี่ยน
notifyไปเรียก API จริง ให้ตั้ง token เป็น environment variable ในเครื่อง (เช่นNOTIFY_TOKEN) แล้วใน.mcp.jsonใส่"env": {"NOTIFY_TOKEN": "${NOTIFY_TOKEN}"}Claude Code จะแทนค่าจากเครื่องตอนเปิด server ไม่เขียน token ตรง ๆ ลงในโค้ดหรือใน.mcp.jsonที่ commit เพราะใครเปิด repo ก็เห็น
Summary
ข้าง cafe ตอนนี้มี server stock (check_stock, reorder, resource stock://ingredients/{name}) และ notify (send_message, resource notify://channels)
แต่ละตัวมี Database ของตัวเอง ส่วน reorder กับ send_message ตรวจคำขอก่อน แล้วถามผู้ใช้ด้วย elicitation เพราะแก้สิ่งที่อยู่นอก server
ตอนนี้ server สามตัวยังทำงานแยกกัน บทหน้า Connect Multiple Servers ให้ Claude Code ใช้ทั้งสามตัวต่อกันในงานเดียวครับ