微信扫码
添加专属顾问
我要投稿
MCP协议动态发现能力,AI模型与工具交互的新突破。 核心内容: 1. MCP与传统API的不同:动态发现能力介绍 2. 动态发现工具与服务的实现细节 3. 代码示例:服务器端与客户端交互展示
MCP(Model Context Protocol)与传统的API相比,一个重要的能力是动态发现:MCP允许AI模型动态发现并与可用工具交互,无需预先设定每个集成的固定代码。
这个动态发现分两个层次:
动态发现工具:在指定的MCP服务器上发现工具,一直都支持。
动态发现服务:定义客户端如何发现并连接远程 MCP 服务器, 这个按照规划是25年上半年要完成的。
MCP 支持动态工具发现。
https://modelcontextprotocol.io/docs/concepts/tools#tool-discovery-and-updates
以下是一个展示动态发现功能的简单代码示例,包括服务器端和客户端:
from mcp.server.fastmcp import FastMCP
# 创建一个MCP服务器
mcp = FastMCP("Demo")
# 添加一个加法工具
@mcp.tool()
def add(a:int, b:int)->int:
"""Add two numbers"""
return a + b
# 添加一个动态问候资源
@mcp.resource("greeting://{name}")
def get_greeting(name:str)->str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
# 运行服务器
if __name__ =="__main__":
mcp.run()
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# 配置服务器
server_params = StdioServerParameters(
command="python",
args=["server.py"]
)
# 创建客户端会话
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 列出服务器提供的工具
tools = await session.list_tools()
print("Available tools:", tools)
# 执行工具
result = await session.call_tool("add",{"a":5,"b":3})
print("Result of add tool:", result)
# 获取动态问候
greeting = await session.read_resource("greeting://Alice")
print("Greeting:", greeting)
if __name__ =="__main__":
asyncio.run(main())
这里用了 Stdio 类型的Server,MCP目前支持两种通讯机制,他们的区别可以看 MCP的通信机制。
上述代码示例展示了如何在服务器端动态创建工具和资源,并在客户端动态发现并调用这些工具和资源。
当工具发生变化时,服务器可以使用 notifications/tools/list_changed
通知客户端
这样就可以:
代码示例,服务器端新加了一个乘法工具,通知客户端变化
服务器端最初版本代码跟上个例子一样,变化成如下:
from mcp.server.fastmcp import FastMCP
from mcp import types
# 创建一个MCP服务器
mcp = FastMCP("Demo")
# 加法工具
@mcp.tool()
def add(a:int, b:int)->int:
"""Add two numbers"""
return a + b
# 动态问候资源
@mcp.resource("greeting://{name}")
def get_greeting(name:str)->str:
"""Get a personalized greeting"""
return f"Hello, {name}!"
# 添加一个乘法工具
@mcp.tool()
def multiply(a:int, b:int)->int:
"""Multiply two numbers"""
return a * b
# 每次工具变化时通知客户端
async def notify_tool_changes():
await mcp.notify(types.ListToolsChangedNotification())
# 运行服务器
if __name__ =="__main__":
import asyncio
async def main():
await notify_tool_changes()
mcp.run()
asyncio.run(main())
客户端会监听工具变化通知,并动态更新工具列表。
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# 配置服务器
server_params = StdioServerParameters(
command="python",
args=["server.py"]
)
# 创建客户端会话
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# 列出服务器提供的工具
tools = await session.list_tools()
print("Available tools:", tools)
# 监听工具变化通知
async def on_tool_change(notification):
print("Tools have changed:", notification)
# 列出更新后的工具
updated_tools = await session.list_tools()
print("Updated tools:", updated_tools)
session.subscribe("notifications/tools/list_changed", on_tool_change)
# 执行加法工具
result = await session.call_tool("add",{"a":5,"b":3})
print("Result of add tool:", result)
# 执行乘法工具
result = await session.call_tool("multiply",{"a":5,"b":3})
print("Result of multiply tool:", result)
# 获取动态问候
greeting = await session.read_resource("greeting://Alice")
print("Greeting:", greeting)
if __name__ =="__main__":
asyncio.run(main())
上述代码示例展示了如何在服务器端添加一个新的乘法工具,并通知客户端这些变化。客户端会监听这些通知,并动态更新工具列表。
按照规划是25年上半年要完成的,参看: https://modelcontextprotocol.io/development/roadmap。
按照 https://github.com/modelcontextprotocol/specification/discussions/69 这里的讨论,是准备:
用一种与 MCP 重叠的协议,并且使用自定义 URI 解决了这个限制,这样就允许在聊天中粘贴 URI 等流程,并让 LLM 决定是否需要与该工具集成、何时使用它等...
大致的流程是:
agent 遇到自定义 URI,例如 mcp://api.myservice.com
agent 解析 URI 并获取有关服务的详细信息。例如,它对预定义端点执行 HTTP GET 请求,例如: https://api.myservice.com/llms.txt
该服务以包含所有相关元数据的 JSON 或文本文件进行响应,其中包括:身份验证、服务及其功能描述、提供的功能/工具/资源列表、完整的 API 文档、定价、付款方式或支持的付款协议的详细信息。
基于上面检索到的信息,Agent 做权限验证、功能映射、启动交互。
通过上面方式,完成对服务的动态发现。
从本质上讲:当你想为一个你不能控制的 Agent 引入工具时,MCP 就会派上用场。
而如何让不能控制的Agent发现你的服务,动态发现就是必须的能力,从上面的讲解看,MCP这个能力将很快就健全了,非常值得期待。
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-04-20
MCP很好,但安全问题不容忽视,智能体安全框架可以解决
2025-04-20
赛博中医大师已经开始为你把脉了
2025-04-20
OpenAI 官方定义:到底什么是 AI Agent?
2025-04-20
AIGC应用必坑指南与落地实战方法论
2025-04-20
「合成用户」进化:基于访谈生成的 1000 个 虚拟用户,能产出洞察吗
2025-04-20
扣子空间火了,是国产通用 agent 一个好的开始,比 manus 还差不少
2025-04-20
微软偷偷上线一款MCP神器,可让Office文件秒变Markdown!
2025-04-20
行业必读丨OpenAI 最新报告:构建 Agents 最佳实践
2024-08-13
2024-06-13
2024-08-21
2024-09-23
2024-07-31
2024-05-28
2024-08-04
2024-04-26
2024-07-09
2024-09-17
2025-04-20
2025-04-18
2025-04-16
2025-04-13
2025-04-13
2025-04-13
2025-04-12
2025-04-12