Python 从0到1构建MCP Server & Client

by GobinFan

153 687 downloads Not rated yet
GitHub

About

支持查询主流agent框架技术文档的MCP server(支持stdio和sse两种传输协议), 支持 langchain、llama-index、autogen、agno、openai-agents-sdk、mcp-doc、camel-ai 和 crew-ai

Explore

- Implements both Stdio (local) and SSE (remote) transport protocols
- Provides a get_docs tool that searches and retrieves documentation for eight popular AI libraries
- Uses the Serper API for Google search and BeautifulSoup for web page parsing
- Includes ready-to-use client configurations for Cursor and Cline
- Ships a complete custom Python MCP client using the OpenAI SDK
- Requires only the mcp CLI package, httpx, and BeautifulSoup as dependencies

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name Python 从0到1构建MCP Server & Client
    Command (node, npx, python, etc.)

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

Install UV, create a project directory, install dependencies (mcp[cli], httpx), and write a main.py file that defines the MCP server with the get_docs tool. Run the server locally with uv run main.py for Stdio, or uv run main.py --host 0.0.0.0 --port 8020 for SSE. Configure clients (Cline, Cursor) by adding a JSON block pointing uv --directory <path> run main.py to the MCP server definition.

print("Initialized SSE client...")
print("Listing tools...")
response = await self.session.list_tools()
tools = response.tools
print("\nConnected to server with tools:", [tool.name for tool in tools])

async def cleanup(self):
"""Properly clean up the session and streams"""
if self._session_context:
await self._session_context.__aexit__(None, None, None)
if self._streams_context:
await self._streams_context.__aexit__(None, None, None)

async def process_query(self, query: str) -> str:
"""Process a query using OpenAI API and available tools"""
messages = [
{
"role": "user",
"content": query
}
]

response = await self.session.list_tools()
available_tools = [{
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema
}
} for tool in response.tools]

tool_results = []
final_text = []

assistant_message = completion.choices[0].message

if assistant_message.tool_calls:
for tool_call in assistant_message.tool_calls:
tool_name = tool_call.function.name
tool_args = json.loads(tool_call.function.arguments)

result = await self.session.call_tool(tool_name, tool_args)
tool_results.append({"call": tool_name, "result": result})
final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")

messages.extend([
{
"role": "assistant",
"content": None,
"tool_calls": [tool_call]
},
{
"role": "tool",
"tool_call_id": tool_call.id,
"content": result.content[0].text
}
])

print(f"Tool {tool_name} returned: {result.content[0].text}")
print("messages", messages)

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "python \u4ece0\u52301\u6784\u5efamcp server & client": {
            "python-mcp-server-client": {
                "command": "uv",
                "args": [
                    "init",
                    "mcp-server"
                ]
            }
        }
    }
}

McpServers

{
    "python-mcp-server-client": {
        "command": "uv",
        "args": [
            "init",
            "mcp-server"
        ]
    }
}

中文 | English

简介

MCP Server 是实现模型上下文协议(MCP)的服务器,旨在为 AI 模型提供一个标准化接口,连接外部数据源和工具,例如文件系统、数据库或 API。

image

MCP 的优势

在 MCP 出现前,AI 调用工具基本通过 Function Call 完成,存在以下问题:

1. 不同的大模型厂商 Function Call 格式不一致
2. 大量 API 工具的输入和输出格式不一致,封装管理繁琐

image

MCP 相当于一个统一的 USB-C,不仅统一了不同大模型厂商的 Function Call 格式,也对相关工具的封装进行了统一。

MCP 传输协议

目前 MCP 支持两种主要的传输协议:

1. Stdio 传输协议
- 针对本地使用
- 需要在用户本地安装命令行工具
- 对运行环境有特定要求

2. SSE(Server-Sent Events)传输协议
- 针对云服务部署
- 基于 HTTP 长连接实现

项目结构

MCP Server

- Stdio 传输协议(本地) - SSE 传输协议(远程)

MCP Client(客户端)

- 自建客户端(Python) - Cursor - Cline

环境配置

1. 安装 UV 包

MacOS/Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

Windows:

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

2. 初始化项目

```bash

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.

Videos about Python 从0到1构建MCP Server & Client

Relevant YouTube tutorials, setups, and demos