# -*- coding: utf-8 -*-"""The base class for MCP clients in AgentScope."""fromabcimportabstractmethodfromtypingimportCallable,Listimportmcp.typesfrom.._loggingimportloggerfrom..messageimportImageBlock,Base64Source,AudioBlock,TextBlock
[文档]classMCPClientBase:"""Base class for MCP clients."""
[文档]def__init__(self,name:str)->None:"""Initialize the MCP client with a name. Args: name (`str`): The name to identify the MCP server, which should be unique across the MCP servers. """self.name=name
[文档]@abstractmethodasyncdefget_callable_function(self,func_name:str,wrap_tool_result:bool=True,)->Callable:"""Get a tool function by its name."""
@staticmethoddef_convert_mcp_content_to_as_blocks(mcp_content_blocks:list,)->List[TextBlock|ImageBlock|AudioBlock]:"""Convert MCP content to AgentScope blocks."""as_content:list=[]forcontentinmcp_content_blocks:ifisinstance(content,mcp.types.TextContent):as_content.append(TextBlock(type="text",text=content.text,),)elifisinstance(content,mcp.types.ImageContent):as_content.append(ImageBlock(type="image",source=Base64Source(type="base64",media_type=content.mimeType,data=content.data,),),)elifisinstance(content,mcp.types.AudioContent):as_content.append(AudioBlock(type="audio",source=Base64Source(type="base64",media_type=content.mimeType,data=content.data,),),)elifisinstance(content,mcp.types.EmbeddedResource):ifisinstance(content.resource,mcp.types.TextResourceContents,):as_content.append(TextBlock(type="text",text=content.resource.model_dump_json(indent=2),),)else:# TODO: support the BlobResourceContents in the future,# which is a base64-encoded string representing the# binary datalogger.error("Unsupported EmbeddedResource content type: %s. ""Skipping this content.",type(content.resource),)else:logger.warning("Unsupported content type: %s. Skipping this content.",type(content),)returnas_content