Lab 2 — ข้างในสาย MCP
Lab walkthrough · EP13 MCP: One Standard for Agent Tools
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP13 MCP: One Standard for Agent Tools
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 1 เราใช้ ClientSession คุยกับ server — มันซ่อนข้อความทั้งหมดไว้ Lab นี้เราจะเป็น client เอง: เปิด server แล้ว พิมพ์ข้อความ JSON-RPC 2.0 ทีละบรรทัด ลงท่อ stdin และอ่านคำตอบดิบจาก stdout (§21.4)
สิ่งที่จะได้ทำ
- เปิด server เป็นโปรแกรมลูก — transport แบบ stdio คือ JSON หนึ่งข้อความต่อหนึ่งบรรทัด
- Handshake:
initialize→ ตกลงเวอร์ชันและความสามารถ →notifications/initialized - Request / response:
tools/list,tools/call— จับคู่ด้วยid - Error สองระดับ: error ของ tool (
isError) กับ error ของโปรโตคอล (-32602) - Notification: ความคืบหน้า (
notifications/progress) และรายการ tool ที่เปลี่ยน (list_changed) - Shutdown: ปิดท่อ แล้ว server ปิดตัวเอง
Lab นี้ไม่เรียก model จึงไม่ต้องใช้ API key และไม่มีค่าใช้จ่าย
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §21.2.3, §21.4, §21.5.2 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| Packages | mcp (ใช้ฝั่ง server เท่านั้น — ฝั่ง client เราเขียนเอง) |
%pip install -q "mcp==1.30.0"1. Server ตัวเดิม + tool ใหม่สองตัว
search_papers และ resource paper://{paper_id} จาก Lab 1 · บวก tool ใหม่ที่ไว้ดูข้อความสองแบบ
index_library— งานที่ใช้เวลา และ รายงานความคืบหน้า (§21.4.4)enable_citations— เพิ่ม toolcite_paperระหว่าง session แล้ว แจ้งว่ารายการ tool เปลี่ยน (§21.5.2)
%%writefile paper_server.py
import json, asyncio
from mcp.server.fastmcp import FastMCP, Context
mcp = FastMCP("cogito-papers")
PAPERS = { # teaching data: real arXiv ids, titles and years; short summaries written for this lab
"2211.14730": {"title": "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers",
"authors": "Nie et al.", "year": 2023, "summary": "PatchTST: split each series into patches, one channel at a time"},
"2310.06625": {"title": "iTransformer: Inverted Transformers Are Effective for Time Series Forecasting",
"authors": "Liu et al.", "year": 2024, "summary": "attention across variables instead of across time steps"},
"2310.10688": {"title": "A decoder-only foundation model for time-series forecasting",
"authors": "Das et al.", "year": 2024, "summary": "TimesFM: one pretrained model that forecasts many series zero-shot"},
"2012.07436": {"title": "Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting",
"authors": "Zhou et al.", "year": 2021, "summary": "sparse attention to make long forecasts cheaper"},
"2205.13504": {"title": "Are Transformers Effective for Time Series Forecasting?",
"authors": "Zeng et al.", "year": 2023, "summary": "a simple linear model beats several transformers"},
}
@mcp.tool()
def search_papers(query: str, max_results: int = 3) -> str:
"""Search the paper library by keyword in the title or summary.
Use this to find papers on a topic. Returns a JSON list of {id, title, year}, best match first."""
words = query.lower().split()
scored = []
for pid, p in PAPERS.items():
score = sum(w in (p["title"] + " " + p["summary"]).lower() for w in words)
if score:
scored.append((score, {"id": pid, "title": p["title"], "year": p["year"]}))
scored.sort(key=lambda s: -s[0])
return json.dumps([paper for _, paper in scored[:max_results]])
@mcp.resource("paper://{paper_id}")
def get_paper(paper_id: str) -> str:
"""One paper's full record, as JSON."""
return json.dumps({"id": paper_id, **PAPERS[paper_id]})Writing paper_server.py
%%writefile -a paper_server.py
@mcp.tool()
async def index_library(ctx: Context) -> str:
"""Rebuild the search index. Slow; reports progress."""
n = len(PAPERS)
for i in range(1, n + 1):
await asyncio.sleep(0.3)
await ctx.report_progress(i, n, f"indexed {i}/{n} papers")
return f"indexed {n} papers"Appending to paper_server.py
%%writefile -a paper_server.py
@mcp.tool()
async def enable_citations(ctx: Context) -> str:
"""Unlock the cite_paper tool for this session."""
def cite_paper(paper_id: str) -> str:
"""Format a short citation for one paper, by its arXiv id."""
p = PAPERS[paper_id]
return f'{p["authors"]} ({p["year"]}). {p["title"]}. arXiv:{paper_id}'
mcp.add_tool(cite_paper)
await ctx.session.send_tool_list_changed()
return "cite_paper is now available"
if __name__ == "__main__":
mcp.run()Appending to paper_server.py
2. เปิด server และต่อท่อเอง
transport แบบ stdio (§21.2.2): client เปิด server เป็นโปรแกรมลูก แล้วคุยผ่าน stdin / stdout ข้อความหนึ่งข้อความ = JSON หนึ่งบรรทัด · log ของ server ออกทาง stderr (เราเก็บลงไฟล์)
import sys, json, subprocess
server = subprocess.Popen([sys.executable, "paper_server.py"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=open("server.log", "w"), text=True)# ✏️ TODO 1 (▶ วิดีโอ 2:31): เขียนข้อความเป็น JSON หนึ่งบรรทัด (ปิดท้ายด้วยขึ้นบรรทัดใหม่)
def send(msg):
server.stdin.write(___)
server.stdin.flush()
print("➡️ ", json.dumps(msg)[:300])
def recv():
msg = json.loads(server.stdout.readline())
print("⬅️ ", json.dumps(msg)[:300])
return msgdef send(msg):
server.stdin.write(json.dumps(msg) + "\n")
server.stdin.flush()
print("➡️ ", json.dumps(msg)[:300])
def recv():
msg = json.loads(server.stdout.readline())
print("⬅️ ", json.dumps(msg)[:300])
return msg3. Handshake: initialize
ข้อความแรกต้องเป็น initialize (§21.4.2): เวอร์ชันโปรโตคอล · ความสามารถของ client · ชื่อ client เราส่งเวอร์ชัน 2024-11-05 ตามตัวอย่างในตำรา
# ✏️ TODO 2 (▶ วิดีโอ 3:01): ตั้ง method ของคำขอแรก
send({"jsonrpc": "2.0", "id": 1, "method": ___,
"params": {"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "by-hand", "version": "0.1"}}})
init = recv()
print("version:", init["result"]["protocolVersion"])
print("server capabilities:", init["result"]["capabilities"])send({"jsonrpc": "2.0", "id": 1, "method": "initialize",
"params": {"protocolVersion": "2024-11-05", "capabilities": {},
"clientInfo": {"name": "by-hand", "version": "0.1"}}})
init = recv()
print("version:", init["result"]["protocolVersion"])
print("server capabilities:", init["result"]["capabilities"])➡️ {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "by-hand", "version": "0.1"}}}
⬅️ {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "capabilities": {"experimental": {}, "prompts": {"listChanged": false}, "resources": {"subscribe": false, "listChanged": false}, "tools": {"listChanged": false}}, "serverInfo": {"name": "cogito-papers", "version": "1.30.0"}}}
version: 2024-11-05
server capabilities: {'experimental': {}, 'prompts': {'listChanged': False}, 'resources': {'subscribe': False, 'listChanged': False}, 'tools': {'listChanged': False}}
# ✏️ TODO 3 (▶ วิดีโอ 3:42): แจ้งว่า client พร้อม (notification: ไม่มี id)
send({"jsonrpc": "2.0", "method": ___})send({"jsonrpc": "2.0", "method": "notifications/initialized"})➡️ {"jsonrpc": "2.0", "method": "notifications/initialized"}
4. Request และ response
ทุกคำขอมี id · คำตอบกลับมาพร้อม id เดิม (§21.4.1) — เหมือนบัตรคิวร้านอาหาร
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
tools = recv()["result"]["tools"]
for t in tools:
print("🔧", t["name"], "· required:", t["inputSchema"].get("required", []))➡️ {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
⬅️ {"jsonrpc": "2.0", "id": 2, "result": {"tools": [{"name": "search_papers", "description": "Search the paper library by keyword in the title or summary.\nUse this to find papers on a topic. Returns a JSON list of {id, title, year}, best match first.", "inputSchema": {"properties": {"query": {"title":
🔧 search_papers · required: ['query']
🔧 index_library · required: []
🔧 enable_citations · required: []
send({"jsonrpc": "2.0", "id": 42, "method": "tools/call",
"params": {"name": "search_papers", "arguments": {"query": "linear", "max_results": 2}}})
reply = recv()
print("id:", reply["id"], "· isError:", reply["result"]["isError"])
print(reply["result"]["content"][0]["text"])➡️ {"jsonrpc": "2.0", "id": 42, "method": "tools/call", "params": {"name": "search_papers", "arguments": {"query": "linear", "max_results": 2}}}
⬅️ {"jsonrpc": "2.0", "id": 42, "result": {"content": [{"type": "text", "text": "[{\"id\": \"2205.13504\", \"title\": \"Are Transformers Effective for Time Series Forecasting?\", \"year\": 2023}]"}], "structuredContent": {"result": "[{\"id\": \"2205.13504\", \"title\": \"Are Transformers Effective for
id: 42 · isError: False
[{"id": "2205.13504", "title": "Are Transformers Effective for Time Series Forecasting?", "year": 2023}]
5. Error สองระดับ
| ระดับ | เกิดเมื่อ | หน้าตา |
|---|---|---|
| tool | tool ทำงานไม่สำเร็จ (argument ผิด, ข้อมูลไม่มี) | result ปกติ แต่ isError: true — ข้อความกลับไปให้ model อ่านได้ |
| โปรโตคอล | ตัวคำขอเองผิด | ไม่มี result · มี error พร้อมรหัส เช่น -32602 invalid params (§21.4.3) |
send({"jsonrpc": "2.0", "id": 43, "method": "tools/call",
"params": {"name": "search_papers", "arguments": {}}})
bad_tool = recv()
print("has result:", "result" in bad_tool, "· isError:", bad_tool["result"]["isError"])➡️ {"jsonrpc": "2.0", "id": 43, "method": "tools/call", "params": {"name": "search_papers", "arguments": {}}}
⬅️ {"jsonrpc": "2.0", "id": 43, "result": {"content": [{"type": "text", "text": "Error executing tool search_papers: 1 validation error for search_papersArguments\nquery\n Field required [type=missing, input_value={}, input_type=dict]\n For further information visit https://errors.pydantic.dev/2.14
has result: True · isError: True
send({"jsonrpc": "2.0", "id": 44, "method": "resources/read", "params": {}})
bad_request = recv()
print("has result:", "result" in bad_request, "· error:", bad_request["error"])➡️ {"jsonrpc": "2.0", "id": 44, "method": "resources/read", "params": {}}
⬅️ {"jsonrpc": "2.0", "id": 44, "error": {"code": -32602, "message": "Invalid request parameters", "data": ""}}
has result: False · error: {'code': -32602, 'message': 'Invalid request parameters', 'data': ''}
6. Notification: ความคืบหน้า และรายการ tool ที่เปลี่ยน
คำขอที่ใส่ _meta.progressToken → server ส่ง notifications/progress มาก่อนคำตอบ (§21.4.4) เราจึงต้องอ่านไปเรื่อยๆ จนเจอข้อความที่มี id ของเรา
# ✏️ TODO 4 (▶ วิดีโอ 5:28): หยุดเมื่อเจอข้อความที่ id ตรงกับคำขอ
def recv_until(request_id):
while True:
msg = recv()
if ___:
return msg
# ✏️ TODO 5 (▶ วิดีโอ 5:39): ขอรับความคืบหน้าด้วย progressToken
send({"jsonrpc": "2.0", "id": 45, "method": "tools/call",
"params": {"name": "index_library", "arguments": {}, "_meta": ___}})
print(recv_until(45)["result"]["content"][0]["text"])def recv_until(request_id):
while True:
msg = recv()
if msg.get("id") == request_id:
return msg
send({"jsonrpc": "2.0", "id": 45, "method": "tools/call",
"params": {"name": "index_library", "arguments": {}, "_meta": {"progressToken": "index-op-1"}}})
print(recv_until(45)["result"]["content"][0]["text"])➡️ {"jsonrpc": "2.0", "id": 45, "method": "tools/call", "params": {"name": "index_library", "arguments": {}, "_meta": {"progressToken": "index-op-1"}}}
⬅️ {"method": "notifications/progress", "params": {"progressToken": "index-op-1", "progress": 1.0, "total": 5.0, "message": "indexed 1/5 papers"}, "jsonrpc": "2.0"}
⬅️ {"method": "notifications/progress", "params": {"progressToken": "index-op-1", "progress": 2.0, "total": 5.0, "message": "indexed 2/5 papers"}, "jsonrpc": "2.0"}
⬅️ {"method": "notifications/progress", "params": {"progressToken": "index-op-1", "progress": 3.0, "total": 5.0, "message": "indexed 3/5 papers"}, "jsonrpc": "2.0"}
⬅️ {"method": "notifications/progress", "params": {"progressToken": "index-op-1", "progress": 4.0, "total": 5.0, "message": "indexed 4/5 papers"}, "jsonrpc": "2.0"}
⬅️ {"method": "notifications/progress", "params": {"progressToken": "index-op-1", "progress": 5.0, "total": 5.0, "message": "indexed 5/5 papers"}, "jsonrpc": "2.0"}
⬅️ {"jsonrpc": "2.0", "id": 45, "result": {"content": [{"type": "text", "text": "indexed 5 papers"}], "structuredContent": {"result": "indexed 5 papers"}, "isError": false}}
indexed 5 papers
send({"jsonrpc": "2.0", "id": 46, "method": "tools/call", "params": {"name": "enable_citations", "arguments": {}}})
recv_until(46)
send({"jsonrpc": "2.0", "id": 47, "method": "tools/list"})
print([t["name"] for t in recv_until(47)["result"]["tools"]])➡️ {"jsonrpc": "2.0", "id": 46, "method": "tools/call", "params": {"name": "enable_citations", "arguments": {}}}
⬅️ {"method": "notifications/tools/list_changed", "jsonrpc": "2.0"}
⬅️ {"jsonrpc": "2.0", "id": 46, "result": {"content": [{"type": "text", "text": "cite_paper is now available"}], "structuredContent": {"result": "cite_paper is now available"}, "isError": false}}
➡️ {"jsonrpc": "2.0", "id": 47, "method": "tools/list"}
⬅️ {"jsonrpc": "2.0", "id": 47, "result": {"tools": [{"name": "search_papers", "description": "Search the paper library by keyword in the title or summary.\nUse this to find papers on a topic. Returns a JSON list of {id, title, year}, best match first.", "inputSchema": {"properties": {"query": {"title"
['search_papers', 'index_library', 'enable_citations', 'cite_paper']
7. Shutdown
ด้วย stdio client ปิดการเชื่อมต่อโดย ปิดท่อ stdin ของ server แล้วรอให้มันจบ
# ✏️ TODO 6 (▶ วิดีโอ 6:29): ปิดท่อ stdin เพื่อสั่งปิด server
___
print("exit code:", server.wait(timeout=10))
print("server saw:", sorted({line.split("type ")[1].strip() for line in open("server.log") if "request of type" in line}))server.stdin.close()
print("exit code:", server.wait(timeout=10))
print("server saw:", sorted({line.split("type ")[1].strip() for line in open("server.log") if "request of type" in line}))exit code: 0
server saw: ['CallToolRequest', 'ListToolsRequest']
สรุป
| ข้อความ | สิ่งที่เห็น |
|---|---|
initialize (id 1) |
ตกลงเวอร์ชัน 2024-11-05 · server ประกาศ tools, resources, prompts |
notifications/initialized |
ไม่มี id · ไม่มีคำตอบ |
tools/call (id 42) |
คำตอบ id 42 · content + isError: false |
| tool ล้มเหลว (id 43) | result ปกติ + isError: true — ส่งให้ model อ่านได้ |
| คำขอผิด (id 44) | error รหัส -32602 — ไม่มี result |
progressToken (id 45) |
notifications/progress 1/5 … 5/5 แล้วคำตอบ |
enable_citations (id 46) |
notifications/tools/list_changed → tools/list มี cite_paper |
| ปิด stdin | server จบด้วยรหัส 0 |
แบบฝึกหัด
- ส่ง
tools/callก่อนinitialize— server ตอบอะไร - ส่ง
resources/readของpaper://2310.06625เอง แล้วหาcontentsในคำตอบ - ส่งคำขอสองคำขอ (id 50, 51) ติดกันก่อนอ่าน แล้วดูว่าคำตอบมาตามลำดับไหน —
idช่วยอะไร
ถัดไป — Lab 3: เขียน host ให้ agent ของเรา ต่อ server สองตัวพร้อมกัน และหยุดถามก่อนเรียก tool ที่ย้อนกลับไม่ได้