首先感谢:探索 MCP-我的学习与实践笔记
我想写个能够支持 MCP 协议的对话终端,类似 cheery-ai 这种,通过 config.json 配置 MCP Server ,在终端中实现对话。
MCP Server 的实现搜索到了不少资料,也比较好理解。但是关于 Go 语言实现 MCP Client 的资料看到比较少。
关于 MCP Client 的实现参考了: cp_simple_chatbot
初步是想着把 Python 代码翻译为 Go 代码,使用 Go 三方库metoro-io/mcp-golang, 翻译如下代码
async def start(self) -> None:
"""Main chat session handler."""
try:
for server in self.servers:
try:
await server.initialize()
except Exception as e:
logging.error(f"Failed to initialize server: {e}")
await self.cleanup_servers()
return
all_tools = []
for server in self.servers:
tools = await server.list_tools()
all_tools.extend(tools)
tools_description = "\n".join([tool.format_for_llm() for tool in all_tools])
system_message = (
"You are a helpful assistant with access to these tools:\n\n"
f"{tools_description}\n"
"Choose the appropriate tool based on the user's question. "
"If no tool is needed, reply directly.\n\n"
"IMPORTANT: When you need to use a tool, you must ONLY respond with "
"the exact JSON object format below, nothing else:\n"
"{\n"
' "tool": "tool-name",\n'
' "arguments": {\n'
' "argument-name": "value"\n'
" }\n"
"}\n\n"
"After receiving a tool's response:\n"
"1. Transform the raw data into a natural, conversational response\n"
"2. Keep responses concise but informative\n"
"3. Focus on the most relevant information\n"
"4. Use appropriate context from the user's question\n"
"5. Avoid simply repeating the raw data\n\n"
"Please use only the tools that are explicitly defined above."
)
messages = [{"role": "system", "content": system_message}]
while True:
try:
user_input = input("You: ").strip().lower()
if user_input in ["quit", "exit"]:
logging.info("\nExiting...")
break
messages.append({"role": "user", "content": user_input})
llm_response = self.llm_client.get_response(messages)
logging.info("\nAssistant: %s", llm_response)
result = await self.process_llm_response(llm_response)
if result != llm_response:
messages.append({"role": "assistant", "content": llm_response})
messages.append({"role": "system", "content": result})
final_response = self.llm_client.get_response(messages)
logging.info("\nFinal response: %s", final_response)
messages.append(
{"role": "assistant", "content": final_response}
)
else:
messages.append({"role": "assistant", "content": llm_response})
except KeyboardInterrupt:
logging.info("\nExiting...")
break
finally:
await self.cleanup_servers()
主要思路是将 “告诉 AI 工具清单”,以及 “AI 分析你的需求,决定用哪个工具” 这段逻辑翻译一下,然后使用 mcp-golang 来处理和 MCP Server 的连接。
目前问题就来了,这样实现感觉不够优雅。MCP Client 的 SDK 其实可以把 LLM+'MCP Server'封装到一起,向大模型提问就可以调用 MCP Server, 引用 SDK 的人就不需要再手动实现“把工具清单告诉 AI”,以及“AI 分析你的需求,决定用哪个工具”逻辑了。
问题 1: 如果我翻译“告诉 AI 工具清单”,以及 “AI 分析你的需求,决定用哪个工具”这段代码,感觉实现不够优雅,其他类似的 MCP Client (如 Cline 、CherryAi 等)是如何实现的呢?
问题 2:Go 语言有类似 mcp_simple_chatbot 的示例代码吗?
问题 3:如果是你,你会如何实现这个需求呢?
1
harlen 1 天前
GitHub topic MCP 然后找评分最高的实现,借鉴一下
|
2
kaneg 1 天前
一般这类需求,如果是 OpenAI , 用 function call 比用自然语言约束要方便和精准。
|