1.参数补全 #
定义了
CompleteResult模型,用于封装补全结果,包含一个Completion类型的字段,便于结构化返回多样化的补全建议。- 新增了工具调用请求和响应的数据结构(如
CallToolRequestParams、CallToolRequest、CallToolResult),为后续补全结果和相关工具操作提供标准的数据交互格式。 - 在
completions_client.py与相关服务(如completions_server.py)中,通过会话和标准输入输出机制,发起参数补全请求并获取建议。例如,对于 Prompt 的language、style,以及资源模板的owner、repo参数,都能够自动给出智能补全值。 - 这些更改能够提升开发体验,在需要参数输入时自动给出符合上下文的可选项,便于选择和填写,减少手动输入错误,提高效率,并为工具链的集成打下基础。
你可以结合客户端和服务端提供的方法,快速体验自动参数补全能力,并通过返回结构化的补全数据轻松集成到更复杂的上层界面与操作流中。
npx @modelcontextprotocol/inspector uv --directory D:/aprepare/mcp-starter run completions_server.py2. completions_client.py #
completions_client.py
# 导入 os 模块
import os
# 从 mcp_lite 包导入 ClientSession、StdioServerParameters、types 类型
from mcp_lite import ClientSession, StdioServerParameters, types
# 从 mcp_lite.client.stdio 导入 stdio_client
from mcp_lite.client.stdio import stdio_client
# 主函数入口
def main():
# 获取当前文件的绝对路径,然后获取其所在目录
base_dir = os.path.dirname(os.path.abspath(__file__))
# 构造 completions_server.py 脚本的完整路径
server_path = os.path.join(base_dir, "completions_server.py")
# 初始化 StdioServerParameters,配置 Python 运行指令和参数
server_params = StdioServerParameters(command="python", args=[server_path], env={})
# 通过 stdio_client 以子进程方式启动 completions_server.py,并获取读写通道
with stdio_client(server_params) as (read, write):
# 基于读写通道创建 MCP 客户端会话
session = ClientSession(read, write)
# 执行会话初始化握手
session.initialize()
# 获取所有可用 Prompt,并打印其名称
prompts = session.list_prompts()
print("[Prompts]", [p.name for p in prompts.prompts])
# 获取所有可用的资源模板,并打印其 uri_template
templates = session.list_resource_templates()
print("[ResourceTemplates]", [t.uri_template for t in templates.resource_templates])
# 如果存在 prompt 提示,做补全演示
if prompts.prompts:
# 选取第一个 prompt 的名称
prompt_name = prompts.prompts[0].name
# 打印分隔符,指明 Prompt 补全示例
print(f"\n=== Prompt 补全示例:{prompt_name} ===")
# 对 prompt 的 language 参数进行补全,模拟输入 "py"
language_completion = session.complete(
ref=types.PromptReference(type="ref/prompt", name=prompt_name),
argument={"name": "language", "value": "py"},
)
# 打印 language 参数的补全建议
print(f"language='py' 的补全建议:{language_completion.completion.values}")
# 对 style 参数进行补全,模拟输入 "func"
style_completion = session.complete(
ref=types.PromptReference(type="ref/prompt", name=prompt_name),
argument={"name": "style", "value": "func"},
)
# 打印 style 参数的补全建议
print(f"style='func' 的补全建议:{style_completion.completion.values}")
# 如果存在资源模板,做资源模板参数补全演示
if templates.resource_templates:
# 选取第一个资源模板
template = templates.resource_templates[0]
# 打印分隔符,指明资源模板补全示例
print(f"\n=== 资源模板补全示例:{template.uri_template} ===")
# 对 owner 参数进行补全,模拟输入 "mod"
owner_completion = session.complete(
ref=types.ResourceTemplateReference(type="ref/resource", uri=template.uri_template),
argument={"name": "owner", "value": "mod"},
)
# 打印 owner 参数的补全建议
print(f"owner='mod' 的补全建议:{owner_completion.completion.values}")
# 对 repo 参数进行补全,模拟输入 "py",并指定 owner 上下文为 "modelcontextprotocol"
repo_completion = session.complete(
ref=types.ResourceTemplateReference(type="ref/resource", uri=template.uri_template),
argument={"name": "repo", "value": "py"},
context_arguments={"owner": "modelcontextprotocol"},
)
# 打印 repo 参数的补全建议(指定 owner 上下文)
print(f"repo='py' 的补全建议(owner=modelcontextprotocol):{repo_completion.completion.values}")
# 如果是主程序入口,则执行 main 函数
if __name__ == "__main__":
main()
3. completions_server.py #
completions_server.py
# 导入 sys 模块,用于设置标准流编码
import sys
# 导入 FastMCP 主类
from mcp_lite.server.fastmcp import FastMCP
# 导入类型定义相关类
from mcp_lite.types import (
Completion, # 补全结果类型
CompletionArgument, # 补全参数类型
CompletionContext, # 补全上下文类型
PromptReference, # 提示参考类型
ResourceTemplateReference, # 资源模板参考类型
)
# 创建 FastMCP 实例,命名为 "Completions Server"
mcp = FastMCP(name="Completions Server")
# 注册一个 Prompt(提示模板),描述为“代码风格指导”
@mcp.prompt(description="代码风格指导")
# 定义 Prompt 处理函数,名称为 code_style_guide,参数包括 language 和 style
def code_style_guide(language: str, style: str) -> str:
# 返回指定语言和风格的代码风格指导字符串
return f"请为 {language} 语言提供 {style} 风格的代码指导。"
# 注册一个资源模板,匹配 github://{owner}/{repo} 格式
@mcp.resource("github://{owner}/{repo}")
# 定义对应资源模板的处理函数,参数为 owner 和 repo
def github_repo_info(owner: str, repo: str) -> str:
# 返回指定仓库的信息说明字符串
return f"GitHub 仓库 {owner}/{repo} 的信息:这是一个示例仓库。"
# 注册参数补全处理器(completion handler)
@mcp.completion()
# 定义异步的补全处理函数
async def handle_completion(
ref: PromptReference | ResourceTemplateReference, # Prompt 或资源模板引用
argument: CompletionArgument, # 参数补全请求
context: CompletionContext | None, # 补全上下文(可选)
) -> Completion | None:
# 如果引用为 PromptReference 类型
if isinstance(ref, PromptReference):
# 如果 Prompt 名称为 "code_style_guide"
if ref.name == "code_style_guide":
# 如果参数名称为 "language"
if argument.name == "language":
# 设置可选的编程语言列表
languages = ["Python", "JavaScript", "Java", "C++", "Go", "Rust"]
# 根据输入内容过滤出以输入值开头的语言
filtered_languages = [
lang
for lang in languages
if lang.lower().startswith(argument.value.lower())
]
# 返回过滤后的语言补全结果
return Completion(
values=filtered_languages,
hasMore=False,
)
# 如果参数名称为 "style"
elif argument.name == "style":
# 设置可选的代码风格类型
styles = [
"clean",
"functional",
"object-oriented",
"procedural",
"declarative",
]
# 根据输入内容过滤出以输入值开头的风格
filtered_styles = [
style
for style in styles
if style.lower().startswith(argument.value.lower())
]
# 返回风格的补全结果
return Completion(
values=filtered_styles,
hasMore=False,
)
# 如果引用为 ResourceTemplateReference 类型
if isinstance(ref, ResourceTemplateReference):
# 如果资源 URI 格式为 github://{owner}/{repo}
if ref.uri == "github://{owner}/{repo}":
# 如果参数名称为 "owner"
if argument.name == "owner":
# 设置可选的 owner 名单
owners = [
"microsoft",
"google",
"facebook",
"netflix",
"modelcontextprotocol",
]
# 根据输入内容过滤 owner 名称
filtered_owners = [
owner
for owner in owners
if owner.lower().startswith(argument.value.lower())
]
# 返回 owner 补全结果
return Completion(
values=filtered_owners,
hasMore=False,
)
# 如果参数名称为 "repo"
elif argument.name == "repo":
# 如果上下文存在并且已经指定了 owner
if context and context.arguments and context.arguments.get("owner"):
# 获取指定的 owner
owner = context.arguments.get("owner")
# 根据 owner 不同设置 repo 列表
if owner == "microsoft":
repos = ["vscode", "typescript", "dotnet", "azure-sdk"]
elif owner == "google":
repos = ["tensorflow", "kubernetes", "go", "chromium"]
elif owner == "modelcontextprotocol":
repos = ["python-sdk", "servers", "specification", "website"]
else:
repos = ["main", "master", "develop", "feature"]
# 根据输入内容过滤 repo 名称
filtered_repos = [
repo
for repo in repos
if repo.lower().startswith(argument.value.lower())
]
# 返回 repo 的补全建议
return Completion(
values=filtered_repos,
hasMore=False,
)
# 如果没有任何补全建议则返回 None
return None
# 如果此脚本作为主程序执行,则使用 stdio 启动服务器
if __name__ == "__main__":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
sys.stdin.reconfigure(encoding="utf-8")
mcp.run(transport="stdio")
4. session.py #
mcp_lite/client/session.py
import sys
# 导入 SessionMessage 类
from mcp_lite.message import SessionMessage
# 从 mcp_lite.types 模块导入相关类型和常量
from mcp_lite.types import ( # 从 mcp_lite.types 模块导入以下类型
InitializeRequestParams, # 初始化请求参数类型
InitializeRequest, # 初始化请求类型
LATEST_PROTOCOL_VERSION, # 最新协议版本常量
ClientCapabilities, # 客户端能力类型
Implementation, # 实现信息类型
InitializedNotification, # 初始化完成通知类型
InitializeResult, # 初始化结果类型
JSONRPCRequest, # JSONRPC请求类型
JSONRPCResponse, # JSONRPC响应类型
JSONRPCError, # JSONRPC错误类型
JSONRPCNotification, # JSONRPC通知类型
LoggingMessageNotificationParams, # 日志消息通知参数
ListToolsRequest, # 工具列表请求类型
ListToolsResult, # 工具列表结果类型
CallToolResult, # 调用工具响应类型
CallToolRequest, # 调用工具请求类型
CallToolRequestParams, # 调用工具请求参数类型
ListResourcesRequest, # 资源列表请求类型
ListResourcesResult, # 资源列表响应类型
ListResourceTemplatesRequest, # 资源模板列表请求类型
ListResourceTemplatesResult, # 资源模板列表响应类型
ReadResourceRequest, # 读取资源请求类型
ReadResourceRequestParams, # 读取资源请求参数类型
ReadResourceResult, # 读取资源响应类型
ListPromptsRequest, # Prompt 列表请求类型
ListPromptsResult, # Prompt 列表响应类型
GetPromptRequest, # 获取 Prompt 请求类型
GetPromptRequestParams, # 获取 Prompt 请求参数类型
GetPromptResult, # 获取 Prompt 响应类型
+ CompleteRequest, # 补全请求类型
+ CompleteRequestParams, # 补全请求参数类型
+ CompleteResult, # 补全响应类型
+ CompletionArgument, # 补全参数类型
+ CompletionContext, # 补全上下文类型
)
# 定义 MCPError 异常类,用于表示协议相关错误
class MCPError(Exception):
# 初始化方法,接收错误码、错误信息和可选的数据
def __init__(self, code, message, data=None):
# 将错误码、错误信息、附加数据赋值为实例属性
self.code, self.message, self.data = code, message, data
# 调用父类 Exception 的初始化,只传递错误信息
super().__init__(message)
# 类方法,利用 JSONRPCError 对象创建 MCPError 实例
@classmethod
def from_jsonrpc(cls, err):
# 从 JSONRPCError.error 对象中取出 code/message/data 创建 MCPError
return cls(err.error.code, err.error.message, err.error.data)
# 定义 ClientSession 类,用于描述客户端会话
class ClientSession:
# 构造方法,接收读取流和写入流
def __init__(self, read_stream, write_stream):
# 赋值读取流和写入流
self._read, self._write = read_stream, write_stream
# 初始化请求 id 计数器为 0
self._req_id = 0
# 内部方法,发送请求并同步等待响应
def _request(self, req, progress_callback=None, message_handler=None, logging_callback=None):
# 当前请求 id
rid = self._req_id
# 自增请求 id,确保下次唯一
self._req_id += 1
# 对请求对象进行序列化,转为 dict
d = req.model_dump(by_alias=True, mode="json", exclude_none=True)
# 构建 JSONRPCRequest,再封装入 SessionMessage,通过写入流发送
jreq = JSONRPCRequest(jsonrpc="2.0", id=rid, method=d["method"], params=d.get("params"))
# 将请求对象封装成 SessionMessage 后发送
self._write.send(SessionMessage(message=jreq))
# 循环等待响应
while True:
# 从读取流取出一条消息
msg = self._read.get()
# 若取到 None,说明连接断开,抛出异常
if msg is None:
raise MCPError(-32000, "Connection closed")
# 若消息类型不是 SessionMessage,忽略继续等
if not isinstance(msg, SessionMessage):
continue
# 取消息内容
m = msg.message
# 判断当前消息是否为通知(即没有 id 字段且具有 method 字段)
if getattr(m, "id", None) is None and hasattr(m, "method"):
# 获取 method 名称
method = getattr(m, "method", "")
# 获取 params 内容(默认为空字典)
params = getattr(m, "params", None) or {}
# 若为进度通知,且传入了进度回调 progress_callback
if method == "notifications/progress" and progress_callback:
# 调用进度回调,传递 progress/total/message 参数
progress_callback(
params.get("progress", 0),
params.get("total"),
params.get("message"),
)
# 若为普通日志/信息通知
elif method == "notifications/message":
# 如果提供日志回调 logging_callback,则尝试解析为日志参数类型并调用
if logging_callback:
try:
# 使用 LoggingMessageNotificationParams 类型校验参数
p = LoggingMessageNotificationParams.model_validate(params, by_name=False)
# 调用日志回调
logging_callback(p)
except Exception:
# 校验失败则直接将原始 params 传递给日志回调
logging_callback(params)
# 如果指定了通用消息处理回调,则调用
if message_handler:
message_handler(m)
# 处理完通知类型后,继续等待下一个消息
continue
# 若为 Response 或 Error,且 id 匹配
if isinstance(m, (JSONRPCResponse, JSONRPCError)) and getattr(m, "id", None) == rid:
# 若为错误,抛出 MCPError 异常
if isinstance(m, JSONRPCError):
raise MCPError.from_jsonrpc(m)
# 为正常响应则返回结果数据
return m.result
# 内部方法,发送通知消息
def _notify(self, n):
# 通知对象序列化为 dict
d = n.model_dump(by_alias=True, mode="json", exclude_none=True)
# 封装为 JSONRPCNotification,再封装成 SessionMessage 后发出
self._write.send(SessionMessage(
message=JSONRPCNotification(
jsonrpc="2.0",
method=d["method"],
params=d.get("params"),
)
))
# 初始化过程,发送初始化请求,收到响应后再发初始化完成通知
def initialize(self):
# 构造初始化请求,并发送等待返回
r = self._request(InitializeRequest(
params=InitializeRequestParams(
protocol_version=LATEST_PROTOCOL_VERSION, # 协议版本号
capabilities=ClientCapabilities(), # 客户端能力
client_info=Implementation(name="mcp_lite", version="0.1.0"), # 客户端信息
)
))
# 发送"初始化完成"通知
self._notify(InitializedNotification())
# 用 InitializeResult 验证响应并返回
return InitializeResult.model_validate(r, by_name=False)
def list_tools(self):
# 发送 ListToolsRequest 请求,使用 ListToolsResult 校验并返回
return ListToolsResult.model_validate(self._request(ListToolsRequest()), by_name=False)
# 调用指定工具方法,传入工具名和参数
# 定义 call_tool 方法,用于调用指定名称的工具
def call_tool(self, name, arguments=None, progress_callback=None, message_handler=None, logging_callback=None):
# 如果提供了 progress_callback,则将当前请求 id 作为 progressToken 加入 meta,便于服务端推送进度通知
rid = self._req_id
meta = {"progressToken": rid} if progress_callback else None
# 构建工具调用请求参数,包含名称、参数和 meta 信息
params = CallToolRequestParams(name=name, arguments=arguments or {}, meta=meta)
# 调用 _request 方法发送工具调用请求,并用 CallToolResult 校验和结构化响应
return CallToolResult.model_validate(
self._request(
CallToolRequest(params=params),
progress_callback=progress_callback, # 进度回调函数
message_handler=message_handler, # 通用消息处理回调
logging_callback=logging_callback, # 日志回调函数
),
by_name=False, # 按字段名校验
)
# 列出已注册的静态资源
def list_resources(self):
# 调用 _request 方法发送 ListResourcesRequest 请求
# 使用 ListResourcesResult 的 model_validate 进行结果校验和结构化
return ListResourcesResult.model_validate(
self._request(ListResourcesRequest()),
by_name=False,
)
# 列出资源模板(带占位符的资源)
def list_resource_templates(self):
# 调用 _request 方法发送 ListResourceTemplatesRequest 请求
# 使用 ListResourceTemplatesResult 的 model_validate 进行结果校验和结构化
return ListResourceTemplatesResult.model_validate(
self._request(ListResourceTemplatesRequest()),
by_name=False,
)
# 读取指定 URI 的资源内容
def read_resource(self, uri):
# uri 可为 str 或 AnyUrl 类型
# 构造 ReadResourceRequestParams 并发送 ReadResourceRequest 请求
# 使用 ReadResourceResult 的 model_validate 进行结果校验和结构化
return ReadResourceResult.model_validate(
self._request(ReadResourceRequest(params=ReadResourceRequestParams(uri=str(uri)))),
by_name=False,
)
# 列出已注册的 Prompt
# 定义 list_prompts 方法,用于获取所有已注册的 Prompt
def list_prompts(self):
# 发送 ListPromptsRequest 请求,校验响应并结构化为 ListPromptsResult
return ListPromptsResult.model_validate(
self._request(ListPromptsRequest()), # 请求所有 Prompt
by_name=False, # 按字段名校验
)
# 请求 Prompt 或资源模板参数的补全建议
+ def complete(self, ref, argument, context_arguments=None):
# 构建补全上下文,若有 context_arguments 则封装为 CompletionContext
+ context = CompletionContext(arguments=context_arguments) if context_arguments else None
# 若 argument 为字典则转为 CompletionArgument
+ arg = argument if isinstance(argument, CompletionArgument) else CompletionArgument(**argument)
# 发送 CompleteRequest,校验并返回 CompleteResult
+ return CompleteResult.model_validate(
+ self._request(CompleteRequest(
+ params=CompleteRequestParams(ref=ref, argument=arg, context=context)
+ )),
+ by_name=False,
+ )
# 获取指定 Prompt 的内容
# 定义 get_prompt 方法,根据名称和参数获取指定 Prompt 的详情
def get_prompt(self, name, arguments=None):
# 发送 GetPromptRequest,请求参数包含指定名称和参数,响应结构化为 GetPromptResult
return GetPromptResult.model_validate(
self._request(GetPromptRequest( # 发送请求
params=GetPromptRequestParams( # 构造请求参数
name=name, # Prompt 名称
arguments=arguments or {} # Prompt 参数(默认为空字典)
)
)),
by_name=False, # 按字段名校验
)
5. init.py #
mcp_lite/server/fastmcp/init.py
# FastMCP 包:从原 fastmcp 模块导入所有内容以保持向后兼容
# 原 fastmcp.py 的内容已移入此包,通过 __init__ 导出
# 导入系统模块
import sys
# 导入 base64 编码库
import base64
# 导入 json 序列化
import json
# 导入正则表达式模块
import re
# 导入 url 解码工具
from urllib.parse import unquote
# 导入类型相关辅助函数
from typing import get_args, get_origin, get_type_hints
# 导入 SessionMessage 类型
from mcp_lite.message import SessionMessage
# 导入 stdio 通信模块
from mcp_lite.server import stdio
# 导入函数签名和异步工具
import inspect
import asyncio
from mcp_lite.types import ( # 导入 mcp_lite.types 模块中的多个类型
JSONRPCRequest, # JSONRPC 请求类型
JSONRPCNotification, # JSONRPC 通知类型
JSONRPCError, # JSONRPC 错误响应类型
ErrorData, # 错误数据类型
InitializeResult, # 初始化结果类型
LATEST_PROTOCOL_VERSION, # 最新协议版本号
ToolsCapability, # 工具相关能力描述类型
ResourcesCapability, # 资源相关能力描述类型
PromptsCapability, # Prompt 相关能力描述类型
+ CompletionsCapability, # 补全能力描述类型
ServerCapabilities, # 服务器能力类型
Implementation, # 实现信息类型
JSONRPCResponse, # JSONRPC 响应类型
ListToolsResult, # 列出工具结果类型
Tool, # 单个工具类型
TextContent, # 文本内容类型
CallToolRequestParams, # 调用工具请求参数类型
CallToolResult, # 调用工具响应结果类型
Resource, # 静态资源类型
ResourceTemplate, # 资源模板类型
ListResourcesResult, # 资源列表返回结果类型
ListResourceTemplatesResult, # 资源模板列表返回结果类型
ReadResourceRequestParams, # 读取资源请求参数类型
ReadResourceResult, # 读取资源请求响应类型
TextResourceContents, # 资源文本内容类型
BlobResourceContents, # 资源二进制内容类型
Prompt, # Prompt 类型
PromptArgument, # Prompt 参数类型
ListPromptsResult, # Prompt 列表结果类型
GetPromptRequestParams, # 获取 Prompt 请求参数类型
GetPromptResult, # 获取 Prompt 响应结果类型
PromptMessage, # Prompt 消息类型
+ Completion, # 补全结果内容类型
+ CompleteRequestParams, # 补全请求参数类型
+ CompleteResult, # 补全响应类型
)
# 导入 pydantic 的基础模型作为类型判定
from pydantic import BaseModel as PydanticBaseModel
# 导入 Typeddict 测试
from typing_extensions import is_typeddict as _is_typeddict
# 导入本包下 prompts 子模块
from . import prompts
# 辅助函数:提取函数输出 schema 及包裹需求
def _output_schema_and_wrap(fn, structured_output: bool):
# 若不是结构化输出,直接返回
if not structured_output:
return None, False
try:
# 获取函数签名
sig = inspect.signature(fn)
# 获取返回类型注解
ann = sig.return_annotation
# 如果没有注解,返回
if ann is inspect.Parameter.empty:
return None, False
except Exception:
return None, False
# 生成 schema
return _schema_from_annotation(ann, fn.__name__)
# 辅助函数:根据注解和函数名生成 schema
def _schema_from_annotation(ann, func_name: str):
# 没有注解直接返回
if ann is inspect.Parameter.empty:
return None, False
# 获取注解的原类型
origin = get_origin(ann)
wrap = False
schema = None
# 如果是 Pydantic 的模型子类
if PydanticBaseModel and isinstance(ann, type) and issubclass(ann, PydanticBaseModel):
schema = ann.model_json_schema()
return schema, False
# 如果是 Typeddict
if hasattr(ann, "__annotations__") and not (origin is dict or origin is list):
if _is_typeddict(ann):
hints = get_type_hints(ann) if hasattr(ann, "__annotations__") else {}
props = {}
for k, v in hints.items():
t = v
if t is int or t is type(None) and int in get_args(v):
props[k] = {"type": "integer"}
elif t is float:
props[k] = {"type": "number"}
elif t is str:
props[k] = {"type": "string"}
elif t is bool:
props[k] = {"type": "boolean"}
else:
props[k] = {"type": "string"}
schema = {"type": "object", "properties": props, "required": list(props)}
return schema, False
try:
hints = get_type_hints(ann)
if hints:
props = {}
for k, v in hints.items():
if v is int or v is type(None):
props[k] = {"type": "integer"}
elif v is float:
props[k] = {"type": "number"}
elif v is str:
props[k] = {"type": "string"}
elif v is bool:
props[k] = {"type": "boolean"}
elif get_origin(v) is list:
props[k] = {"type": "array", "items": {"type": "string"}}
else:
props[k] = {"type": "string"}
schema = {"type": "object", "properties": props}
return schema, False
except Exception:
pass
# 如果是 dict 类型
if origin is dict:
args = get_args(ann)
if len(args) == 2 and args[0] is str:
vt = args[1]
# 判断 value 类型
if vt is float:
schema = {"type": "object", "additionalProperties": {"type": "number"}}
elif vt is int:
schema = {"type": "object", "additionalProperties": {"type": "integer"}}
elif vt is str:
schema = {"type": "object", "additionalProperties": {"type": "string"}}
else:
schema = {"type": "object", "additionalProperties": {}}
return schema, False
wrap = True
# 如果是 list、基础类型等需要包裹
if origin is list or ann in (int, float, str, bool, type(None)):
wrap = True
# 包裹输出情况
if wrap:
result_schema = {"type": "string"}
if ann is int:
result_schema = {"type": "integer"}
elif ann is float:
result_schema = {"type": "number"}
elif ann is bool:
result_schema = {"type": "boolean"}
elif origin is list:
result_schema = {"type": "array", "items": {"type": "string"}}
schema = {"type": "object", "properties": {"result": result_schema}, "required": ["result"]}
return schema, True
return None, False
# 辅助:对象输出转换为结构化内容
def _to_structured(out, output_schema, wrap_output):
if output_schema is None:
return None
try:
# 如果是 Pydantic 模型
if PydanticBaseModel and isinstance(out, PydanticBaseModel):
return out.model_dump(mode="json")
# 如果需要包裹
if wrap_output:
return {"result": out}
# 如果是字典
if isinstance(out, dict):
return dict(out)
# 带有 __annotations__ 的对象,提取属性
if hasattr(out, "__annotations__"):
hints = get_type_hints(type(out)) if hasattr(type(out), "__annotations__") else getattr(out, "__annotations__", {})
return {k: getattr(out, k) for k in hints if hasattr(out, k)}
# 其它直接包裹
return {"result": out}
except Exception:
# 发生异常返回字符串
return {"result": str(out)}
# 根据函数参数生成 schema
def _schema(fn):
sig = inspect.signature(fn)
props = {}
req = []
for n, p in sig.parameters.items():
# 跳过以下划线开头的参数
if n.startswith("_"):
continue
# 跳过 Context 类型参数(由框架注入)
if _find_context_parameter(fn) == n:
continue
# 参数类型为字符串,标题为参数名
props[n] = {"type": "string", "title": n}
# 必填参数加入 required
if p.default is inspect.Parameter.empty:
req.append(n)
return {"type": "object", "properties": props, "required": req}
# 检测工具函数是否包含 Context 参数
def _find_context_parameter(fn):
"""若函数有 ctx: Context 参数,返回参数名;否则返回 None。"""
try:
sig = inspect.signature(fn)
hints = get_type_hints(fn) if hasattr(fn, "__annotations__") else {}
for name, param in sig.parameters.items():
ann = hints.get(name, param.annotation)
if ann is not inspect.Parameter.empty:
n = getattr(ann, "__name__", None) or str(ann)
if n == "Context" or (isinstance(n, str) and n.endswith(".Context")):
return name
except Exception:
pass
return None
# 根据 prompt 函数生成 prompt schema
def _prompt_schema(fn):
"""根据函数签名生成 Prompt 参数 schema。"""
sig = inspect.signature(fn)
props = {}
req = []
for n, p in sig.parameters.items():
if n.startswith("_"):
continue
props[n] = {"type": "string", "title": n}
if p.default is inspect.Parameter.empty:
req.append(n)
return {"type": "object", "properties": props, "required": req}
# Context 类:工具执行时的上下文,支持 read_resource、report_progress、debug、info
class Context:
"""工具执行上下文,提供资源读取、进度报告、日志发送等能力。"""
def __init__(self, mcp_server, request_id, send_notification=None, progress_token=None):
self._mcp = mcp_server
self.request_id = request_id
self._send = send_notification or (lambda _: None)
self._progress_token = progress_token
async def read_resource(self, uri: str):
"""异步读取资源,返回内容块列表(与 ReadResourceResult.contents 结构一致)。"""
uri_str = str(uri)
# 静态资源
if res := self._mcp._resources.get(uri_str):
out = res.run()
from mcp_lite.types import TextResourceContents
return [TextResourceContents(uri=uri_str, text=str(out), mime_type=res.mime_type)]
# 模板资源
for template in self._mcp._resource_templates.values():
if args := template.matches(uri_str):
out = template.run(args)
from mcp_lite.types import TextResourceContents, BlobResourceContents
if isinstance(out, bytes):
return [BlobResourceContents(uri=uri_str, blob=base64.b64encode(out).decode(), mime_type=template.mime_type or "application/octet-stream")]
return [TextResourceContents(uri=uri_str, text=str(out), mime_type=template.mime_type or "text/plain")]
return []
async def report_progress(self, progress: float, total: float | None = None, message: str | None = None):
"""发送进度通知(仅当客户端提供了 progressToken 时有效)。"""
if self._progress_token is not None:
self._send({"method": "notifications/progress", "params": {"progressToken": self._progress_token, "progress": progress, "total": total, "message": message}})
async def debug(self, data):
"""发送 debug 级别日志。"""
self._send({"method": "notifications/message", "params": {"level": "debug", "data": data}})
async def info(self, data):
"""发送 info 级别日志。"""
self._send({"method": "notifications/message", "params": {"level": "info", "data": data}})
# 工具函数封装类
class _Tool:
def __init__(self, fn, name=None, desc=None, structured_output=True):
# 函数本体
self.fn = fn
# 名称
self.name = name or fn.__name__
# 描述
self.desc = desc or (fn.__doc__ or "").strip()
# 入参 schema
self.schema = _schema(fn)
# 是否是异步函数
self.async_fn = asyncio.iscoroutinefunction(fn)
# 是否结构化输出
self.structured_output = structured_output
# 输出 schema 及需否包裹
self.output_schema, self.wrap_output = _output_schema_and_wrap(fn, structured_output) if structured_output else (None, False)
# Context 参数名(若有)
self._ctx_param = _find_context_parameter(fn)
# 转换为 Tool 对象
def to_tool(self):
return Tool(name=self.name, description=self.desc or None, input_schema=self.schema, output_schema=self.output_schema)
# 执行工具(自动支持异步),支持注入 Context
def run(self, args, mcp_server=None, request_id=None, progress_token=None, send_notification=None):
if self._ctx_param is not None and mcp_server is not None:
ctx = Context(mcp_server, request_id, send_notification, progress_token)
args = dict(args) if args else {}
args[self._ctx_param] = ctx
if self.async_fn:
return asyncio.run(self.fn(**args))
return self.fn(**args)
# 静态资源封装类
class _Resource:
def __init__(self, uri, fn, mime_type="text/plain"):
# 资源 URI
self.uri = uri
# 回调函数
self.fn = fn
# MIME 类型
self.mime_type = mime_type
# 是否异步
self.async_fn = asyncio.iscoroutinefunction(fn)
# 资源运行,自动支持异步
def run(self):
if self.async_fn:
return asyncio.run(self.fn())
return self.fn()
# 资源模板封装类(支持 URI 参数模板)
class _ResourceTemplate:
def __init__(self, uri_template, fn, mime_type="text/plain"):
# URI 模板
self.uri_template = uri_template
# 生成资源内容的函数
self.fn = fn
# MIME 类型
self.mime_type = mime_type
# 是否异步
self.async_fn = asyncio.iscoroutinefunction(fn)
# 提取函数里除了 _ 开头之外的参数名
sig = inspect.signature(fn)
self.param_names = [n for n in sig.parameters if not n.startswith("_")]
# 检查 URI 是否与模板匹配,并解析参数
def matches(self, uri):
pattern = self.uri_template.replace("{", "(?P<").replace("}", ">[^/]+)")
m = re.match(f"^{pattern}$", uri)
if m:
return {k: unquote(v) for k, v in m.groupdict().items()}
return None
# 执行模板内容生成函数
def run(self, args):
if self.async_fn:
return asyncio.run(self.fn(**args))
return self.fn(**args)
# Prompt 封装
class _Prompt:
"""内部 Prompt 封装类。"""
def __init__(self, fn, name=None, title=None, description=None):
# prompt 生成函数
self.fn = fn
# prompt 名称
self.name = name or fn.__name__
# prompt 标题
self.title = title
# prompt 描述
self.description = description or (fn.__doc__ or "").strip()
# 通用 schema
self.schema = _prompt_schema(fn)
# 是否异步
self.async_fn = asyncio.iscoroutinefunction(fn)
# 从 schema 生成 PromptArgument 列表
args_list = []
if "properties" in self.schema:
required = set(self.schema.get("required", []))
for pname, pinfo in self.schema["properties"].items():
args_list.append(
PromptArgument(
name=pname,
description=pinfo.get("title"),
required=pname in required,
)
)
self.arguments = args_list
# 转成 Prompt 对象
def to_prompt(self):
return Prompt(
name=self.name,
title=self.title,
description=self.description or None,
arguments=self.arguments if self.arguments else None,
)
# prompt 执行
def run(self, args):
if self.async_fn:
return asyncio.run(self.fn(**args))
return self.fn(**args)
# FastMCP 主类
class FastMCP:
def __init__(self, name="mcp-server"):
# 服务器名称
self.name = name
# 工具注册表
self._tools = {}
# 静态资源注册表
self._resources = {}
# 资源模板注册表
self._resource_templates = {}
# prompt 注册表
self._prompts = {}
# 补全处理器(注册后用于 completion/complete 请求)
+ self._completion_handler = None
# 注册工具的装饰器
def tool(self, name=None, description=None, structured_output=True):
def deco(fn):
t = _Tool(fn, name, description, structured_output=structured_output)
self._tools[t.name] = t
return fn
return deco
# 注册资源或模板资源的装饰器
def resource(self, uri, mime_type="text/plain"):
def deco(fn):
# 判断带模板参数还是静态资源
if "{" in uri and "}" in uri:
template = _ResourceTemplate(uri, fn, mime_type)
self._resource_templates[uri] = template
else:
res = _Resource(uri, fn, mime_type)
self._resources[uri] = res
return fn
return deco
# 注册补全处理器的装饰器
+ def completion(self):
+ """注册参数补全处理器,用于 Prompt 或资源模板参数的自动补全。"""
+ def deco(fn):
+ self._completion_handler = fn
+ return fn
+ return deco
# 注册 Prompt 的装饰器
def prompt(self, name=None, title=None, description=None):
"""注册 Prompt 的装饰器。"""
def deco(fn):
p = _Prompt(fn, name=name, title=title, description=description)
self._prompts[p.name] = p
return fn
return deco
# 核心 RPC 方法分发
def _handle(self, req):
# 获取方法名、参数和请求 id
method, params, rid = req.method, req.params or {}, req.id
# 初始化请求
if method == "initialize":
caps = ServerCapabilities(
tools=ToolsCapability(),
resources=ResourcesCapability(),
prompts=PromptsCapability() if self._prompts else None,
+ completions=CompletionsCapability() if self._completion_handler else None,
)
r = InitializeResult(
protocol_version=LATEST_PROTOCOL_VERSION,
capabilities=caps,
server_info=Implementation(name=self.name, version="0.1.0"),
)
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 工具列表请求
if method == "tools/list":
r = ListToolsResult(tools=[t.to_tool() for t in self._tools.values()])
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 工具调用请求
if method == "tools/call":
p = CallToolRequestParams.model_validate(params, by_name=False)
t = self._tools.get(p.name)
if not t:
return JSONRPCError(
jsonrpc="2.0",
id=rid,
error=ErrorData(code=-32602, message=f"Unknown tool: {p.name}")
)
# 从 meta/_meta 提取 progressToken,用于发送进度/日志通知
meta = p.meta or {}
progress_token = meta.get("progressToken") or meta.get("progress_token")
notifications = []
def _send_notification(payload):
method_name = payload.get("method", "")
params = payload.get("params")
notifications.append(JSONRPCNotification(jsonrpc="2.0", method=method_name, params=params))
try:
out = t.run(
p.arguments or {},
mcp_server=self,
request_id=rid,
progress_token=progress_token,
send_notification=_send_notification,
)
# 如果直接返回的是 CallToolResult
if isinstance(out, CallToolResult):
r = out
else:
struct = None
# 结构化输出
if t.output_schema is not None:
struct = _to_structured(out, t.output_schema, t.wrap_output)
# 字符串直接用文本包装
if isinstance(out, str):
c = [TextContent(text=out)]
elif out is None:
c = []
elif struct is not None:
# 结构化结果按 JSON 格式化后返回
c = [TextContent(text=json.dumps(struct, ensure_ascii=False, indent=2))]
else:
# 普通对象尝试转 json,否则转字符串
try:
if PydanticBaseModel and isinstance(out, PydanticBaseModel):
text = json.dumps(out.model_dump(mode="json"), ensure_ascii=False, indent=2)
elif isinstance(out, dict):
text = json.dumps(out, ensure_ascii=False, indent=2)
else:
text = str(out)
except Exception:
text = str(out)
c = [TextContent(text=text)]
r = CallToolResult(content=c, structured_content=struct)
except Exception as e:
r = CallToolResult(content=[TextContent(text=str(e))], is_error=True)
resp = JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
if notifications:
return (notifications, resp)
return resp
# prompts/list 请求
if method == "prompts/list":
prompts_list = [p.to_prompt() for p in self._prompts.values()]
r = ListPromptsResult(prompts=prompts_list)
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# prompts/get 请求
if method == "prompts/get":
p = GetPromptRequestParams.model_validate(params, by_name=False)
prompt_obj = self._prompts.get(p.name)
if not prompt_obj:
return JSONRPCError(
jsonrpc="2.0",
id=rid,
error=ErrorData(code=-32602, message=f"Unknown prompt: {p.name}")
)
try:
args = p.arguments or {}
result = prompt_obj.run(args)
messages = []
# 单条消息包装为列表
if not isinstance(result, (list, tuple)):
result = [result]
for msg in result:
# 若为内置的 Message 对象
if isinstance(msg, prompts.base.Message):
content = msg.content
if isinstance(content, str):
content = TextContent(type="text", text=content)
messages.append(PromptMessage(role=msg.role, content=content))
# 字符串消息按 user 角色组装
elif isinstance(msg, str):
messages.append(PromptMessage(role="user", content=TextContent(type="text", text=msg)))
# dict 消息,读 role 和 content
elif isinstance(msg, dict):
role = msg.get("role", "user")
cnt = msg.get("content", "")
if isinstance(cnt, dict) and cnt.get("type") == "text":
content = TextContent(**cnt)
else:
content = TextContent(type="text", text=str(cnt) if not isinstance(cnt, str) else cnt)
messages.append(PromptMessage(role=role, content=content))
# 其它均归为 user 文本
else:
messages.append(PromptMessage(role="user", content=TextContent(type="text", text=str(msg))))
r = GetPromptResult(description=prompt_obj.description, messages=messages)
except Exception as e:
return JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=-32603, message=str(e)))
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 资源静态列表
if method == "resources/list":
resources = [
Resource(uri=u, name=u, mime_type=r.mime_type)
for u, r in self._resources.items()
]
r = ListResourcesResult(resources=resources)
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 资源模板列表
if method == "resources/templates/list":
templates = [
ResourceTemplate(uri_template=u, name=u, mime_type=t.mime_type)
for u, t in self._resource_templates.items()
]
r = ListResourceTemplatesResult(resource_templates=templates)
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 处理补全请求 completion/complete
+ if method == "completion/complete":
# 如果没有补全处理器,返回方法未找到错误
+ if not self._completion_handler:
+ return JSONRPCError(
+ jsonrpc="2.0",
+ id=rid,
+ error=ErrorData(code=-32601, message="Method not found: completion/complete"),
+ )
# 校验并解析补全请求参数
+ p = CompleteRequestParams.model_validate(params, by_name=False)
+ try:
# 获取补全处理函数
+ fn = self._completion_handler
# 如果处理函数是协程,则用 asyncio.run 执行,否则直接调用
+ result = (
+ asyncio.run(fn(p.ref, p.argument, p.context))
+ if asyncio.iscoroutinefunction(fn)
+ else fn(p.ref, p.argument, p.context)
+ )
# 若处理函数无结果则返回空补全
+ if result is None:
+ result = Completion(values=[], total=None, has_more=None)
# 封装补全响应对象
+ r = CompleteResult(completion=result)
# 构造并返回 JSONRPCResponse 响应
+ return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
+ except Exception as e:
# 捕获异常并返回内部错误
+ return JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=-32603, message=str(e)))
# 读取资源接口
if method == "resources/read":
p = ReadResourceRequestParams.model_validate(params, by_name=False)
uri_str = str(p.uri)
try:
# 静态资源优先
if res := self._resources.get(uri_str):
out = res.run()
content = TextResourceContents(uri=uri_str, text=str(out), mime_type=res.mime_type)
r = ReadResourceResult(contents=[content])
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 匹配模板资源
for template in self._resource_templates.values():
if args := template.matches(uri_str):
out = template.run(args)
if isinstance(out, bytes):
content = BlobResourceContents(
uri=uri_str,
blob=base64.b64encode(out).decode(),
mime_type=template.mime_type or "application/octet-stream",
)
else:
content = TextResourceContents(
uri=uri_str,
text=str(out),
mime_type=template.mime_type or "text/plain",
)
r = ReadResourceResult(contents=[content])
return JSONRPCResponse(jsonrpc="2.0", id=rid, result=r.model_dump(by_alias=True, exclude_none=True))
# 找不到资源
return JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=-32602, message=f"Unknown resource: {uri_str}"))
except Exception as e:
return JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=-32603, message=str(e)))
# 未知方法
return JSONRPCError(jsonrpc="2.0", id=rid, error=ErrorData(code=-32601, message=f"Method not found: {method}"))
# 消息包装与请求
def _handle_msg(self, msg):
# 非 SessionMessage 类型忽略
if not isinstance(msg, SessionMessage):
return None
m = msg.message
# 必须是带 id 的 jsonrpc 请求
if not isinstance(m, JSONRPCRequest) or getattr(m, "id", None) is None:
return None
#print("[Server] Request:", m.model_dump_json(by_alias=True, exclude_unset=True), file=sys.stderr)
try:
resp = self._handle(m)
#print("[Server] Response:", resp.model_dump_json(by_alias=True, exclude_unset=True), file=sys.stderr)
return resp
except Exception as e:
err = JSONRPCError(jsonrpc="2.0", id=m.id, error=ErrorData(code=-32603, message=str(e)))
#print("[Server] Response (error):", err.model_dump_json(by_alias=True, exclude_unset=True), file=sys.stderr)
return err
# 运行服务器主逻辑
def run(self, transport="stdio", host: str = "127.0.0.1", port: int = 8000):
# 如果传输方式为 stdio,则启动标准输入输出服务器
if transport == "stdio":
stdio.stdio_server(self._handle_msg)
# 如果传输方式为 streamable-http,则启动基于 HTTP 的服务器
elif transport == "streamable-http":
# 导入 Starlette 框架相关模块
from starlette.applications import Starlette
from starlette.routing import Mount
# 导入 streamable_http_app 工厂方法
from mcp_lite.server.streamable_http import streamable_http_app
# 导入 uvicorn 用于启动 ASGI 服务
import uvicorn
# 创建 Streamable HTTP ASGI 应用
app = streamable_http_app(self._handle_msg, path="/")
# 将 /mcp 路径挂载到应用
full_app = Starlette(routes=[Mount("/mcp", app=app)])
# 启动 uvicorn 服务,监听指定 host 和 port
uvicorn.run(full_app, host=host, port=port)
# 如果传输方式不被支持,则抛出异常
else:
raise ValueError(f"unsupported transport: {transport}")
# 明确导出接口
__all__ = ["FastMCP", "Context", "prompts"]
6. types.py #
mcp_lite/types.py
# 从 pydantic 导入 BaseModel、ConfigDict、Field、TypeAdapter、field_validator
from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, field_validator
# 导入 pydantic 的 to_camel 驼峰命名生成器
from pydantic.alias_generators import to_camel
# 导入 Any、Literal、Annotated 类型注解
+from typing import Any, Literal, Annotated
# 定义 RequestId 类型,既可以是 int 也可以是 str
RequestId = int | str
# 定义 MCP 的基础模型类,支持驼峰命名和按名称填充
class MCPModel(BaseModel):
# 指定 Pydantic 模型配置:使用驼峰形式命名和按名称填充
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
# 定义客户端能力结构体
class ClientCapabilities(MCPModel):
# 可选字段:客户端实验性能力扩展,键为 str,值为字典
experimental: dict[str, dict[str, Any]] | None = None
# 定义服务器或客户端的实现信息结构体
class Implementation(MCPModel):
# 实现的名称
name: str = ""
# 实现的版本号
version: str = ""
# 可选字段:人类可读的标题
title: str | None = None
# 可选字段:实现的描述
description: str | None = None
# 定义初始化请求参数结构体
class InitializeRequestParams(MCPModel):
# 协议版本号
protocol_version: str = ""
# 可选字段:客户端能力描述
capabilities: ClientCapabilities = None
# 可选字段:客户端实现信息
client_info: Implementation = None
# 定义初始化请求结构体
class InitializeRequest(MCPModel):
# 方法名,固定为 "initialize"
method: Literal["initialize"] = "initialize"
# 可选字段:参数,类型为 InitializeRequestParams
params: InitializeRequestParams = None
# 当前协议的最新版本号
LATEST_PROTOCOL_VERSION = "2024-11-05"
# 定义工具相关能力结构体
class ToolsCapability(MCPModel):
# 工具列表是否发生变化,可选布尔类型
list_changed: bool | None = None
# 定义资源相关能力结构体
class ResourcesCapability(MCPModel):
# 是否支持资源订阅
subscribe: bool | None = None
# 资源列表是否变化通知
list_changed: bool | None = None
# 定义 Prompt 相关能力结构体
class PromptsCapability(MCPModel):
list_changed: bool | None = None
# 定义补全能力描述(服务端声明支持补全时使用)
+class CompletionsCapability(MCPModel):
+ pass
# 定义服务端能力描述结构体
class ServerCapabilities(MCPModel):
# 可选字段:实验性能力扩展
experimental: dict[str, dict[str, Any]] | None = None
# 可选字段:工具能力
tools: ToolsCapability | None = None
# 可选字段:资源能力
resources: ResourcesCapability | None = None
# 可选字段:Prompt 能力
prompts: PromptsCapability | None = None
# 可选字段:补全能力(注册了 @completion 时声明)
+ completions: CompletionsCapability | None = None
# 定义初始化响应结构体
class InitializeResult(MCPModel):
# 协议版本号
protocol_version: str = ""
# 可选字段:服务端能力描述
capabilities: ServerCapabilities = None
# 可选字段:服务端实现信息
server_info: Implementation = None
# 可选字段:初始化说明信息
instructions: str | None = None
# 定义客户端初始化完成通知结构体
class InitializedNotification(MCPModel):
# 方法名,固定为 "notifications/initialized"
method: Literal["notifications/initialized"] = "notifications/initialized"
# 可选字段:通知参数,可以为字典或 None
params: dict[str, Any] | None = None
# 定义 JSONRPC 请求的数据结构
class JSONRPCRequest(BaseModel):
# jsonrpc 协议版本,固定为 "2.0"
jsonrpc: Literal["2.0"] = "2.0"
# 请求 ID,可以为 int 或 str 类型
id: RequestId = None
# 方法名称,字符串类型
method: str = ""
# 方法参数,为一个字典或 None
params: dict[str, Any] | None = None
# 定义 JSONRPC 通知的数据结构(没有 id 字段)
class JSONRPCNotification(BaseModel):
# jsonrpc 协议版本,固定为 "2.0"
jsonrpc: Literal["2.0"] = "2.0"
# 通知的方法名称
method: str = ""
# 通知参数,可以为字典或者 None
params: dict[str, Any] | None = None
# 定义 JSONRPC 响应的数据结构
class JSONRPCResponse(BaseModel):
# jsonrpc 协议版本,固定为 "2.0"
jsonrpc: Literal["2.0"] = "2.0"
# 响应的 ID,需要与请求 ID 匹配
id: RequestId = None
# 响应结果,可以为字典或 None
result: dict[str, Any] = None
# 定义错误的数据结构
class ErrorData(BaseModel):
# 错误码,默认值为 0
code: int = 0
# 错误信息,默认值为空字符串
message: str = ""
# 附加的错误数据,可以为任意类型或 None
data: Any = None
# 定义 JSONRPC 错误消息的数据结构
class JSONRPCError(BaseModel):
# jsonrpc 协议版本,固定为 "2.0"
jsonrpc: Literal["2.0"] = "2.0"
# 错误对应的请求 ID,可以为 None
id: RequestId | None = None
# 错误的详细信息,类型为 ErrorData
error: ErrorData = None
# 定义所有 JSONRPC 消息的联合类型
JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError
# 进度通知参数(notifications/progress)
class ProgressNotificationParams(MCPModel):
progress_token: str | int = ""
progress: float = 0.0
total: float | None = None
message: str | None = None
# 日志消息通知参数(notifications/message)
class LoggingMessageNotificationParams(MCPModel):
level: str = "info"
data: Any = None
logger: str | None = None
# 定义 JSONRPC 消息适配器,用于类型自动推断和校验
jsonrpc_message_adapter = TypeAdapter(JSONRPCMessage)
# 定义工具结果中的文本内容块
class TextContent(MCPModel):
type: Literal["text"] = "text"
text: str = ""
# 定义工具描述数据结构体
class Tool(MCPModel):
# 工具名称
name: str = ""
# 可选字段:工具描述
description: str | None = None
# 工具输入参数的 schema,默认为空字典
input_schema: dict[str, Any] = Field(default_factory=dict)
# 可选字段:工具输出 schema
output_schema: dict[str, Any] | None = None
# 定义获取工具列表请求结构体
class ListToolsRequest(MCPModel):
# 方法名,固定为 "tools/list"
method: Literal["tools/list"] = "tools/list"
# 可选字段:参数,可以为字典或 None
params: dict[str, Any] | None = None
# 定义获取工具列表响应结构体
class ListToolsResult(MCPModel):
# 工具列表,默认为空列表
tools: list[Tool] = []
# 可选字段:分页游标,可为 None
next_cursor: str | None = None
# 定义资源元数据结构体
class Resource(MCPModel):
# 资源 URI
uri: str = ""
# 可选:资源名称
name: str | None = None
# 可选:人类可读标题
title: str | None = None
# 可选:资源描述
description: str | None = None
# 可选:MIME 类型
mime_type: str | None = None
# 定义资源模板结构体
class ResourceTemplate(MCPModel):
# URI 模板,如 greeting://{name}
uri_template: str = ""
# 可选:模板名称
name: str | None = None
# 可选:人类可读标题
title: str | None = None
# 可选:模板描述
description: str | None = None
# 可选:MIME 类型
mime_type: str | None = None
# 定义 resources/list 请求结构体
class ListResourcesRequest(MCPModel):
method: Literal["resources/list"] = "resources/list"
params: dict[str, Any] | None = None
# 定义 resources/list 响应结构体
class ListResourcesResult(MCPModel):
resources: list[Resource] = []
next_cursor: str | None = None
# 定义 resources/templates/list 请求结构体
class ListResourceTemplatesRequest(MCPModel):
method: Literal["resources/templates/list"] = "resources/templates/list"
params: dict[str, Any] | None = None
# 定义 resources/templates/list 响应结构体
class ListResourceTemplatesResult(MCPModel):
resource_templates: list[ResourceTemplate] = []
next_cursor: str | None = None
# 定义 resources/read 请求参数结构体
class ReadResourceRequestParams(MCPModel):
uri: str = ""
# 定义 resources/read 请求结构体
class ReadResourceRequest(MCPModel):
method: Literal["resources/read"] = "resources/read"
params: ReadResourceRequestParams = None
# 定义资源内容基类(文本)
class TextResourceContents(MCPModel):
uri: str = ""
mime_type: str | None = None
text: str = ""
# 定义资源内容基类(二进制)
class BlobResourceContents(MCPModel):
uri: str = ""
mime_type: str | None = None
blob: str = "" # base64 编码
# 定义 resources/read 响应结构体
class ReadResourceResult(MCPModel):
contents: list[TextResourceContents | BlobResourceContents] = []
# 定义 Prompt 参数结构体
# 定义代表 Prompt 参数的模型
class PromptArgument(MCPModel):
# 参数名称
name: str = ""
# 参数描述,可为 None
description: str | None = None
# 是否为必填参数,可为 None
required: bool | None = None
# 定义 Prompt 元数据结构体
# 定义代表 Prompt 元数据的模型
class Prompt(MCPModel):
# Prompt 名称
name: str = ""
# Prompt 描述,可为 None
description: str | None = None
# Prompt 参数列表,可为 None
arguments: list[PromptArgument] | None = None
# Prompt 标题,可为 None
title: str | None = None
# 定义 prompts/list 请求结构体
# 定义 prompts/list 请求的数据模型
class ListPromptsRequest(MCPModel):
# 固定方法字段
method: Literal["prompts/list"] = "prompts/list"
# 请求参数,可为 None
params: dict[str, Any] | None = None
# 定义 prompts/list 响应结构体
# 定义 prompts/list 响应的数据模型
class ListPromptsResult(MCPModel):
# 返回的 Prompt 列表
prompts: list[Prompt] = []
# 下一页游标,可为 None
next_cursor: str | None = None
# 定义 prompts/get 请求参数结构体
# 定义 prompts/get 的参数模型
class GetPromptRequestParams(MCPModel):
# Prompt 名称
name: str = ""
# 传递给 Prompt 的参数,可为 None
arguments: dict[str, str] | None = None
# 定义 prompts/get 请求结构体
# 定义 prompts/get 请求的数据模型
class GetPromptRequest(MCPModel):
# 固定方法字段
method: Literal["prompts/get"] = "prompts/get"
# 请求参数,可为 None
params: GetPromptRequestParams | None = None
# 定义 Prompt 消息结构体(role + content)
# 定义表示 Prompt 里的单条消息的数据模型
class PromptMessage(MCPModel):
# 消息角色(user 或 assistant)
role: Literal["user", "assistant"] = "user"
# 消息内容,可以是 TextContent 或字典,默认为空文本
content: TextContent | dict[str, Any] = Field(default_factory=lambda: TextContent(text=""))
# 字段校验器:在模型初始化前解析 content 字段
@field_validator("content", mode="before")
@classmethod
def _parse_content(cls, v):
# 如果是字典且 type 为 "text",转换为 TextContent 实例
if isinstance(v, dict) and v.get("type") == "text":
return TextContent(text=v.get("text", ""))
# 否则原样返回
return v
# 定义 prompts/get 响应结构体
# 定义 prompts/get 的响应数据模型
class GetPromptResult(MCPModel):
# Prompt 的描述,可为 None
description: str | None = None
# Prompt 返回的消息列表
messages: list[PromptMessage] = []
# 定义 Prompt 引用类型(用于补全请求)
+class PromptReference(MCPModel):
# 类型字段,固定为 "ref/prompt"
+ type: Literal["ref/prompt"] = "ref/prompt"
# Prompt 名称
+ name: str = ""
# 定义资源模板引用类型(用于补全请求)
+class ResourceTemplateReference(MCPModel):
# 类型字段,固定为 "ref/resource"
+ type: Literal["ref/resource"] = "ref/resource"
# 资源模板的 URI
+ uri: str = ""
# 定义补全参数类型
+class CompletionArgument(MCPModel):
# 参数名称
+ name: str = ""
# 参数值
+ value: str = ""
# 定义补全上下文类型(已解析的其它参数)
+class CompletionContext(MCPModel):
# 补全上下文参数,字典类型,可能为 None
+ arguments: dict[str, str] | None = None
# 定义补全结果内容类型
+class Completion(MCPModel):
# 候选内容列表,默认为空列表
+ values: list[str] = Field(default_factory=list)
# 总数,可为 None
+ total: int | None = None
# 是否有更多结果,可为 None
+ has_more: bool | None = None
# 定义 completion/complete 请求参数
+class CompleteRequestParams(MCPModel):
# 引用字段,用 type 字段区分 PromptReference 与 ResourceTemplateReference
+ ref: Annotated[
+ PromptReference | ResourceTemplateReference,
+ Field(discriminator="type"),
+ ] = None
# 需要补全的参数
+ argument: CompletionArgument = None
# 辅助的上下文字段,可为 None
+ context: CompletionContext | None = None
# 定义 completion/complete 请求
+class CompleteRequest(MCPModel):
# 方法名,固定为 "completion/complete"
+ method: Literal["completion/complete"] = "completion/complete"
# 请求参数
+ params: CompleteRequestParams = None
# 定义 completion/complete 响应
+class CompleteResult(MCPModel):
# 补全结果,类型为 Completion
+ completion: Completion = None
# 定义调用工具请求参数结构体
class CallToolRequestParams(MCPModel):
# 工具名称
name: str = ""
# 可选字段:输入参数,为字典类型或 None
arguments: dict[str, Any] | None = None
# 可选:元数据,含 progressToken 时服务端可发送进度通知
meta: dict[str, Any] | None = Field(default=None, alias="_meta")
# 定义调用工具请求结构体
class CallToolRequest(MCPModel):
# 方法名,固定为 "tools/call"
method: Literal["tools/call"] = "tools/call"
# 可选字段:参数,类型为 CallToolRequestParams
params: CallToolRequestParams = None
# 定义调用工具响应结构体
class CallToolResult(MCPModel):
# 内容字段,由 TextContent 或字典组成的列表,默认为空列表
content: list[TextContent | dict[str, Any]] = Field(default_factory=list)
# 结构化内容字段,可为字典或 None
structured_content: dict[str, Any] | None = None
# 错误标志字段,标识是否为错误结果,默认为 False
is_error: bool = False
# 针对 content 字段的字段校验器,模型初始化前调用
@field_validator("content", mode="before")
@classmethod
def _parse_content(cls, v):
# 如果传入的值不是列表,直接返回
if not isinstance(v, list):
return v
# 初始化输出列表
out = []
# 遍历每一项
for item in v:
# 如果项是字典且类型为 "text",转换为 TextContent 实例
if isinstance(item, dict) and item.get("type") == "text":
out.append(TextContent(text=item.get("text", "")))
# 否则,原样加入输出列表
else:
out.append(item)
# 返回处理后的列表
return out 7.执行流程 #
7.1 功能概述 #
参数补全用于在用户输入 Prompt 或资源模板参数时,由服务端根据当前输入和上下文返回候选值,实现类似 IDE 的自动补全。
7.2 时序图 #
7.2.1 整体流程 #
sequenceDiagram
autonumber
participant Client as completions_client
participant Session as ClientSession
participant stdio as stdio_client
participant Server as completions_server
participant FastMCP as FastMCP._handle
participant Handler as handle_completion
Client->>Session: initialize()
Session->>stdio: JSON-RPC initialize
stdio->>Server: stdin
Server->>FastMCP: _handle_msg
FastMCP->>FastMCP: initialize 响应
FastMCP-->>Client: InitializeResult (含 completions 能力)
Client->>Session: list_prompts() / list_resource_templates()
Session->>stdio: JSON-RPC
stdio->>Server: stdin
Server->>FastMCP: _handle
FastMCP-->>Client: ListPromptsResult / ListResourceTemplatesResult
Client->>Session: complete(ref, argument, context_arguments)
Session->>Session: 封装 CompleteRequest
Session->>stdio: JSON-RPC completion/complete
stdio->>Server: stdin (params: ref, argument, context)
Server->>FastMCP: _handle_msg -> _handle
FastMCP->>FastMCP: CompleteRequestParams.model_validate(params)
Note over FastMCP: discriminator="type" 区分 ref 类型
FastMCP->>Handler: handle_completion(p.ref, p.argument, p.context)
Handler->>Handler: isinstance(ref, PromptReference) 或 ResourceTemplateReference
Handler->>Handler: 按 argument.name 过滤并返回 Completion
Handler-->>FastMCP: Completion
FastMCP->>FastMCP: CompleteResult(completion=result)
FastMCP-->>stdio: JSONRPCResponse
stdio-->>Session: stdout
Session-->>Client: CompleteResult
7.2.2 单次补全请求的详细流程 #
sequenceDiagram
autonumber
participant Client as completions_client
participant Session as ClientSession
participant write_q as write_q
participant read_q as read_q
participant ServerProc as completions_server 子进程
participant Handler as handle_completion
Client->>Session: complete(ref=ResourceTemplateReference(uri="github://{owner}/{repo}"), argument={"name":"owner","value":"mod"})
Session->>Session: 构建 CompletionContext / CompletionArgument
Session->>Session: 构建 CompleteRequest(params=CompleteRequestParams(...))
Session->>write_q: SessionMessage(JSONRPCRequest method="completion/complete")
Note over Session: _request 阻塞在 read_q.get()
ServerProc->>ServerProc: 从 stdin 读取 JSON
ServerProc->>ServerProc: jsonrpc_message_adapter.validate_json
ServerProc->>Handler: _handle_msg -> _handle(m)
Handler->>Handler: method == "completion/complete"
Handler->>Handler: CompleteRequestParams.model_validate(params, by_name=False)
Note over Handler: ref 为 dict {"type":"ref/resource","uri":"github://{owner}/{repo}"}
Note over Handler: discriminator 按 type 解析为 ResourceTemplateReference
Handler->>Handler: p.ref 是 ResourceTemplateReference 实例
Handler->>Handler: fn = _completion_handler (handle_completion)
Handler->>Handler: await fn(p.ref, p.argument, p.context) // 修复点:使用 await 而不是 asyncio.run
Handler->>Handler: isinstance(ref, ResourceTemplateReference) == True
Handler->>Handler: ref.uri == "github://{owner}/{repo}"
Handler->>Handler: argument.name == "owner" -> 过滤 owners
Handler-->>Handler: 返回 Completion(values=["modelcontextprotocol"])
Handler->>Handler: 构造 CompleteResult(completion=...)
Handler->>ServerProc: 返回 JSONRPCResponse
ServerProc->>read_q: 通过 stdout 写入 JSON 响应
read_q->>Session: 从队列获取 result
Session->>Session: CompleteResult.model_validate(result)
Session-->>Client: 返回 CompleteResult(completion.values=["modelcontextprotocol"])
7.2.3 补全处理器内部分支逻辑 #
sequenceDiagram
participant Client as 调用者
participant Handler as handle_completion
participant LangStore as LanguageStore
participant StyleStore as StyleStore
participant OwnerStore as OwnerStore
participant RepoStore as RepoStore
Client->>Handler: 调用(ref, argument, context)
alt isinstance ref, PromptReference
alt ref.name == "code_style_guide"
alt argument.name == "language"
Handler->>LangStore: 过滤 languages 列表
LangStore-->>Handler: 返回过滤结果
Handler-->>Client: 返回 Completion(values=过滤结果)
else argument.name == "style"
Handler->>StyleStore: 过滤 styles 列表
StyleStore-->>Handler: 返回过滤结果
Handler-->>Client: 返回 Completion(values=过滤结果)
else
Handler-->>Client: 返回 None (不支持的参数)
end
else
Handler-->>Client: 返回 None (不支持的 Prompt)
end
else isinstance ref, ResourceTemplateReference
alt ref.uri == "github://{owner}/{repo}"
alt argument.name == "owner"
Handler->>OwnerStore: 过滤 owners 列表
OwnerStore-->>Handler: 返回过滤结果
Handler-->>Client: 返回 Completion(values=过滤结果)
else argument.name == "repo"
alt context.arguments.owner 存在
Handler->>RepoStore: 按 owner 过滤 repos 列表
RepoStore-->>Handler: 返回过滤结果
Handler-->>Client: 返回 Completion(values=过滤结果)
else
Handler-->>Client: 返回 Completion(values=[]) # owner 缺失,返回空列表
end
else
Handler-->>Client: 返回 None (不支持的参数)
end
else
Handler-->>Client: 返回 None (不支持的 ResourceTemplate)
end
else
Handler-->>Client: 返回 None (不支持的引用类型)
end
7.3 涉及模块与改动 #
7.3.1 客户端 completions_client.py #
作用:演示如何调用补全接口。
流程:
- 用
stdio_client启动completions_server.py子进程 - 创建
ClientSession,执行initialize() - 调用
list_prompts()、list_resource_templates()获取可补全的 Prompt 和资源模板 - 对 Prompt 参数调用
session.complete(ref=PromptReference(...), argument={...}) - 对资源模板参数调用
session.complete(ref=ResourceTemplateReference(...), argument={...}, context_arguments={...})
7.3.2 服务端 completions_server.py #
作用:注册 Prompt、资源模板和补全处理器。
要点:
- `@mcp.prompt()
注册 Promptcode_style_guide(language, style)` - `@mcp.resource("github://{owner}/{repo}")` 注册资源模板
- `@mcp.completion()
注册补全处理器handle_completion(ref, argument, context)` - 补全逻辑:根据
ref类型(PromptReference/ResourceTemplateReference)和argument.name返回过滤后的候选列表
7.3.3 客户端会话 mcp_lite/client/session.py #
新增 complete() 方法:
def complete(self, ref, argument, context_arguments=None):
context = CompletionContext(arguments=context_arguments) if context_arguments else None
arg = argument if isinstance(argument, CompletionArgument) else CompletionArgument(**argument)
return CompleteResult.model_validate(
self._request(CompleteRequest(
params=CompleteRequestParams(ref=ref, argument=arg, context=context)
)),
by_name=False,
)- 将
argument转为CompletionArgument - 将
context_arguments封装为CompletionContext - 发送
completion/complete请求并解析为CompleteResult
7.3.4 FastMCP mcp_lite/server/fastmcp/__init__.py #
改动:
- 增加
_completion_handler和 `@mcp.completion()` 装饰器 - 在
initialize中,若有补全处理器则声明completions能力 - 在
_handle中处理completion/complete:校验参数、调用补全处理器、返回CompleteResult
7.3.5 类型定义 mcp_lite/types.py #
新增类型:
PromptReference(type="ref/prompt",name)ResourceTemplateReference(type="ref/resource",uri)CompletionArgument(name,value)CompletionContext(arguments)Completion(values,total,has_more)CompleteRequestParams、CompleteRequest、CompleteResultCompletionsCapability
重要点:CompleteRequestParams.ref 使用 Field(discriminator="type"),让 Pydantic 根据 type 正确解析为 PromptReference 或 ResourceTemplateReference。