MCPcopy Create free account
hub / github.com/modelscope/ms-agent / MCPClient

Class MCPClient

ms_agent/tools/mcp_client.py:33–313  ·  view source on GitHub ↗

MCP client for all mcp tools This class can hold multiple mcp servers. Args: config(`DictConfig`): The config instance. mcp_config(`Optional[Dict[str, Any]]`): Extra mcp servers in json format.

Source from the content-addressed store, hash-verified

31
32
33class MCPClient(ToolBase):
34 """MCP client for all mcp tools
35
36 This class can hold multiple mcp servers.
37
38 Args:
39 config(`DictConfig`): The config instance.
40 mcp_config(`Optional[Dict[str, Any]]`): Extra mcp servers in json format.
41 """
42
43 def __init__(
44 self,
45 mcp_config: Optional[Dict[str, Any]] = None,
46 config: Optional[DictConfig] = None,
47 ):
48 super().__init__(config)
49 self.sessions: Dict[str, ClientSession] = {}
50 self.exit_stack = AsyncExitStack()
51 self.mcp_config: Dict[str, Dict[str, Any]] = {'mcpServers': {}}
52 if config is not None:
53 config_from_file = Config.convert_mcp_servers_to_json(config)
54 self.mcp_config['mcpServers'].update(
55 config_from_file.get('mcpServers', {}))
56 self.exclude_functions = {}
57 self.include_functions = {}
58 if mcp_config is not None:
59 self.mcp_config['mcpServers'].update(
60 mcp_config.get('mcpServers', {}))
61
62 async def call_tool(self, server_name: str, tool_name: str,
63 tool_args: dict):
64 response = await self.sessions[server_name].call_tool(
65 tool_name, tool_args)
66
67 texts = []
68 resources = []
69 if response.isError:
70 sep = '\n\n'
71 if all(isinstance(item, str) for item in response.content):
72 return f'execute tool call error: [{server_name}]{tool_name}, {sep.join(response.content)}'
73 else:
74 item_list = []
75 for item in response.content:
76 item_list.append(item.text)
77 return f'execute tool call error: [{server_name}]{tool_name}, {sep.join(item_list)}'
78 for content in response.content:
79 if content.type == 'text':
80 texts.append(content.text)
81 elif content.type == 'resource':
82 import json5
83 json_str = content.resource.model_dump_json(by_alias=True)
84 texts.append(json_str)
85 resources.append(json5.loads(json_str))
86
87 if resources:
88 return {'text': '\n\n'.join(texts), 'resources': resources}
89
90 return '\n\n'.join(texts)

Callers 3

mainMethod · 0.90
mainMethod · 0.90
connectMethod · 0.90

Calls

no outgoing calls

Tested by 2

mainMethod · 0.72
mainMethod · 0.72