返回资讯中心
外部精选
大数据
#数据科学#机器学习

教程:用 Python 构建无状态 MCP 服务器

来源标题:Build Your First MCP Server in Python (Stateless Spec Edition)

一篇教程介绍了如何用 Python 构建无状态 MCP 服务器,通过 HTTP 暴露工具、资源和提示。新版 MCP 规范简化了开发流程,开发者用装饰器即可定义资源(如 kb://articles)、工具和可复用提示模板,其中资源为可读数据,工具为可执行操作。

KDnuggetsKanwal Mehreen2026/10/9 · 17 天前9 分钟阅读

以下正文由 AI 翻译自 KDnuggets(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。

def list_articles() -> str: """Return the available knowledge-base articles.""" lines = [] for article in ARTICLES: lines.append( f"{article['id']}: {article['title']}" ) return "\n".join(lines)

该资源的 URI 为:

kb://articles

客户端无需调用工具即可读取它。

Resource ≈ 可读取的数据 Tool ≈ 可执行工作的函数

SDK 文档大致将 resources 类比为类似 GET 的行为,将 tools 类比为面向动作的类似 POST 的行为。

我们还可以暴露一个可复用的 prompt 模板。

def draft_support_reply(customer_message: str) -> str: """Create a prompt for drafting a concise support response.""" return f""" You are a technical support assistant. Write a concise and helpful response to this customer message: {customer_message} Use the support knowledge base when relevant. Do not invent product policies. """.strip()

同样,这只是一个 Python 函数加一个装饰器。

Prompts 通常由用户或 host 发起,而不是由模型自主调用。当前的 SDK 通过同一套面向装饰器的服务器接口来支持 tools、resources 和 prompts。

此时,server.py 看起来是这样的:

from mcp.server import MCPServer mcp = MCPServer( "Developer Support KB", instructions=( "Use the knowledge-base tools to answer support questions. " "Prefer retrieved KB information over guessing." ), ) ARTICLES = [

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →