Lab 1 — สร้าง MCP server
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 ที่คุณรันเองจึงอาจต่างจากหน้านี้
คลิปทฤษฎีเปิดด้วย tool search_papers ที่ต้องเขียนตัวเชื่อมใหม่ทุกครั้งที่ย้ายไปโปรแกรมอื่น Lab นี้เราจะเปลี่ยนมันเป็น MCP server ด้วย FastMCP (Listing 21.1) แล้วต่อด้วย client (Listing 21.2)
สิ่งที่จะได้ทำ
- เขียน server ค้น paper: tool สองตัว · resource หนึ่งแบบ · prompt หนึ่งตัว
- ต่อ client ทาง stdio — เริ่มต้น และตกลงความสามารถ
- ดูว่า FastMCP สร้าง inputSchema จาก type hint และ docstring อย่างไร
- เรียก tool · อ่าน resource · ขอ prompt · และดู error
- ให้ model เลือก tool เอง จากคำอธิบายที่ server ส่งมา
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ และปีเป็นของจริง) ส่วนการเลือก tool ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §21.2–21.3, §21.5, §21.7.1–21.7.2, Listings 21.1–21.2 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 0.01 เซ็นต์ดอลลาร์) |
| Packages | mcp, openai, python-dotenv (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "mcp==1.30.0" "openai>=1.50" python-dotenv1. เขียน server: paper_server.py
server ต้องรันเป็น process แยก (transport แบบ stdio: client เปิด server เป็นโปรแกรมลูก) เราจึงเขียนลงไฟล์ด้วย %%writefile — cell แรกสร้างไฟล์ cell ต่อๆ ไปใช้ -a เขียนต่อท้าย
| ส่วนของ server | ใน MCP คือ | ใครเป็นคนใช้ |
|---|---|---|
search_papers, cite_paper |
tool | model ตัดสินใจเรียก |
paper://{paper_id} |
resource | host ดึงมาใส่ context |
summarize_paper |
prompt | ผู้ใช้เลือกใช้ |
%%writefile paper_server.py
import json
from mcp.server.fastmcp import FastMCP
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"},
}Writing paper_server.py
# ✏️ TODO 1 (▶ วิดีโอ 1:33): ประกาศว่าฟังก์ชันนี้เป็น tool ของ server
%%writefile -a paper_server.py
___
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():
text = (p["title"] + " " + p["summary"]).lower()
score = sum(w in text 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]])%%writefile -a paper_server.py
@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():
text = (p["title"] + " " + p["summary"]).lower()
score = sum(w in text 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]])Appending to paper_server.py
%%writefile -a paper_server.py
@mcp.tool()
def cite_paper(paper_id: str) -> str:
"""Format a short citation for one paper. Use this when you already know the paper's arXiv id,
e.g. "2310.06625". Fails on an unknown id; use search_papers first."""
if paper_id not in PAPERS:
raise ValueError(f"Unknown paper id {paper_id!r}. Use search_papers to find an id.")
p = PAPERS[paper_id]
return f'{p["authors"]} ({p["year"]}). {p["title"]}. arXiv:{paper_id}'Appending to paper_server.py
# ✏️ TODO 2 (▶ วิดีโอ 2:48): ผูกฟังก์ชันกับแม่แบบ URI ของ resource
%%writefile -a paper_server.py
@mcp.resource(___)
def get_paper(paper_id: str) -> str:
"""One paper's full record, as JSON."""
return json.dumps({"id": paper_id, **PAPERS[paper_id]})
@mcp.prompt()
def summarize_paper(paper_id: str) -> str:
"""Ask for a three-bullet summary of one paper, for a report."""
return f"Read paper://{paper_id} and summarize it in three short bullets for a report on transformers for time series."
if __name__ == "__main__":
mcp.run() # stdio by default%%writefile -a paper_server.py
@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]})
@mcp.prompt()
def summarize_paper(paper_id: str) -> str:
"""Ask for a three-bullet summary of one paper, for a report."""
return f"Read paper://{paper_id} and summarize it in three short bullets for a report on transformers for time series."
if __name__ == "__main__":
mcp.run() # stdio by defaultAppending to paper_server.py
2. ต่อ client ทาง stdio
วงจรชีวิตของการเชื่อมต่อ (§21.2.3): เปิด server → initialize (บอกเวอร์ชันและความสามารถ) → ใช้งาน → ปิด
ใน notebook เราเก็บ session ไว้ใช้ข้ามหลาย cell จึงให้ session อยู่ใน task ของตัวเอง (ถ้าเปิดด้วย async with ใน cell หนึ่ง แล้วไปปิดใน cell อื่น asyncio จะ error)
import os, sys, json, asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from openai import OpenAI
def load_key():
try: # Google Colab Secrets
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
pass
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]async def run_session(params, ready, stop):
with open("server.log", "w") as log:
async with stdio_client(params, errlog=log) as (read, write):
# ✏️ TODO 3 (▶ วิดีโอ 4:15): ส่งคำขอ initialize (ขั้นแรกของวงจรชีวิต)
async with ClientSession(read, write) as session:
init = ___
ready.set_result((session, init))
await stop.wait()
async def connect(server_file):
ready, stop = asyncio.get_running_loop().create_future(), asyncio.Event()
params = StdioServerParameters(command=sys.executable, args=[server_file])
task = asyncio.create_task(run_session(params, ready, stop))
session, init = await ready
async def close():
stop.set()
await task
return session, init, closeasync def run_session(params, ready, stop):
with open("server.log", "w") as log:
async with stdio_client(params, errlog=log) as (read, write):
async with ClientSession(read, write) as session:
init = await session.initialize()
ready.set_result((session, init))
await stop.wait()
async def connect(server_file):
ready, stop = asyncio.get_running_loop().create_future(), asyncio.Event()
params = StdioServerParameters(command=sys.executable, args=[server_file])
task = asyncio.create_task(run_session(params, ready, stop))
session, init = await ready
async def close():
stop.set()
await task
return session, init, closesession, init, close = await connect("paper_server.py")
print("server:", init.serverInfo.name, init.serverInfo.version, "· protocol", init.protocolVersion)
caps = init.capabilities
print("tools:", caps.tools is not None, "· resources:", caps.resources is not None,
"· prompts:", caps.prompts is not None, "· sampling: not offered by servers")server: cogito-papers 1.30.0 · protocol 2025-11-25
tools: True · resources: True · prompts: True · sampling: not offered by servers
3. ถาม server ว่ามีอะไรบ้าง
tools/list · resources/templates/list · prompts/list — client ไม่ต้องรู้ล่วงหน้าเลยว่า server มีอะไร
# ✏️ TODO 4 (▶ วิดีโอ 5:25): ขอรายการ tool จาก server
listed = ___
for t in listed.tools:
print(f"🔧 {t.name}\n {t.description}\n inputSchema: {json.dumps(t.inputSchema)}\n")listed = await session.list_tools()
for t in listed.tools:
print(f"🔧 {t.name}\n {t.description}\n inputSchema: {json.dumps(t.inputSchema)}\n")🔧 search_papers
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.
inputSchema: {"properties": {"query": {"title": "Query", "type": "string"}, "max_results": {"default": 3, "title": "Max Results", "type": "integer"}}, "required": ["query"], "title": "search_papersArguments", "type": "object"}
🔧 cite_paper
Format a short citation for one paper. Use this when you already know the paper's arXiv id,
e.g. "2310.06625". Fails on an unknown id; use search_papers first.
inputSchema: {"properties": {"paper_id": {"title": "Paper Id", "type": "string"}}, "required": ["paper_id"], "title": "cite_paperArguments", "type": "object"}
templates = await session.list_resource_templates()
for r in templates.resourceTemplates:
print("📄", r.uriTemplate, "-", r.description)
prompts = await session.list_prompts()
for p in prompts.prompts:
print("📝", p.name, [a.name for a in p.arguments], "-", p.description)📄 paper://{paper_id} - One paper's full record, as JSON.
📝 summarize_paper ['paper_id'] - Ask for a three-bullet summary of one paper, for a report.
4. เรียก tool · อ่าน resource · ขอ prompt
result = await session.call_tool("search_papers", {"query": "transformer time series", "max_results": 3})
print("isError:", result.isError)
print(result.content[0].text)isError: False
[{"id": "2211.14730", "title": "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers", "year": 2023}, {"id": "2310.06625", "title": "iTransformer: Inverted Transformers Are Effective for Time Series Forecasting", "year": 2024}, {"id": "2012.07436", "title": "Informer: Beyond Efficient Transformer for Long Sequence Time-Series Forecasting", "year": 2021}]
res = await session.read_resource("paper://2310.06625")
print(res.contents[0].uri, "\n", res.contents[0].text)
pr = await session.get_prompt("summarize_paper", {"paper_id": "2310.06625"})
print(pr.messages[0].role, ":", pr.messages[0].content.text)paper://2310.06625
{"id": "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"}
user : Read paper://2310.06625 and summarize it in three short bullets for a report on transformers for time series.
bad = await session.call_tool("cite_paper", {"paper_id": "9999.99999"})
print("isError:", bad.isError)
print(bad.content[0].text)isError: True
Error executing tool cite_paper: Unknown paper id '9999.99999'. Use search_papers to find an id.
5. ให้ model เลือก tool จากคำอธิบายของ server
Model: google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora · lab นี้ต้องการ tool calling (model คืนชื่อ tool + argument เป็น JSON) ซึ่ง Gemma 4 ทำได้ · ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก — การเลือก tool หนึ่งครั้งราว 0.002 เซ็นต์ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-25: 3 ใน 4 ครั้งได้ 429 “rate-limited”)
MCP บอก schema ของ tool ส่วน API ของ model ต้องการ tool ใน รูปแบบของตัวเอง — ตำราบอกว่า JSON schema ของ argument เหมือนกัน (§21.9.2) จึงแปลงได้ในไม่กี่บรรทัด
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}}client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
COST = {"chat": 0.0}# ✏️ TODO 5 (▶ วิดีโอ 8:02): ใส่ inputSchema ของ MCP เป็น parameters ของ model
def to_openai(tool):
"""MCP tool → the tool format of the OpenAI-style chat API."""
return {"type": "function",
"function": {"name": tool.name, "description": tool.description,
"parameters": ___}}
TOOLS = [to_openai(t) for t in listed.tools]def to_openai(tool):
"""MCP tool → the tool format of the OpenAI-style chat API."""
return {"type": "function",
"function": {"name": tool.name, "description": tool.description,
"parameters": tool.inputSchema}}
TOOLS = [to_openai(t) for t in listed.tools]async def pick_and_call(question):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, tools=TOOLS,
messages=[{"role": "user", "content": question}])
COST["chat"] += r.usage.cost
call = r.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
print(f"❓ {question}\n🤖 model picked: {call.function.name}({args})")
# ✏️ TODO 6 (▶ วิดีโอ 8:34): ส่ง tool call ที่ model เลือกไปให้ server ผ่าน MCP
result = ___
print("📦", result.content[0].text, "\n")async def pick_and_call(question):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, tools=TOOLS,
messages=[{"role": "user", "content": question}])
COST["chat"] += r.usage.cost
call = r.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
print(f"❓ {question}\n🤖 model picked: {call.function.name}({args})")
result = await session.call_tool(call.function.name, args)
print("📦", result.content[0].text, "\n")await pick_and_call("Find papers about transformers for time series forecasting.")
await pick_and_call("Give me a citation for paper 2310.06625.")❓ Find papers about transformers for time series forecasting.
🤖 model picked: search_papers({'query': 'transformers for time series forecasting'})
📦 [{"id": "2211.14730", "title": "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers", "year": 2023}, {"id": "2310.06625", "title": "iTransformer: Inverted Transformers Are Effective for Time Series Forecasting", "year": 2024}, {"id": "2205.13504", "title": "Are Transformers Effective for Time Series Forecasting?", "year": 2023}]
❓ Give me a citation for paper 2310.06625.
🤖 model picked: cite_paper({'paper_id': '2310.06625'})
📦 Liu et al. (2024). iTransformer: Inverted Transformers Are Effective for Time Series Forecasting. arXiv:2310.06625
await close()
print(f"cost: ${COST['chat']:.6f}")cost: $0.000050
สรุป
| ขั้น | สิ่งที่เห็น |
|---|---|
| server | FastMCP + decorator สามแบบ: @mcp.tool() · @mcp.resource("paper://{paper_id}") · @mcp.prompt() |
| initialize | server ประกาศ tools · resources · prompts |
tools/list |
inputSchema สร้างจาก type hint, คำอธิบายคือ docstring — ไม่ได้เขียน JSON schema เอง |
tools/call ผิด |
ไม่มี exception — isError: True + ข้อความที่ model อ่านได้ |
| model เลือก tool | หาตามหัวข้อ → search_papers · รู้เลขแล้ว → cite_paper |
แบบฝึกหัด
- เปลี่ยน docstring ของ
cite_paperเป็นแค่"Cite."แล้วถามคำถามที่สองอีกครั้ง — model ยังเลือกถูกไหม - เพิ่ม tool
list_years()ที่คืนปีทั้งหมดในคลัง แล้วดูว่ามันโผล่ในtools/listโดยไม่ต้องแก้ client - เปิด
server.logดูว่า server ได้รับคำขออะไรบ้าง
ถัดไป — Lab 2: เปิดดูข้างในสาย พิมพ์ข้อความ JSON-RPC เองถึง server ตัวนี้ ตั้งแต่ initialize จนถึง error