Top AI Repos — open-source AI, indexed and scored
Top AI Repos tracks AI repositories on GitHub and answers two different questions about each one: is it moving right now, and would you bet a product on it.
Top AI Repos tracks AI repositories on GitHub and answers two different questions about each one: is it moving right now, and would you bet a product on it.
Model Context Protocol(MCP) 编程极速入门
| Date | Stars |
|---|---|
| 2026-07-31 | 3551 |
| 2026-08-03 | 3551 |
| 2026-08-04 | 3554 |
| 2026-08-06 | 3554 |
Today
— stars today
This week
— stars this week
This month
— stars this month
Momentum
0.0
growth rate 0.00%/day
# Model Context Protocol(MCP) 编程极速入门
[TOC]
## 简介
模型上下文协议(MCP)是一个创新的开源协议,它重新定义了大语言模型(LLM)与外部世界的互动方式。MCP 提供了一种标准化方法,使任意大语言模型能够轻松连接各种数据源和工具,实现信息的无缝访问和处理。MCP 就像是 AI 应用程序的 USB-C 接口,为 AI 模型提供了一种标准化的方式来连接不同的数据源和工具。

MCP 有以下几个核心功能:
- Resources 资源
- Prompts 提示词
- Tools 工具
- Sampling 采样
- Roots 根目录
- Transports 传输层
因为大部分功能其实都是服务于 Claude 客户端的,本文更希望编写的 MCP 服务器服务与通用大语言模型,所以本文将会主要以“工具”为重点,其他功能会放到最后进行简单讲解。
其中 MCP 的传输层支持了 2 种协议的实现:stdio(标准输入/输出)和 SSE(服务器发送事件),因为 stdio 更为常用,所以本文会以 stdio 为例进行讲解。
本文将会使用 3.11 的 Python 版本,并使用 uv 来管理 Python 项目。同时代码将会在文末放到 Github 上,废话不多说,我们这就开始吧~
## 开发 MCP 服务器
在这一小节中,我们将会实现一个用于网络搜索的服务器。首先,我们先来通过 uv 初始化我们的项目。
> uv 官方文档:https://docs.astral.sh/uv/
```shell
# 初始化项目
uv init mcp_getting_started
cd mcp_getting_started
# 创建虚拟环境并进入虚拟环境
uv venv
.venv\Scripts\activate.bat
# 安装依赖
uv add "mcp[cli]" httpx openai
```
然后我们来创建一个叫 `web_search.py` 文件,来实现我们的服务。MCP 为我们提供了2个对象:`mcp.server.FastMCP` 和 `mcp.server.Server`,`mcp.server.FastMCP` 是更高层的封装,我们这里就来使用它。
```python
import httpx
from mcp.server import FastMCP
# # 初始化 FastMCP 服务器
app = FastMCP('web-search')
```
实现执行的方法非常简单,MCP 为我们提供了一个 `@mcp.tool()` 我们只需要将实现函数用这个装饰器装饰即可。函数名称将作为工具名称,参数将作为工具参数,并通过注释来描述工具与参数,以及返回值。
这里我们直接使用智谱的接口,它这个接口不仅能帮我们搜索到相关的结果链接,并帮我们生成了对应链接中文章总结后的内容的,~~并且现阶段是免费的~~(目前已经开始收费,0.03元/次),非常适合我们。
>官方文档:https://bigmodel.cn/dev/api/search-tool/web-search-pro
>
>API Key 生成地址:https://bigmodel.cn/usercenter/proj-mgmt/apikeys
```python
@app.tool()
async def web_search(query: str) -> str:
"""
搜索互联网内容
Args:
query: 要搜索内容
Returns:
搜索结果的总结
"""
async with httpx.AsyncClient() as client:
response = await client.post(
'https://open.bigmodel.cn/api/paas/v4/tools',
headers={'Authorization': '换成你自己的API KEY'},
json={
'tool': 'web-search-pro',
'messages': [
{'role': 'user', 'content': query}
],
'stream': False
}
)
res_data = []
for choice in response.json()['choices']:
for message in choice['message']['tool_calls']:
search_results = message.get('search_result')
if not search_results:
continue
for result in search_results:
res_data.append(result['content'])
return '\n\n\n'.join(res_data)
```
最后,我们来添加运行服务器的代码。
```python
if __name__ == "__main__":
app.run(transport='stdio')
```
## 调试 MCP 服务器
此时,我们就完成了 MCP 服务端的编写。下面,我们来使用官方提供的 `Inspector` 可视化工具来调试我们的服务器。
我们可以通过两种方法来运行`Inspector`:
> 请先确保已经安装了 node 环境。
通过 npx:
```shell
npx -y @modelcontextprotocol/inspector <command> <arg1> <arg2>
```
我们的这个代码运行命令为:
```shell
npx -y @modelcontextprotocol/inspector uv run web_search.py
```
通过 mcp dev 来运行:
```shell
mcp dev PYTHONFILE
```
我们的这个代码运行命令为:
```shell
mcp dev web_search.py
```
当出现如下提示则代表运行成功。如果提示连接出错,可能是端口被占用,可以看这个 issue 的解决方法:https://github.com/liaokongVFX/MCP-Chinese-Getting-Started-Guide/issues/6

然后,我们打开这个地址,点击左侧的 `Connect` 按钮,即可连接我们刚写的服务。然后我们切换到 `Tools` 栏中,点击 `List Tools` 按钮即可看到我们刚写的工具,我们就可以开始进行调试啦。

## 开发 MCP 客户端
首先,我们先来看看如何在客户端如何调用我们刚才开发的 MCP 服务器中的工具。
```python
import asyncio
from mcp.client.stdio import stdio_client
from mcp import ClientSession, StdioServerParameters
# 为 stdio 连接创建服务器参数
server_params = StdioServerParameters(
# 服务器执行的命令,这里我们使用 uv 来运行 web_search.py
command='uv',
# 运行的参数
args=['run', 'web_search.py'],
# 环境变量,默认为 None,表示使用当前环境变量
# env=None
)
async def main():
# 创建 stdio 客户端
async with stdio_client(server_params) as (stdio, write):
# 创建 ClientSession 对象
async with ClientSession(stdio, write) as session:
# 初始化 ClientSession
await session.initialize()
# 列出可用的Excerpt of 26,291 characters
Read on GitHub了空 · China
23
1
1
Would you bet a product on this? Bounded 0–100 and slow moving.
matched fp:fcedef1280446c6c, topic:mcp, topic:mcp-server, desc:model context protocol