调通mcp tool

This commit is contained in:
玄凤科技
2025-03-20 11:52:37 +08:00
parent 8504c181c0
commit 2b81ebca8e
3 changed files with 53 additions and 59 deletions
+14 -41
View File
@@ -1,7 +1,7 @@
import asyncio
from typing import Optional
from contextlib import AsyncExitStack
import os
import os, shutil
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
@@ -19,34 +19,19 @@ class MCPClient:
self.tolls = []
async def initialize(self):
main_command = self.config["command"]
args = self.config.get("args", [])
server_script_path = main_command
if args:
# 如果第一个参数是路径,使用其目录作为工作目录
possible_path = args[0]
if os.path.exists(possible_path):
server_script_path = possible_path
await self.connect_to_server(server_script_path)
command = (
shutil.which("npx")
if self.config["command"] == "npx"
else self.config["command"]
)
async def connect_to_server(self, server_script_path: str):
"""Connect to an MCP server
env={**os.environ, **self.config["env"]}
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")
env = self.config.get("env", {})
command = "python" if is_python else "node"
server_params = StdioServerParameters(
command=command,
args=[server_script_path],
args=args,
env=env
)
@@ -61,7 +46,10 @@ class MCPClient:
tools = response.tools
self.tools = tools
self.logger.bind(tag=TAG).info(f"Connected to server with tools:{[tool.name for tool in tools]}")
def has_tool(self, tool_name):
return any(tool.name == tool_name for tool in self.tools)
def get_available_tools(self):
available_tools = [{"type": "function", "function":{
"name": tool.name,
@@ -72,25 +60,10 @@ class MCPClient:
return available_tools
async def call_tool(self, tool_name: str, tool_args: dict):
self.logger.bind(tag=TAG).info(f"MCPClient Calling tool {tool_name} with args: {tool_args}")
response = await self.session.call_tool(tool_name, tool_args)
return response
async def cleanup(self):
"""Clean up resources"""
await self.exit_stack.aclose()
async def main():
if len(sys.argv) < 2:
print("Usage: python client.py <path_to_server_script>")
sys.exit(1)
client = MCPClient()
try:
await client.connect_to_server(sys.argv[1])
await client.chat_loop()
finally:
await client.cleanup()
if __name__ == "__main__":
import sys
asyncio.run(main())
await self.exit_stack.aclose()
+3 -2
View File
@@ -80,14 +80,15 @@ class MCPManager:
"""执行工具调用
Args:
tool_name: 工具名称
arguments: 工具参数
arguments: 工具参数
Returns:
Any: 工具执行结果
Raises:
ValueError: 工具未找到时抛出
"""
self.logger.bind(tag=TAG).info(f"Executing tool {tool_name} with arguments: {arguments}")
for client in self.client.values():
if any(tool_name == tool["name"] for tool in client.tools):
if client.has_tool(tool_name):
return await client.call_tool(tool_name, arguments)
raise ValueError(f"Tool {tool_name} not found in any MCP server")