(self, tool_name, tool_args: dict)
| 397 | return new_client |
| 398 | |
| 399 | async def execute_function(self, tool_name, tool_args: dict): |
| 400 | from mcp.types import TextResourceContents |
| 401 | |
| 402 | # Check if session is alive |
| 403 | try: |
| 404 | await self.session.send_ping() |
| 405 | except Exception as e: |
| 406 | logger.info(f"Session is not alive, please increase 'sse_read_timeout' in the config, try reconnect: {e}") |
| 407 | # Auto reconnect |
| 408 | try: |
| 409 | from qwen_agent.tools.mcp_manager import MCPManager |
| 410 | manager = MCPManager() |
| 411 | if self.client_id is not None: |
| 412 | manager.clients[self.client_id] = await self.reconnect() |
| 413 | return await manager.clients[self.client_id].execute_function(tool_name, tool_args) |
| 414 | else: |
| 415 | logger.info('Reconnect failed: client_id is None') |
| 416 | return 'Session reconnect (client creation) exception: client_id is None' |
| 417 | except Exception as e3: |
| 418 | logger.info(f'Reconnect (client creation) exception type: {type(e3)}, value: {repr(e3)}') |
| 419 | return f'Session reconnect (client creation) exception: {e3}' |
| 420 | if tool_name == 'list_resources': |
| 421 | try: |
| 422 | list_resources = await self.session.list_resources() |
| 423 | if list_resources.resources: |
| 424 | resources_str = '\n\n'.join(str(resource) for resource in list_resources.resources) |
| 425 | else: |
| 426 | resources_str = 'No resources found' |
| 427 | return resources_str |
| 428 | except Exception as e: |
| 429 | logger.info(f'No list resources: {e}') |
| 430 | return f'Error: {e}' |
| 431 | elif tool_name == 'read_resource': |
| 432 | try: |
| 433 | uri = tool_args.get('uri') |
| 434 | if not uri: |
| 435 | raise ValueError('URI is required for read_resource') |
| 436 | read_resource = await self.session.read_resource(uri) |
| 437 | texts = [] |
| 438 | for resource in read_resource.contents: |
| 439 | if isinstance(resource, TextResourceContents): |
| 440 | texts.append(resource.text) |
| 441 | # if isinstance(resource, BlobResourceContents): |
| 442 | # texts.append(resource.blob) |
| 443 | if texts: |
| 444 | return '\n\n'.join(texts) |
| 445 | else: |
| 446 | return 'Failed to read resource' |
| 447 | except Exception as e: |
| 448 | logger.info(f'Failed to read resource: {e}') |
| 449 | return f'Error: {e}' |
| 450 | else: |
| 451 | response = await self.session.call_tool(tool_name, tool_args) |
| 452 | texts = [] |
| 453 | for content in response.content: |
| 454 | if content.type == 'text': |
| 455 | texts.append(content.text) |
| 456 | if texts: |
no test coverage detected