ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

MCP 从入门到实战:用 Python 构建本地知识便签服务,把 Server 配置改到 TaoToken

MCP 从入门到实战:用 Python 构建本地知识便签服务,把 Server 配置改到 TaoToken 1. 为什么本地知识便签服务值得用 MCP 重写一遍如果你正在找一个能真正跑通的 MCP 入门项目本地知识便签服务是个很合适的选择它足够小小到一个server.py就能写完又足够完整完整到能覆盖 Tools、Resources、Prompts 三种核心能力。更重要的是它天然需要“读写本地数据 被 AI 客户端调用”正好是 MCPModel Context Protocol模型上下文协议最典型的落地场景。MCP 是什么一句话它是一套让 AI 应用以统一方式连接外部数据和工具的开放协议。能做什么让模型发现并调用你写的 Python 函数、读取你暴露的资源、复用你封装好的提示模板。适合谁适合已经会基础 Python、想把本地脚本变成 AI 可调用能力的开发者。我这次的目标不是再写一个“Hello World”式的 MCP Demo而是把 Server 的 endpoint 与鉴权配置统一改到 TaoToken 通道然后用 Python Client 完成一次真实的便签写入、搜索、读取闭环。整个过程你会拿到三样东西可复制的 Server 端配置片段、可运行的 Client 调用示例、以及一次从配置到调用的完整验证动作。先说清楚一个容易踩的坑MCP 不是大模型不会让模型变聪明它也不是 Agent 框架不负责规划任务。它解决的是“连接标准化”——把 AI 应用和外部系统之间的私有适配收敛成一套统一协议。理解了这一点后面的配置和排障才不会跑偏。本文的实战载体是一个notes-assistantServer提供add_note、search_notes、delete_note三个工具notes://index和notes://{note_id}两个资源以及一个summarize_topic提示模板。数据存在本地 JSON 文件里不依赖数据库。等你跑通之后把存储换成 SQLite 或真实知识库就是一次平滑升级。2. TaoToken 前置把 Server 的 endpoint 与鉴权统一到一条通道在动手写代码之前先把“通道”这件事定下来。很多 MCP 教程只讲 stdio 本地进程但真实项目里Server 往往需要调用一个统一的模型或能力网关。这里我们把 endpoint 与鉴权配置改到 TaoToken 统一通道好处是Server 端不用散落多套 KeyClient 调用时也只需要认一个 Base URL。TaoToken 在这里扮演的角色是统一接入层。官网地址是 https://taotoken.net/?utm_sourcetaotoken_aicg_blog_endutm_mediumcsdnutm_campaignrewriteutm_content API 入口是 https://taotoken.net/api 注意 API 地址不加 UTM 参数。你需要先拿到一个 API Key再去控制台确认可用的 Model ID。具体操作路径是这样的打开模型对话页面 https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentmodel_chatutm_campaignrewrite 可以先体验模型能力进入 API Keys 页面 https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentapi_keysutm_campaignrewrite 创建密钥如果你打算长期做编码或 Agent 类项目可以看 Coding Plan https://taotoken.net/coding-plan?utm_sourcetaotoken_aicg_blog_endutm_contentcoding_planutm_campaignrewrite 接入细节查文档 https://taotoken.net/doc?utm_sourcetaotoken_aicg_blog_endutm_contentdocutm_campaignrewrite 。这里要强调一个原则MCP Server 本身不一定要联网但一旦它需要调用模型能力比如做语义检索、生成摘要就应该把 endpoint 和鉴权集中配置而不是在每个工具函数里硬编码。我们会在 Server 端读取环境变量把 Base URL、API Key、Model ID 三件套统一管理。注意不要把 API Key 写进代码或提交到 Git。用环境变量或本地.env文件并在.gitignore里排除。如果你用的是 Claude Code 这类客户端配置入口在 https://taotoken.net/claude-code-anthropic?utm_sourcetaotoken_aicg_blog_endutm_contentclaude_codeutm_campaignrewrite 需要管理多个 Key 时用控制台 https://taotoken.net/console?utm_sourcetaotoken_aicg_blog_endutm_contentconsoleutm_campaignrewrite 。这些页面先收藏后面排障会反复用到。3. 可复制配置Server 端 settings 与 Client 端 JSON 片段这一节是全文最“能抄”的部分。先给 Server 端的配置片段再给 Client 端的调用配置。路径和字段名请按你本机实际情况替换。先看 Server 端的环境配置。我们用一个settings.json来集中管理通道信息放在项目根目录{ taotoken: { base_url: https://taotoken.net/api, api_key_env: TAOTOKEN_API_KEY, model_id: your-model-id, timeout_seconds: 60 }, notes: { data_dir: ./data, notes_file: ./data/notes.json, max_title_len: 100, max_content_len: 5000, max_tags: 10 } }对应的 Server 端读取逻辑写在config.py里from __future__ import annotations import json import os from pathlib import Path BASE_DIR Path(__file__).resolve().parent SETTINGS_FILE BASE_DIR / settings.json def load_settings() - dict: if not SETTINGS_FILE.exists(): raise RuntimeError(settings.json 不存在请先创建) data json.loads(SETTINGS_FILE.read_text(encodingutf-8)) api_key os.getenv(data[taotoken][api_key_env], ) if not api_key: raise RuntimeError( f环境变量 {data[taotoken][api_key_env]} 未设置 ) data[taotoken][api_key] api_key return data这里的关键点是base_url固定为https://taotoken.net/apiapi_key从环境变量读取model_id单独配置。三件套齐了Server 端任何需要模型能力的地方都从这里取。再看 Client 端的 MCP 配置。不同客户端格式略有差异但核心字段一致。以常见的mcpServers结构为例{ mcpServers: { notes-assistant: { command: uv, args: [ --directory, C:/projects/mcp-notes-demo, run, python, server.py ], env: { TAOTOKEN_API_KEY: sk-your-key-here, TAOTOKEN_BASE_URL: https://taotoken.net/api, TAOTOKEN_MODEL_ID: your-model-id } } } }如果你用的是 Codex 的auth.json风格配置结构会是这样{ base_url: https://taotoken.net/api, api_key: sk-your-key-here, model: your-model-id }三件套必须写全Base URL、Key、Model ID。少任何一个后面调用都会报错。Windows 路径用正斜杠/或者反斜杠写成\\。保存后记得重启或刷新客户端。提示如果你用 Cline 或 CC Switch 管理多个 MCP Server把notes-assistant单独列一项env 里只放它需要的变量避免 Key 串用。4. 验证请求一次完整的便签读写闭环配置写好了接下来要证明它真的能跑。我们分两步先用 MCP Inspector 人工验证再用 Python Client 自动验证。先启动 Inspectoruv run mcp dev server.py浏览器打开调试地址后依次做这几件事确认 Server 初始化成功查看 Tools 列表调用add_note参数如下{ title: MCP 学习记录, content: MCP Server 可以通过 Tools、Resources 和 Prompts 暴露能力。, tags: [MCP, Python] }然后调用search_notes关键词填MCP打开notes://index用新增便签的 ID 读取notes://{note_id}。如果每一步都有正常返回说明 Server 端没问题。接下来写 Python Client 做自动化验证。创建client.pyimport asyncio import sys from pathlib import Path from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client BASE_DIR Path(__file__).resolve().parent async def main() - None: server StdioServerParameters( commandsys.executable, args[str(BASE_DIR / server.py)], ) async with stdio_client(server) as (read_stream, write_stream): async with ClientSession(read_stream, write_stream) as session: await session.initialize() tools await session.list_tools() print(可用工具, [tool.name for tool in tools.tools]) created await session.call_tool( add_note, arguments{ title: 第一次调用 MCP Tool, content: 这条便签由 Python MCP Client 创建。, tags: [MCP, 实战], }, ) print(新增结果, created.content) searched await session.call_tool( search_notes, arguments{keyword: MCP, limit: 5}, ) print(搜索结果, searched.content) index await session.read_resource(notes://index) print(便签索引, index.contents[0].text) if __name__ __main__: asyncio.run(main())运行uv run python client.py如果终端依次打印出工具列表、新增结果、搜索结果和便签索引说明你已经跑通了完整链路Client 启动 Server 子进程 → initialize 能力协商 → list_tools 能力发现 → call_tool 工具调用 → read_resource 资源读取。这比“客户端界面里好像出现了工具”可靠得多因为每一层都被验证过了。5. 本篇常见错排查401、local proxy failed 与 reading choices排障部分我按真实报错来写你遇到哪个就查哪个。报错一401 Unauthorized。这是鉴权失败九成是 Key 没传对。检查三处环境变量名是否和settings.json里的api_key_env一致Client 配置的env里是否真的注入了 KeyKey 是否有多余空格或换行。如果用的是 Codexauth.json确认api_key字段名没写错。报错二local proxy failed。这个通常出现在 Client 启动 Server 子进程时命令或路径不对。检查command是否在客户端环境里可执行args里的目录是否是绝对路径。桌面应用继承的 PATH 可能和终端不同把uv换成绝对路径往往能解决。Windows 下用Get-Command uv查路径macOS/Linux 用which uv。报错三reading choices 相关错误。这类错误一般出现在模型返回结构不符合预期时。检查model_id是否填对Base URL 是否是https://taotoken.net/api。如果 Server 端调用了模型能力确认请求体里的model字段和配置一致。报错四OAuth 相关错误。如果你在 Claude Code 或类似客户端里看到 OAuth 报错先确认是否误用了需要 OAuth 的入口。我们的场景用 API Key 即可配置入口参考 https://taotoken.net/claude-code-anthropic?utm_sourcetaotoken_aicg_blog_endutm_contentclaude_codeutm_campaignrewrite 。检查auth.json或客户端配置里是否残留了旧的 OAuth 字段。报错五Server 一启动就退出。检查 Python 环境是否装了mcp配置里的脚本绝对路径是否正确stderr 里有没有导入或语法错误。stdio 模式下print()到 stdout 会破坏协议所有调试信息必须走 stderr。报错六工具可见但模型总选错。这不是配置问题是 Tool 设计问题。优化 Tool 名称、描述、参数 Schema以及重叠工具的职责边界。不要靠加长系统 Prompt 硬掰。6. 语义一致 CTA把这条通道用起来跑通本地便签服务只是起点。接下来你可以做三件事把存储换成 SQLite 或真实知识库给search_notes加上语义检索把 Server 部署到远程用 Streamable HTTP 暴露。需要创建或管理 Key去 API Keys 页面 https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentapi_keysutm_campaignrewrite 接入细节查文档 https://taotoken.net/doc?utm_sourcetaotoken_aicg_blog_endutm_contentdocutm_campaignrewrite 想先验证模型能力用模型对话 https://taotoken.net/api-keys?utm_sourcetaotoken_aicg_blog_endutm_contentmodel_chatutm_campaignrewrite 长期做编码或 Agent 项目看 Coding Plan https://taotoken.net/coding-plan?utm_sourcetaotoken_aicg_blog_endutm_contentcoding_planutm_campaignrewrite 。最后留一个实用技巧每次改完配置先用 Inspector 验证 Server 本身再用 Python Client 验证协议链路最后才接 AI 客户端。这个顺序能帮你把问题定位在正确的层而不是在客户端日志里大海捞针。
返回列表