概述
试想一下,如果要想在现有应用上构建,让AI读取引用我们功能和数据,该怎么办,比如询问某个城市的天气,我们希望AI能调用天气函数返回相应结果,这时MCP (Model Context Protocol)就可以派上用场了,它相当于我们电脑的USB-C接口,提供了一个标准方式让AI模型连接不同的应用和工具。 我们可以建一个MUP Server来处理这类业务,比如市面上已有各类MUP Server,比较典型的高德地图MCP,除此之外,还有旅行交通的 AirbnbMCPServer
,提供房源问询,版本控制的 gitlab-mr-mcp
,工具类mcp-openai,开发类 mcp-server-and-gw
等,更多工具可查看:https://github.com/punkpeye/awesome-mcp-servers/blob/main/README-zh.md#%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%AE%9E%E7%8E%B0
MCP 服务器的职能变得非常容易理解:即遵循 MCP 协议来暴露其可提供的 Resources、Tools 或 Prompts:
- Resources:结构化数据(如文件、API 响应)
- Tools:可执行函数(如查询数据库、发送邮件)
- Prompts:预定义的交互模板
MCP与Function Calling的区别:
开发一个MCP Server
使用Python为例。
- 安装uv
windows:powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"linux/mac:curl -LsSf https://astral.sh/uv/install.sh | sh
- 安装依赖
pip install mcppip install mcp[cli]pip install httpx==0.27
- 编写代码:非常简单,将普通的py函数添加一个注解即可。
import osfrom mcp.server.fastmcp import FastMCPmcp = FastMCP("债券服务Demo")@mcp.tool()def filterByRate(a:str) -> list: """根据债券评级的条件筛选债券""" print('债券评级过滤条件:',a) return ["债券A","债券B","债券C"]@mcp.tool()def filterByType(t:str) -> list: """根据债券类型的条件筛选债券""" print('债券类型过滤条件:',t) return ["债券A","债券C","债券D"]@mcp.tool()def filterByBidRange(a1:float,a2:float) -> list: """根据债券bid收益率区间筛选债券""" print('债券类型过滤条件:',a1,a2) return ["债券A2","债券C2","债券D2"]@mcp.tool()def filterResult(**kwargs) -> list: """获取所有符合条件的债券结果""" print('filterResult:',kwargs) return ["债券A111","债券C222","债券D3333"]if __name__ == "__main__": # mcp.run(transport='stdio') mcp.run(transport='sse')
- 启动服务:
mcp dev.\mcp\hello.py
客户端集成
工具集成
以 CherryStudio
为例,其他类型,添加一个: MCPServer
,问答时选中MCP Server即可.
代码集成
程序集成:编写一个客户端程序即可,我们以本地ollama部署的qwen为例,代码如下:
client_mcp.pyimport asyncioimport jsonimport sysimport timefrom typing import Optionalfrom contextlib import AsyncExitStackfrom mcp.client.sse import sse_clientfrom mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_clientfrom openai import AsyncOpenAIclass MCPClient: def __init__(self): # Initialize session and client objects self.session: Optional[ClientSession] = None self.exit_stack = AsyncExitStack() self.client = AsyncOpenAI( api_key="test", base_url="http://ollama地址:11434/v1" ) async def connect_to_server(self, server_script_path: str): """Connect to an MCP server Args: server_script_path: Path to the server script (.py or .js) """ is_python = server_script_path.endswith(".py") is_js = server_script_path.endswith(".js") if not (is_python or is_js): raise ValueError("Server script must be a .py or .js file") command = "python" if is_python else "node" server_params = StdioServerParameters( command=command, args=[server_script_path], env=None ) stdio_transport = await self.exit_stack.enter_async_context( stdio_client(server_params) ) self.stdio, self.write = stdio_transport self.session = await self.exit_stack.enter_async_context( ClientSession(self.stdio, self.write) ) await self.session.initialize() # List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.name for tool in tools]) async def connect_to_sse_server(self, server_url: str): """Connect to an MCP server Args: server_script_path: Path to the server script (.py or .js) """ self._streams_context = sse_client(url=server_url) streams = await self._streams_context.__aenter__() self._session_context = ClientSession(*streams) self.session = await self._session_context.__aenter__() await self.session.initialize() # List available tools response = await self.session.list_tools() tools = response.tools print("\nConnected to server with tools:", [tool.name for tool in tools]) async def process_query(self, query: str) -> str: """使用 LLM 和 MCP 服务器提供的工具处理查询""" 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] # 初始化 LLM API 调用 response = await self.client.chat.completions.create( model="qwen2.5:14b", messages=messages, tools=available_tools # 将工具列表传递给 LLM ) final_text = [] message = response.choices[0].message print(response.choices[0]) final_text.append(message.content or "") # 处理响应并处理工具调用 if message.tool_calls: # 处理每个工具调用 for tool_call in message.tool_calls: tool_name = tool_call.function.name tool_args = json.loads(tool_call.function.arguments) # 执行工具调用 start_time = time.time() result = await self.session.call_tool(tool_name, tool_args) end_time = time.time() print(f"Tool {tool_name} took {end_time - start_time} seconds to execute") final_text.append(f"[Calling tool {tool_name} with args {tool_args}]") # 将工具调用和结果添加到消息历史 messages.append({ "role": "assistant", "tool_calls": [ { "id": tool_call.id, "type": "function", "function": { "name": tool_name, "arguments": json.dumps(tool_args) } } ] }) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": str(result.content) }) # 将工具调用的结果交给 LLM response = await self.client.chat.completions.create( model="qwen2.5:14b", messages=messages, tools=available_tools ) message = response.choices[0].message if message.content: final_text.append(message.content) return "\n".join(final_text) async def chat_loop(self): """Run an interactive chat loop""" print("\nMCP Client Started!") print("Type your queries or 'quit' to exit.") while True: try: query = input("\nQuery: ").strip() if query.lower() == 'quit': break response = await self.process_query(query) print("\n" + response) except Exception as e: print(f"\nError: {str(e)}") async def cleanup(self): """Clean up resources""" await self.exit_stack.aclose()main.pyimport requestsimport jsonimport httpximport asynciofrom client_mcp import MCPClientimport sysasync def main(): url_server_mcp = 'http://localhost:8000/sse' client = MCPClient() try: # 根据MCP Server传输协议进行选择 await client.connect_to_sse_server(url_server_mcp) await client.chat_loop() finally: await client.cleanup()if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main())
如何学习大模型 AI ?
由于新岗位的生产效率,要优于被取代岗位的生产效率,所以实际上整个社会的生产效率是提升的。
但是具体到个人,只能说是:
“最先掌握AI的人,将会比较晚掌握AI的人有竞争优势”。
这句话,放在计算机、互联网、移动互联网的开局时期,都是一样的道理。
我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。
我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
第一阶段(10天):初阶应用
该阶段让大家对大模型 AI有一个最前沿的认识,对大模型 AI 的理解超过 95% 的人,可以在相关讨论时发表高级、不跟风、又接地气的见解,别人只会和 AI 聊天,而你能调教 AI,并能用代码将大模型和业务衔接。
- 大模型 AI 能干什么?
- 大模型是怎样获得「智能」的?
- 用好 AI 的核心心法
- 大模型应用业务架构
- 大模型应用技术架构
- 代码示例:向 GPT-3.5 灌入新知识
- 提示工程的意义和核心思想
- Prompt 典型构成
- 指令调优方法论
- 思维链和思维树
- Prompt 攻击和防范
- …
第二阶段(30天):高阶应用
该阶段我们正式进入大模型 AI 进阶实战学习,学会构造私有知识库,扩展 AI 的能力。快速开发一个完整的基于 agent 对话机器人。掌握功能最强的大模型开发框架,抓住最新的技术进展,适合 Python 和 JavaScript 程序员。
- 为什么要做 RAG
- 搭建一个简单的 ChatPDF
- 检索的基础概念
- 什么是向量表示(Embeddings)
- 向量数据库与向量检索
- 基于向量检索的 RAG
- 搭建 RAG 系统的扩展知识
- 混合检索与 RAG-Fusion 简介
- 向量模型本地部署
- …
第三阶段(30天):模型训练
恭喜你,如果学到这里,你基本可以找到一份大模型 AI相关的工作,自己也能训练 GPT 了!通过微调,训练自己的垂直大模型,能独立训练开源多模态大模型,掌握更多技术方案。
到此为止,大概2个月的时间。你已经成为了一名“AI小子”。那么你还想往下探索吗?
- 为什么要做 RAG
- 什么是模型
- 什么是模型训练
- 求解器 & 损失函数简介
- 小实验2:手写一个简单的神经网络并训练它
- 什么是训练/预训练/微调/轻量化微调
- Transformer结构简介
- 轻量化微调
- 实验数据集的构建
- …
第四阶段(20天):商业闭环
对全球大模型从性能、吞吐量、成本等方面有一定的认知,可以在云端和本地等多种环境下部署大模型,找到适合自己的项目/创业方向,做一名被 AI 武装的产品经理。
- 硬件选型
- 带你了解全球大模型
- 使用国产大模型服务
- 搭建 OpenAI 代理
- 热身:基于阿里云 PAI 部署 Stable Diffusion
- 在本地计算机运行大模型
- 大模型的私有化部署
- 基于 vLLM 部署大模型
- 案例:如何优雅地在阿里云私有部署开源大模型
- 部署一套开源 LLM 项目
- 内容安全
- 互联网信息服务算法备案
- …
学习是一个过程,只要学习就会有挑战。天道酬勤,你越努力,就会成为越优秀的自己。
如果你能在15天内完成所有的任务,那你堪称天才。然而,如果你能完成 60-70% 的内容,你就已经开始具备成为一名大模型 AI 的正确特征了。