MCP 快速开始

1. 简介

MCP (Model Context Protocol) 是一个开放协议,规范了应用程序如何向大语言模型提供上下文。标准化 AI 应用和外部数据源的连接,类似于使用 REST 去标准化网络应用。可将 MCP 服务器视为 API 的封装层。避免直接对接复杂的 API 接口,而是让 MCP 服务器代为处理。

2. MCP 架构

MCP 采用 Client-Server 架构。

1. 基本概念:

  1. Host: 希望使用 MCP 去访问数据的大模型应用
  2. MCP Server: 通过 MCP 去暴露特定功能的程序
  3. MCP Client: 在 Host 内部与 MCP Server 建立一对一的联系

2. Context 类型:

  1. Tools: 定义大模型可以调用的外部功能,例如搜索引擎、计算器
  2. Resources: 可访问的数据资源或上下文内容,例如文档、数据库
  3. prompts: 是系统预设的指令或对话结构模板
    • 用途例子: 假如用户输入 “请将 report.pdf 转为 Markdown 格式”, 那么大模型可能不能清晰的了解用户的需求, 即不清晰的了解 Markdown 的格式。那么可以将用户输入转为 “你是一个文档转换专家, 你的任务是…, Markdown 的格式是…”

Python 示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 1. Tool
@mcp.tool()
def add(a: int, b: int) -> int:
"""
Args:
a: First number to add
b: Second number to add

Returns:
The sum of the two numbers
"""
return a + b

# 2. Resource
# a. Direct (直接访问某特定资源)
@mcp.resource(
"docs://documents",
mime_type="application/json"
)
def list_docs():
# Return a list of document names

# b. Templated (通过参数选择特定资源)
@mcp.resource(
"docs://documents/{doc_id}",
mime_type="text/plain"
)
def fetch_doc(doc_id: str):
# Return the contents of a doc

# 3. Prompt
@mcp.prompt(
name="format",
description="Rewrites the contents of a document in Markdown format"
)
def format_document(
doc_id: str,
) -> list[base.Message]:
# Return a list of messages

3. 通信生命周期

  1. 初始化: Client 对 Server 发起初始化请求, Server 进行初始化回应, Client 最后再发送通知确认初始化完成
  2. 信息交换: Client 向客户端发送 Request, Server 回应 Response
  3. 终止: 任何一方都可以终止连接

4. 信息传输

两种方式 (都使用 JSON-RPC 2.0):
1. Stdio: 适用于 MCP Server 在本地的情况
Client 将 Server 以子进程的方式启动, 然后为自己所用
Client 和 Server 之间使用标准输入输出流进行读写

2. Streamable HTTP: 适用于 MCP Server 在远程的情况
Server 需要提前启动, 为 Client 的使用做好准备
Client 和 Server 之间使用 HTTP 进行请求与响应

3. 创建 MCP Server

1. 安装

1
pip install "mcp[cli]"

2. 完整示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Math") # 指定 MCP Server Name

@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b

@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers"""
return a * b

if __name__ == "__main__":
mcp.run(transport="stdio") # 本地 Server 一般使用 stdio

4. MCP Inspector (MCP 检查器)

MCP Inspector 是一个交互式的开发工具,用于测试和调试 MCP 服务器

1
2
cd <目录>
npx @modelcontextprotocol/inspector uv run <文件名>

连接失败, 原因暂时未知