Skip to content
Back to search

python-mcp-server-client

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

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/gobinfan--python-mcp-server-client/badge.svg)](/listings/gobinfan--python-mcp-server-client)

HTML

<a href="/listings/gobinfan--python-mcp-server-client"><img src="/api/listings/gobinfan--python-mcp-server-client/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

**MacOS/Linux:**

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

**Windows:**

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

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 659 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. [![MseeP.ai Security Assessment Badge](https://mseep.net/pr/gobinfan-python-mcp-server-client-badge.png)](https://mseep.ai/app/gobinfan-python-mcp-server-client)
  2. # Python 从0到1构建MCP Server & Client
  3. 中文 | [English](README_EN.md)
  4. ## 简介
  5. MCP Server 是实现模型上下文协议(MCP)的服务器,旨在为 AI 模型提供一个标准化接口,连接外部数据源和工具,例如文件系统、数据库或 API。
  6. ![image](https://github.com/user-attachments/assets/7d91b2db-14dd-47c1-93ec-91dbcd3d6797)
  7. ### MCP 的优势
  8. 在 MCP 出现前,AI 调用工具基本通过 Function Call 完成,存在以下问题:
  9. 1. 不同的大模型厂商 Function Call 格式不一致
  10. 2. 大量 API 工具的输入和输出格式不一致,封装管理繁琐
  11. ![image](https://github.com/user-attachments/assets/01b931a3-7406-426f-8d1e-31f50d21c9e4)
  12. MCP 相当于一个统一的 USB-C,不仅统一了不同大模型厂商的 Function Call 格式,也对相关工具的封装进行了统一。
  13. ## MCP 传输协议
  14. 目前 MCP 支持两种主要的传输协议:
  15. 1. **Stdio 传输协议**
  16. - 针对本地使用
  17. - 需要在用户本地安装命令行工具
  18. - 对运行环境有特定要求
  19. 2. **SSE(Server-Sent Events)传输协议**
  20. - 针对云服务部署
  21. - 基于 HTTP 长连接实现
  22. ## 项目结构
  23. ### MCP Server
  24. - Stdio 传输协议(本地)
  25. - SSE 传输协议(远程)
  26. ### MCP Client(客户端)
  27. - 自建客户端(Python)
  28. - Cursor
  29. - Cline
  30. ## 环境配置
  31. ### 1. 安装 UV 包
  32. **MacOS/Linux:**
  33. ```bash
  34. curl -LsSf https://astral.sh/uv/install.sh | sh
  35. ```
  36. **Windows:**
  37. ```powershell
  38. powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  39. ```
  40. ### 2. 初始化项目
  41. ```bash
  42. # 创建项目目录
  43. uv init mcp-server
  44. cd mcp-server
  45. # 创建并激活虚拟环境
  46. uv venv
  47. source .venv/bin/activate # Windows: .venv\Scripts\activate
  48. # 安装依赖
  49. uv add "mcp[cli]" httpx
  50. # 创建服务器实现文件
  51. touch main.py
  52. ```
  53. ## 构建工具函数
  54. ![image](https://github.com/user-attachments/assets/b49e6ac8-9c5d-432d-8a52-48eaa159aaea)
  55. 为了让大模型能访问市面上主流框架的技术文档,我们主要通过用户输入的 query,结合指定 site 特定域名的谷歌搜索进行搜索相关网页,并对相关网页进行解析提取网页文本并返回。
  56. ### 1. 构建相关文档映射字典
  57. ```python
  58. docs_urls = {
  59. "langchain": "python.langchain.com/docs",
  60. "llama-index": "docs.llamaindex.ai/en/stable",
  61. "autogen": "microsoft.github.io/autogen/stable",
  62. "agno": "docs.agno.com",
  63. "openai-agents-sdk": "openai.github.io/openai-agents-python",
  64. "mcp-doc": "modelcontextprotocol.io",
  65. "camel-ai": "docs.camel-ai.org",
  66. "crew-ai": "docs.crewai.com"
  67. }
  68. ```
  69. ### 2. 构建 MCP 工具
  70. ```python
  71. import json
  72. import os
  73. import httpx
  74. from bs4 import BeautifulSoup
  75. from mcp import tool
  76. async def search_web(query: str) -> dict | None:
  77. payload = json.dumps({"q": query, "num": 3})
  78. headers = {
  79. "X-API-KEY": os.getenv("SERPER_API_KEY"),
  80. "Content-Type": "application/json",
  81. }
  82. async with httpx.AsyncClient() as client:
  83. try:
  84. response = await client.post(
  85. SERPER_URL, headers=headers, data=payload, timeout=30.0
  86. )
  87. response.raise_for_status()
  88. return response.json()
  89. except httpx.TimeoutException:
  90. return {"organic": []}
  91. async def fetch_url(url: str):
  92. async with httpx.AsyncClient() as client:
  93. try:
  94. response = await client.get(url, timeout=30.0)
  95. soup = BeautifulSoup(response.text, "html.parser")
  96. text = soup.get_text()
  97. return text
  98. except httpx.TimeoutException:
  99. return "Timeout error"
  100. @tool()
  101. async def get_docs(query: str, library: str):
  102. """
  103. 搜索给定查询和库的最新文档。
  104. 支持 langchain、llama-index、autogen、agno、openai-agents-sdk、mcp-doc、camel-ai 和 crew-ai。
  105. 参数:
  106. query: 要搜索的查询 (例如 "React Agent")
  107. library: 要搜索的库 (例如 "agno")
  108. 返回:
  109. 文档中的文本
  110. """
  111. if library not in docs_urls:
  112. raise ValueError(f"Library {library} not supported by this tool")
  113. query = f"site:{docs_urls[library]} {query}"
  114. results = await search_web(query)
  115. if len(results["organic"]) == 0:
  116. return "No results found"
  117. text = ""
  118. for result in results["organic"]:
  119. text += await fetch_url(result["link"])
  120. return text
  121. ```
  122. ## 封装 MCP Server (基于 Stdio 协议)
  123. ### 1. MCP Server (Stdio)
  124. ```python
  125. # main.py
  126. from mcp.server.fastmcp import FastMCP
  127. from dotenv import load_dotenv
  128. import httpx
  129. import json
  130. import os
  131. from bs4 import BeautifulSoup
  132. from typing import Any
  133. import httpx
  134. from mcp.server.fastmcp import FastMCP
  135. from starlette.applications import Starlette
  136. from mcp.server.sse import SseServerTransport
  137. from starlette.requests import Request
  138. from starlette.routing import Mount, Route
  139. from mcp.server import Server
  140. import uvicorn
  141. load_dotenv()
  142. mcp = FastMCP("Agentdocs")
  143. USER_AGENT = "Agentdocs-app/1.0"
  144. SERPER_URL = "https://google.serper.dev/search"
  145. docs_urls = {
  146. "langchain": "python.langchain.com/docs",
  147. "llama-index": "docs.llamaindex.ai/en/stable",
  148. "autogen": "microsoft.github.io/autogen/stable",
  149. "agno": "docs.agno.com",
  150. "openai-agents-sdk": "openai.github.io/openai-agents-python",
  151. "mcp-doc": "modelcontextprotocol.io",
  152. "camel-ai": "docs.camel-ai.org",
  153. "crew-ai": "docs.crewai.com"
  154. }
  155. async def search_web(query: str) -> dict | None:
  156. payload = json.dumps({"q": query, "num": 2})
  157. headers = {
  158. "X-API-KEY": os.getenv("SERPER_API_KEY"),
  159. "Content-Type": "application/json",
  160. }
  161. async with httpx.AsyncClient() as client:
  162. try:
  163. response = await client.post(
  164. SERPER_URL, headers=headers, data=payload, timeout=30.0
  165. )
  166. response.raise_for_status()
  167. return response.json()
  168. except httpx.TimeoutException:
  169. return {"organic": []}
  170. async def fetch_url(url: str):
  171. async with httpx.AsyncClient() as client:
  172. try:
  173. response = await client.get(url, timeout=30.0)
  174. soup = BeautifulSoup(response.text, "html.parser")
  175. text = soup.get_text()
  176. return text
  177. except httpx.TimeoutException:
  178. return "Timeout error"
  179. @mcp.tool()
  180. async def get_docs(query: str, library: str):
  181. """
  182. 搜索给定查询和库的最新文档。
  183. 支持 langchain、llama-index、autogen、agno、openai-agents-sdk、mcp-doc、camel-ai 和 crew-ai。
  184. 参数:
  185. query: 要搜索的查询 (例如 "React Agent")
  186. library: 要搜索的库 (例如 "agno")
  187. 返回:
  188. 文档中的文本
  189. """
  190. if library not in docs_urls:
  191. raise ValueError(f"Library {library} not supported by this tool")
  192. query = f"site:{docs_urls[library]} {query}"
  193. results = await search_web(query)
  194. if len(results["organic"]) == 0:
  195. return "No results found"
  196. text = ""
  197. for result in results["organic"]:
  198. text += await fetch_url(result["link"])
  199. return text
  200. if __name__ == "__main__":
  201. mcp.run(transport="stdio")
  202. ```
  203. 启动命令:
  204. ```bash
  205. uv run main.py
  206. ```
  207. ### 2. 客户端配置
  208. #### 2.1 基于 Cline
  209. 首先在 Visual Studio Code 安装 Cline 插件,然后进行配置 MCP
  210. ```json
  211. {
  212. "mcpServers": {
  213. "mcp-server": {
  214. "command": "uv",
  215. "args": [
  216. "--directory",
  217. "<你的项目路径>",
  218. "run",
  219. "main.py"
  220. ]
  221. }
  222. }
  223. }
  224. ```
  225. 成功绑定如图(左侧绿灯):
  226. ![image](https://github.com/user-attachments/assets/6b166508-5eea-48b9-b31b-40330ee0b3ca)
  227. #### 2.2 基于 Cursor
  228. 项目根目录创建 .cursor 文件夹,并创建 mcp.json 文件,如:
  229. ![image](https://github.com/user-attachments/assets/fe47e9a9-fd05-4c60-85e1-dc0807af3eee)
  230. 然后粘贴以下内容到 mcp.json
  231. ```json
  232. {
  233. "mcpServers": {
  234. "mcp-server": {
  235. "command": "uv",
  236. "args": [
  237. "--directory",
  238. "<你的项目路径>",
  239. "run",
  240. "main.py"
  241. ]
  242. }
  243. }
  244. }
  245. ```
  246. 成功配置如图:
  247. ![image](https://github.com/user-attachments/assets/c42b4564-bb92-4550-9bb0-d510e7645834)
  248. 在 Features 开启 MCP 服务
  249. ![image](https://github.com/user-attachments/assets/386282c2-7ff5-4797-a478-b4cca65984ba)
  250. 通过对话它便通过 MCP 获取相关文档信息进行回答:
  251. ![image](https://github.com/user-attachments/assets/283c4702-cd40-4150-8efa-e23d515b13af)
  252. ## 构建 SSE MCP Server (基于 SSE 协议)
  253. ### 1. 封装 MCP Server
  254. ```python
  255. from mcp.server.fastmcp import FastMCP
  256. from dotenv import load_dotenv
  257. import httpx
  258. import json
  259. import os
  260. from bs4 import BeautifulSoup
  261. from typing import Any
  262. import httpx
  263. from mcp.server.fastmcp import FastMCP
  264. from starlette.applications import Starlette
  265. from mcp.server.sse import SseServerTransport
  266. from starlette.requests import Request
  267. from starlette.routing import Mount, Route
  268. from mcp.server import Server
  269. import uvicorn
  270. load_dotenv()
  271. mcp = FastMCP("docs")
  272. USER_AGENT = "docs-app/1.0"
  273. SERPER_URL = "https://google.serper.dev/search"
  274. docs_urls = {
  275. "langchain": "python.langchain.com/docs",
  276. "llama-index": "docs.llamaindex.ai/en/stable",
  277. "autogen": "microsoft.github.io/autogen/stable",
  278. "agno": "docs.agno.com",
  279. "openai-agents-sdk": "openai.github.io/openai-agents-python",
  280. "mcp-doc": "modelcontextprotocol.io",
  281. "camel-ai": "docs.camel-ai.org",
  282. "crew-ai": "docs.crewai.com"
  283. }
  284. async def search_web(query: str) -> dict | None:
  285. payload = json.dumps({"q": query, "num": 2})
  286. headers = {
  287. "X-API-KEY": os.getenv("SERPER_API_KEY"),
  288. "Content-Type": "application/json",
  289. }
  290. async with httpx.AsyncClient() as client:
  291. try:
  292. response = await client.post(
  293. SERPER_URL, headers=headers, data=payload, timeout=30.0
  294. )
  295. response.raise_for_status()
  296. return response.json()
  297. except httpx.TimeoutException:
  298. return {"organic": []}
  299. async def fetch_url(url: str):
  300. async with httpx.AsyncClient() as client:
  301. try:
  302. response = await client.get(url, timeout=30.0)
  303. soup = BeautifulSoup(response.text, "html.parser")
  304. text = soup.get_text()
  305. return text
  306. except httpx.TimeoutException:
  307. return "Timeout error"
  308. @mcp.tool()
  309. async def get_docs(query: str, library: str):
  310. """
  311. 搜索给定查询和库的最新文档。
  312. 支持 langchain、llama-index、autogen、agno、openai-agents-sdk、mcp-doc、camel-ai 和 crew-ai。
  313. 参数:
  314. query: 要搜索的查询 (例如 "React Agent")
  315. library: 要搜索的库 (例如 "agno")
  316. 返回:
  317. 文档中的文本
  318. """
  319. if library not in docs_urls:
  320. raise ValueError(f"Library {library} not supported by this tool")
  321. query = f"site:{docs_urls[library]} {query}"
  322. results = await search_web(query)
  323. if len(results["organic"]) == 0:
  324. return "No results found"
  325. text = ""
  326. for result in results["organic"]:
  327. text += await fetch_url(result["link"])
  328. return text
  329. ## sse传输
  330. def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
  331. """Create a Starlette application that can serve the provided mcp server with SSE."""
  332. sse = SseServerTransport("/messages/")
  333. async def handle_sse(request: Request) -> None:
  334. async with sse.connect_sse(
  335. request.scope,
  336. request.receive,
  337. request._send, # noqa: SLF001
  338. ) as (read_stream, write_stream):
  339. await mcp_server.run(
  340. read_stream,
  341. write_stream,
  342. mcp_server.create_initialization_options(),
  343. )
  344. return Starlette(
  345. debug=debug,
  346. routes=[
  347. Route("/sse", endpoint=handle_sse),
  348. Mount("/messages/", app=sse.handle_post_message),
  349. ],
  350. )
  351. if __name__ == "__main__":
  352. mcp_server = mcp._mcp_server
  353. import argparse
  354. parser = argparse.ArgumentParser(description='Run MCP SSE-based server')
  355. parser.add_argument('--host', default='0.0.0.0', help='Host to bind to')
  356. parser.add_argument('--port', type=int, default=8020, help='Port to listen on')
  357. args = parser.parse_args()
  358. # Bind SSE request handling to MCP server
  359. starlette_app = create_starlette_app(mcp_server, debug=True)
  360. uvicorn.run(starlette_app, host=args.host, port=args.port)
  361. ```
  362. 启动命令:
  363. ```bash
  364. uv run main.py --host 0.0.0.0 --port 8020
  365. ```
  366. 以上 MCP server 代码直接在你的云服务器跑即可。
  367. ### 2. 构建 MCP Client
  368. ```python
  369. import asyncio
  370. import json
  371. import os
  372. from typing import Optional
  373. from contextlib import AsyncExitStack
  374. import time
  375. from mcp import ClientSession
  376. from mcp.client.sse import sse_client
  377. from openai import AsyncOpenAI
  378. from dotenv import load_dotenv
  379. load_dotenv() # load environment variables from .env
  380. class MCPClient:
  381. def __init__(self):
  382. # Initialize session and client objects
  383. self.session: Optional[ClientSession] = None
  384. self.exit_stack = AsyncExitStack()
  385. self.openai = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY"), base_url=os.getenv("OPENAI_BASE_URL"))
  386. async def connect_to_sse_server(self, server_url: str):
  387. """Connect to an MCP server running with SSE transport"""
  388. # Store the context managers so they stay alive
  389. self._streams_context = sse_client(url=server_url)
  390. streams = await self._streams_context.__aenter__()
  391. self._session_context = ClientSession(*streams)
  392. self.session: ClientSession = await self._session_context.__aenter__()
  393. # Initialize
  394. await self.session.initialize()
  395. # List available tools to verify connection
  396. print("Initialized SSE client...")
  397. print("Listing tools...")
  398. response = await self.session.list_tools()
  399. tools = response.tools
  400. print("\nConnected to server with tools:", [tool.name for tool in tools])
  401. async def cleanup(self):
  402. """Properly clean up the session and streams"""
  403. if self._session_context:
  404. await self._session_context.__aexit__(None, None, None)
  405. if self._streams_context:
  406. await self._streams_context.__aexit__(None, None, None)
  407. async def process_query(self, query: str) -> str:
  408. """Process a query using OpenAI API and available tools"""
  409. messages = [
  410. {
  411. "role": "user",
  412. "content": query
  413. }
  414. ]
  415. response = await self.session.list_tools()
  416. available_tools = [{
  417. "type": "function",
  418. "function": {
  419. "name": tool.name,
  420. "description": tool.description,
  421. "parameters": tool.inputSchema
  422. }
  423. } for tool in response.tools]
  424. # Initial OpenAI API call
  425. completion = await self.openai.chat.completions.create(
  426. model=os.getenv("OPENAI_MODEL"),
  427. max_tokens=1000,
  428. messages=messages,
  429. tools=available_tools
  430. )
  431. # Process response and handle tool calls
  432. tool_results = []
  433. final_text = []
  434. assistant_message = completion.choices[0].message
  435. if assistant_message.tool_calls:
  436. for tool_call in assistant_message.tool_calls:
  437. tool_name = tool_call.function.name
  438. tool_args = json.loads(tool_call.function.arguments)
  439. # Execute tool call
  440. result = await self.session.call_tool(tool_name, tool_args)
  441. tool_results.append({"call": tool_name, "result": result})
  442. final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
  443. # Continue conversation with tool results
  444. messages.extend([
  445. {
  446. "role": "assistant",
  447. "content": None,
  448. "tool_calls": [tool_call]
  449. },
  450. {
  451. "role": "tool",
  452. "tool_call_id": tool_call.id,
  453. "content": result.content[0].text
  454. }
  455. ])
  456. print(f"Tool {tool_name} returned: {result.content[0].text}")
  457. print("messages", messages)
  458. # Get next response from OpenAI
  459. completion = await self.openai.chat.completions.create(
  460. model=os.getenv("OPENAI_MODEL"),
  461. max_tokens=1000,
  462. messages=messages,
  463. )
  464. if isinstance(completion.choices[0].message.content, (dict, list)):
  465. final_text.append(str(completion.choices[0].message.content))
  466. else:
  467. final_text.append(completion.choices[0].message.content)
  468. else:
  469. if isinstance(assistant_message.content, (dict, list)):
  470. final_text.append(str(assistant_message.content))
  471. else:
  472. final_text.append(assistant_message.content)
  473. return "\n".join(final_text)
  474. async def chat_loop(self):
  475. """Run an interactive chat loop"""
  476. print("\nMCP Client Started!")
  477. print("Type your queries or 'quit' to exit.")
  478. while True:
  479. try:
  480. query = input("\nQuery: ").strip()
  481. if query.lower() == 'quit':
  482. break
  483. response = await self.process_query(query)
  484. print("\n" + response)
  485. except Exception as e:
  486. print(f"\nError: {str(e)}")
  487. async def main():
  488. if len(sys.argv) < 2:
  489. print("Usage: uv run client.py <URL of SSE MCP server (i.e. http://localhost:8080/sse)>")
  490. sys.exit(1)
  491. client = MCPClient()
  492. try:
  493. await client.connect_to_sse_server(server_url=sys.argv[1])
  494. await client.chat_loop()
  495. finally:
  496. await client.cleanup()
  497. if __name__ == "__main__":
  498. import sys
  499. asyncio.run(main())
  500. ```
  501. 启动命令:
  502. ```bash
  503. uv run client.py http://0.0.0.0:8020/sse
  504. ```
  505. Client 日志:
  506. ![image](https://github.com/user-attachments/assets/c4999d81-8a80-49a3-93c1-62571d4bed22)
  507. Server 日志:
  508. ![image](https://github.com/user-attachments/assets/2f45ac47-31db-442d-ad0a-87d3b3bef8b5)
  509. 以上便是 Python 从 0 到 1 搭建 MCP Server 以及 MCP Client 的完整教程。有不对的地方请多多指教。
  510. 参考相关资料:
  511. - https://www.youtube.com/watch?v=Ek8JHgZtmcI
  512. - https://serper.dev/
  513. - https://modelcontextprotocol.io/quickstart/server
  514. - https://modelcontextprotocol.io/quickstart/client
  515. - https://docs.cursor.com/context/model-context-protocol

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.