原创 孔某人 2025-03-16 16:42 北京
MCP是一种Agent应用的插件协议
我个人之前对MCP并不是很关心,最近与人讨论稍微研究了一下这方面。但并不算深入,也没有翻太多源码,所以本文的观点将来可能会被推翻。但只要这篇文章还在,就表示我的观点没有被推翻。
MCP是一种Agent应用的插件协议,而且这个插件更偏工具性质,不能大幅的覆盖原有Agent的功能和设定,更多是给它新增一些tools。
它本质上并不是LLM tool use协议的替代,官方demo的例子就是把MCP的调用转换为了LLM的tool调用给LLM模型,以下代码来自 https://modelcontextprotocol.io/quickstart/client
async def process_query(self, query: str) -> str:
"""Process a query using Claude and available tools"""
messages = [
{
"role": "user",
"content": query
}
]
response = await self.session.list_tools()
available_tools = [{
"name": tool.name,
"description": tool.description,
"input_schema": tool.inputSchema
} for tool in response.tools]
# Initial Claude API call
response = self.anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=messages,
tools=available_tools
)
# Process response and handle tool calls
final_text = []
assistant_message_content = []
for content in response.content:
if content.type == 'text':
final_text.append(content.text)
assistant_message_content.append(content)
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
# Execute tool call
result = await self.session.call_tool(tool_name, tool_args)
final_text.append(f"[Calling tool {tool_name} with args {tool_args}]")
assistant_message_content.append(content)
messages.append({
"role": "assistant",
"content": assistant_message_content
})
messages.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": content.id,
"content": result.content
}
]
})
# Get next response from Claude
response = self.anthropic.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
messages=messages,
tools=available_tools
)
final_text.append(response.content[0].text)
return "\n".join(final_text)
这段代码就已经很清楚了,再结合该文档前面的链接建立,感觉就是个很典型的插件模式。
MCP体系的命名是挺糟糕的:MCP Server是工具提供方,MCP client是Agent应用。
MCP本来是为Claude的App端与用户本地PC资源和Context进行交互而设计的,后来协议也在逐步往跨机器通讯来扩展。
MCP协议其实与LLM并不绑定,获取了tool之后如果是硬编码匹配tool函数名进行调用其实也没问题,这样就完全没有LLM参与了。只是实际使用中,肯定是希望避免对于具体插件的硬编码,这样就需要结合tool的描述来进行使用,所以就需要LLM的语义理解、推理能力、知识等。
这可以看成是传统软件开发中依赖注入(Dependency Injection)的一个实例,只不过真的想要实现注入工具的自动适配,需要有LLM的能力才能有效的使用。
交流与合作
如果希望和我交流讨论,或参与相关的讨论群,或者建立合作,请加微信,联系方式请点击 -> 联系方式。
本文于2025.3.16 首发于微信公众号