MCP Server 實作教學:用 Python 建立第一個可呼叫的文章搜尋工具
MCP 入門與實戰 03|2026 年 12 月 1 日|Python SDK v2 系列
這篇不從部署雲端主機開始,而是先建立一個可在本機測試的 MCP Server。完成目標是讓測試用戶端能發現文章搜尋工具、送出搜尋關鍵字並取得結構化結果。
範例以官方 Python SDK v2 文件為基準,需 Python 3.11 以上。未執行實機測試,讀者可使用下方驗收步驟確認自己的環境。
01|建立環境
在終端機建立專案及虛擬環境:
mkdir mcp-article-demo
cd mcp-article-demo
python -m venv .venv
Windows PowerShell 使用 .venv\Scripts\Activate.ps1 啟用;macOS 或 Linux 使用 source .venv/bin/activate。安裝指定主版本的 SDK:
python -m pip install "mcp[cli]>=2,<3"
固定主版本可以避免舊版教學與新版 API 混用。實際專案應再鎖定測試通過的完整套件版本。
02|撰寫 server.py
from mcp.server import MCPServer
mcp = MCPServer("Article Demo")
ARTICLES = [
{"id": "a001", "title": "MCP 入門",
"summary": "理解 AI 與工具的連接方式"},
{"id": "a002", "title": "網站權限管理",
"summary": "認識最小權限與發布審核"},
{"id": "a003", "title": "本地 AI 部署",
"summary": "在個人電腦執行模型"},
]
@mcp.tool()
def search_articles(query: str, limit: int = 5) -> list[dict[str, str]]:
"""依標題或摘要搜尋公開文章,最多回傳 10 筆。"""
keyword = query.strip().casefold()
if not keyword or not 1 <= limit <= 10:
raise ValueError("請提供關鍵字,limit 必須介於 1 至 10")
matches = [
article for article in ARTICLES
if keyword in (article["title"] + " " +
article["summary"]).casefold()
]
return matches[:limit]
if __name__ == "__main__":
mcp.run()
這裡的資料是固定的示範內容,不會連接正式網站,也不會修改檔案。函式名稱、型別提示與文件字串共同提供工具描述。
03|透過 Inspector 驗收
安裝 Node.js 後,在相同虛擬環境執行:
mcp dev server.py
依終端機顯示的網址開啟 MCP Inspector,找到 Tools,列出 search_articles 並輸入 query = MCP、limit = 5。
預期結果是包含 a001 的清單。再測試不存在的關鍵字,應回傳空清單;輸入 100 作為 limit 時,應回傳錯誤而非忽略限制。如果 Inspector 無法啟動,檢查 Node.js、Python 版本與虛擬環境中的 mcp 套件。
04|從本機變成 HTTP 服務
如果需要讓其他支援 MCP 的程式連線,可將最後的執行方式調整成:
mcp.run(transport="streamable-http", port=8000)
預設使用本機位址及 /mcp 路徑,應依官方文件與啟動日誌確認。stdio 適合由宿主啟動本機程序;Streamable HTTP 適合網路部署。舊 HTTP+SSE 傳輸主要用於相容舊版客戶端。
這不是直接部署公開服務的完整方式。正式上線還需要 HTTPS、身份驗證、權限、限流、日誌及資料來源驗證。
05|下一步
將固定清單換成既有後端的唯讀搜尋 API,並確保每個結果具有穩定 ID。等到讀取流程穩定,再新增草稿工具。不要一開始就給模型管理員權限。
官方文件
MCP introduction and practice 03 | December 1, 2026 | Python SDK v2 series
This article does not start with deploying a cloud server, but first establishes an MCP Server that can be tested locally. The goal is to enable the test client to discover the article search tool, send search keywords, and obtain structured results.
The example is based on the official Python SDK v2 documentation and requires Python 3.11 or higher. The reader can use the acceptance steps below to verify their own environment without running the actual test.
01 | Establish the environment
Create a project and virtual environment in the terminal:
mkdir mcp-article-demo
cd mcp-article-demo
python -m venv .venv
Use Windows PowerShell to activate; .venv\Scripts\Activate.ps1 macOS or Linux use source .venv/bin/activate. Install the specified major version of the SDK:
python -m pip install "mcp[cli]>=2,<3"
Fixing the major version can avoid mixing old tutorials with new APIs. In actual projects, it is recommended to lock the complete package version that has passed the test.
02 | Write server.py
from mcp.server import MCPServer
mcp = MCPServer("Article Demo")
ARTICLES = [
{"id": "a001", "title": "MCP 入門",
"summary": "理解 AI 與工具的連接方式"},
{"id": "a002", "title": "網站權限管理",
"summary": "認識最小權限與發布審核"},
{"id": "a003", "title": "本地 AI 部署",
"summary": "在個人電腦執行模型"},
]
@mcp.tool()
def search_articles(query: str, limit: int = 5) -> list[dict[str, str]]:
"""依標題或摘要搜尋公開文章,最多回傳 10 筆。"""
keyword = query.strip().casefold()
if not keyword or not 1 <= limit <= 10:
raise ValueError("請提供關鍵字,limit 必須介於 1 至 10")
matches = [
article for article in ARTICLES
if keyword in (article["title"] + " " +
article["summary"]).casefold()
]
return matches[:limit]
if __name__ == "__main__":
mcp.run()
The data here is fixed demonstration content and will not connect to the official website or modify files. The function name, type hints, and document strings together provide a tool description.
03|Verify through Inspector
After installing Node.js, run it in the same virtual environment:
mcp dev server.py
Open the MCP Inspector according to the URL displayed in the terminal, find Tools, and list search_articles and enter query = MCP, limit = 5.
The expected result is a list containing a001. Test again with a non-existent keyword, it should return an empty list; when entering 100 as the limit, it should return an error instead of ignoring the limit. If the Inspector cannot be started, check the Node.js, Python version, and the mcp package in the virtual environment.
04|Become an HTTP service from a local machine
If you need to allow other programs that support MCP to connect, you can adjust the final execution method to:
mcp.run(transport="streamable-http", port=8000)
The default uses the local address and /mcp path, and should be confirmed according to the official documentation and startup log. stdio is suitable for the host to start the local program; Streamable HTTP is suitable for network deployment. The old HTTP+SSE transmission is mainly used for compatibility with old clients.
This is not a complete way to deploy a public service directly. Formal online still needs HTTPS, identity authentication, permissions, flow limitation, log, and data source verification.
05|Next step
Replace the fixed list with a read-only search API from the existing backend, and ensure that each result has a stable ID. Wait until the reading process is stable, then add a draft tool. Do not give the model management authority from the beginning.