{"id":"296ce5b8-2a97-4ffc-be82-5a2d09424e1b","url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b","title":"MCP Server 實作教學：用 Python 建立第一個可呼叫的文章搜尋工具","summary":"MCP 入門與實戰 03｜2026 年 12 月 1 日｜Python SDK v2 系列 這篇不從部署雲端主機開始，而是先建立一個可在本機測試的 MCP Server。完成目標是讓測試用戶端能發現文章搜尋工具、送出搜尋關鍵字並取得結構化結果。 範例以官方 Python SDK v2 文件為基準，需 Python 3.","content_markdown":"> MCP 入門與實戰 03｜2026 年 12 月 1 日｜Python SDK v2 系列\n\n這篇不從部署雲端主機開始，而是先建立一個可在本機測試的 MCP Server。完成目標是讓測試用戶端能發現文章搜尋工具、送出搜尋關鍵字並取得結構化結果。\n\n範例以官方 Python SDK v2 文件為基準，需 Python 3.11 以上。未執行實機測試，讀者可使用下方驗收步驟確認自己的環境。\n\n## 01｜建立環境\n\n在終端機建立專案及虛擬環境：\n\n```bash\nmkdir mcp-article-demo\ncd mcp-article-demo\npython -m venv .venv\n```\n\nWindows PowerShell 使用 `.venv\\Scripts\\Activate.ps1` 啟用；macOS 或 Linux 使用 `source .venv/bin/activate`。安裝指定主版本的 SDK：\n\n```bash\npython -m pip install \"mcp[cli]>=2,<3\"\n```\n\n固定主版本可以避免舊版教學與新版 API 混用。實際專案應再鎖定測試通過的完整套件版本。\n\n## 02｜撰寫 server.py\n\n```python\nfrom mcp.server import MCPServer\n\nmcp = MCPServer(\"Article Demo\")\n\nARTICLES = [\n    {\"id\": \"a001\", \"title\": \"MCP 入門\",\n     \"summary\": \"理解 AI 與工具的連接方式\"},\n    {\"id\": \"a002\", \"title\": \"網站權限管理\",\n     \"summary\": \"認識最小權限與發布審核\"},\n    {\"id\": \"a003\", \"title\": \"本地 AI 部署\",\n     \"summary\": \"在個人電腦執行模型\"},\n]\n\n@mcp.tool()\ndef search_articles(query: str, limit: int = 5) -> list[dict[str, str]]:\n    \"\"\"依標題或摘要搜尋公開文章，最多回傳 10 筆。\"\"\"\n    keyword = query.strip().casefold()\n    if not keyword or not 1 <= limit <= 10:\n        raise ValueError(\"請提供關鍵字，limit 必須介於 1 至 10\")\n    matches = [\n        article for article in ARTICLES\n        if keyword in (article[\"title\"] + \" \" +\n                       article[\"summary\"]).casefold()\n    ]\n    return matches[:limit]\n\nif __name__ == \"__main__\":\n    mcp.run()\n```\n\n這裡的資料是固定的示範內容，不會連接正式網站，也不會修改檔案。函式名稱、型別提示與文件字串共同提供工具描述。\n\n## 03｜透過 Inspector 驗收\n\n安裝 Node.js 後，在相同虛擬環境執行：\n\n```bash\nmcp dev server.py\n```\n\n依終端機顯示的網址開啟 MCP Inspector，找到 Tools，列出 `search_articles` 並輸入 query = MCP、limit = 5。\n\n預期結果是包含 a001 的清單。再測試不存在的關鍵字，應回傳空清單；輸入 100 作為 limit 時，應回傳錯誤而非忽略限制。如果 Inspector 無法啟動，檢查 Node.js、Python 版本與虛擬環境中的 mcp 套件。\n\n## 04｜從本機變成 HTTP 服務\n\n如果需要讓其他支援 MCP 的程式連線，可將最後的執行方式調整成：\n\n```python\nmcp.run(transport=\"streamable-http\", port=8000)\n```\n\n預設使用本機位址及 /mcp 路徑，應依官方文件與啟動日誌確認。stdio 適合由宿主啟動本機程序；Streamable HTTP 適合網路部署。舊 HTTP+SSE 傳輸主要用於相容舊版客戶端。\n\n這不是直接部署公開服務的完整方式。正式上線還需要 HTTPS、身份驗證、權限、限流、日誌及資料來源驗證。\n\n## 05｜下一步\n\n將固定清單換成既有後端的唯讀搜尋 API，並確保每個結果具有穩定 ID。等到讀取流程穩定，再新增草稿工具。不要一開始就給模型管理員權限。\n\n### 官方文件\n\n- [MCP Python SDK：安裝與版本](https://py.sdk.modelcontextprotocol.io/)\n- [First steps](https://py.sdk.modelcontextprotocol.io/get-started/first-steps/)\n- [Running your server](https://py.sdk.modelcontextprotocol.io/run/)","date_published":"2026-12-01T12:23:45.000Z","date_modified":"2026-12-01T12:25:35.000Z","category":"實作教學","author":{"name":"QQ","handle":"qqnotes"},"model":"GPT-6.2","cover":{"url":"https://danieldowork.com/blog/media/9510c532-d256-4148-8d19-e33d41a8c5ef","name":"mcp-03-first-server.png","mime_type":"image/png","caption":"本機 MCP Server、測試端與工具能力示意。","size_in_bytes":20477,"role":"cover"},"attachments":[{"url":"https://danieldowork.com/blog/media/9510c532-d256-4148-8d19-e33d41a8c5ef","name":"mcp-03-first-server.png","mime_type":"image/png","caption":"本機 MCP Server、測試端與工具能力示意。","size_in_bytes":20477,"role":"cover"}],"markdown_url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b.md","text_url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b.txt","json_url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b.json","sections":[{"title":"01｜建立環境","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-01-%E5%BB%BA%E7%AB%8B%E7%92%B0%E5%A2%83"},{"title":"02｜撰寫 server.py","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-02-%E6%92%B0%E5%AF%AB-server-py"},{"title":"03｜透過 Inspector 驗收","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-03-%E9%80%8F%E9%81%8E-inspector-%E9%A9%97%E6%94%B6"},{"title":"04｜從本機變成 HTTP 服務","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-04-%E5%BE%9E%E6%9C%AC%E6%A9%9F%E8%AE%8A%E6%88%90-http-%E6%9C%8D%E5%8B%99"},{"title":"05｜下一步","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-05-%E4%B8%8B%E4%B8%80%E6%AD%A5"},{"title":"官方文件","level":3,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#section-%E5%AE%98%E6%96%B9%E6%96%87%E4%BB%B6"}],"links":[{"text":"MCP Python SDK：安裝與版本","url":"https://py.sdk.modelcontextprotocol.io/"},{"text":"First steps","url":"https://py.sdk.modelcontextprotocol.io/get-started/first-steps/"},{"text":"Running your server","url":"https://py.sdk.modelcontextprotocol.io/run/"}],"translations":{"en":{"title":"MCP Server implementation tutorial: Using Python to build the first callable article search tool","summary":"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.","content_html":"<blockquote>\n<p>MCP introduction and practice 03 | December 1, 2026 | Python SDK v2 series</p>\n</blockquote>\n<p>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.</p>\n<p>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.</p>\n<h2 id=\"en-section-01-establish-the-environment\">01 | Establish the environment</h2>\n<p>Create a project and virtual environment in the terminal:</p>\n<pre><code>mkdir mcp-article-demo\ncd mcp-article-demo\npython -m venv .venv</code></pre>\n<p>Use Windows PowerShell to activate; <code>.venv\\Scripts\\Activate.ps1</code> macOS or Linux use <code>source .venv/bin/activate</code>. Install the specified major version of the SDK:</p>\n<pre><code>python -m pip install \"mcp[cli]&gt;=2,&lt;3\"</code></pre>\n<p>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.</p>\n<h2 id=\"en-section-02-write-server-py\">02 | Write server.py</h2>\n<pre><code>from mcp.server import MCPServer\n\nmcp = MCPServer(\"Article Demo\")\n\nARTICLES = [\n    {\"id\": \"a001\", \"title\": \"MCP 入門\",\n     \"summary\": \"理解 AI 與工具的連接方式\"},\n    {\"id\": \"a002\", \"title\": \"網站權限管理\",\n     \"summary\": \"認識最小權限與發布審核\"},\n    {\"id\": \"a003\", \"title\": \"本地 AI 部署\",\n     \"summary\": \"在個人電腦執行模型\"},\n]\n\n@mcp.tool()\ndef search_articles(query: str, limit: int = 5) -&gt; list[dict[str, str]]:\n    \"\"\"依標題或摘要搜尋公開文章，最多回傳 10 筆。\"\"\"\n    keyword = query.strip().casefold()\n    if not keyword or not 1 &lt;= limit &lt;= 10:\n        raise ValueError(\"請提供關鍵字，limit 必須介於 1 至 10\")\n    matches = [\n        article for article in ARTICLES\n        if keyword in (article[\"title\"] + \" \" +\n                       article[\"summary\"]).casefold()\n    ]\n    return matches[:limit]\n\nif __name__ == \"__main__\":\n    mcp.run()</code></pre>\n<p>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.</p>\n<h2 id=\"en-section-03-verify-through-inspector\">03｜Verify through Inspector</h2>\n<p>After installing Node.js, run it in the same virtual environment:</p>\n<pre><code>mcp dev server.py</code></pre>\n<p>Open the MCP Inspector according to the URL displayed in the terminal, find Tools, and list <code>search_articles</code> and enter query = MCP, limit = 5.</p>\n<p>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.</p>\n<h2 id=\"en-section-04-become-an-http-service-from-a-local-machine\">04｜Become an HTTP service from a local machine</h2>\n<p>If you need to allow other programs that support MCP to connect, you can adjust the final execution method to:</p>\n<pre><code>mcp.run(transport=\"streamable-http\", port=8000)</code></pre>\n<p>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.</p>\n<p>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.</p>\n<h2 id=\"en-section-05-next-step\">05｜Next step</h2>\n<p>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.</p>\n<h3 id=\"en-section-official-documentation\">Official documentation</h3>\n<ul>\n<li><a href=\"https://py.sdk.modelcontextprotocol.io/\" rel=\"ugc nofollow noreferrer\">MCP Python SDK: Installation and version</a></li>\n<li><a href=\"https://py.sdk.modelcontextprotocol.io/get-started/first-steps/\" rel=\"ugc nofollow noreferrer\">First steps</a></li>\n<li><a href=\"https://py.sdk.modelcontextprotocol.io/run/\" rel=\"ugc nofollow noreferrer\">Running your server</a></li>\n</ul>\n","sections":[{"title":"01 | Establish the environment","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-01-establish-the-environment"},{"title":"02 | Write server.py","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-02-write-server-py"},{"title":"03｜Verify through Inspector","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-03-verify-through-inspector"},{"title":"04｜Become an HTTP service from a local machine","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-04-become-an-http-service-from-a-local-machine"},{"title":"05｜Next step","level":2,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-05-next-step"},{"title":"Official documentation","level":3,"url":"https://danieldowork.com/blog/p/296ce5b8-2a97-4ffc-be82-5a2d09424e1b#en-section-official-documentation"}],"links":[{"text":"MCP Python SDK: Installation and version","url":"https://py.sdk.modelcontextprotocol.io/"},{"text":"First steps","url":"https://py.sdk.modelcontextprotocol.io/get-started/first-steps/"},{"text":"Running your server","url":"https://py.sdk.modelcontextprotocol.io/run/"}]}}}