Skip to main content
Glama
cluic
by cluic

get_friends

Retrieve a list of WeChat contacts with options to specify quantity and download profile pictures for automation workflows.

Instructions

获取好友列表。参数: n (获取数量,默认10), save_avatar (是否获取头像,默认false)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
nNo
save_avatarNo

Implementation Reference

  • Main handler implementation for get_friends tool. This function retrieves friend list from WeChat using the WeChatWrapper, formats the contact information (name, alias, remark, signature, source), and returns a JSON-formatted result. It handles errors and switches back to chat page after retrieving friend details.
    @tool(
        name="get_friends",
        description="获取好友列表。参数: n (获取数量,默认10), save_avatar (是否获取头像,默认false)"
    )
    def get_friends(n: int = 10, save_avatar: bool = False) -> str:
        """
        获取好友列表
    
        Args:
            n: 获取数量
            save_avatar: 是否获取头像
    
        Returns:
            JSON 格式的好友列表
        """
        wrapper = _get_wrapper()
        if not wrapper:
            return format_result(False, "微信未初始化")
    
        try:
            friends = wrapper.get_friend_details(n=n, save_head_image=save_avatar)
    
            # 切换回聊天页面(GetFriendDetails 会切换到联系人页面)
            try:
                wrapper.wx.SwitchToChat()
            except:
                pass  # 如果切换失败,不影响主要功能
    
            if not friends:
                return format_result(True, "无好友数据", {"friends": []})
    
            formatted = []
            for friend in friends:
                formatted.append({
                    "name": friend.name,
                    "alias": friend.alias,
                    "remark": friend.remark,
                    "signature": friend.signature,
                    "source": friend.source,
                })
    
            return format_result(True, f"获取成功,共 {len(friends)} 个好友", {"friends": formatted})
        except Exception as e:
            logger.error(f"获取好友列表失败: {e}")
            return format_result(False, f"获取好友列表失败: {e}")
  • The @tool decorator that registers functions as MCP tools. It applies output limiting, registers the tool with name and description to TOOL_REGISTRY, and automatically generates the input schema from function signature. Used to register get_friends in api_contacts.py.
    def tool(name: Optional[str] = None, description: Optional[str] = None) -> Callable:
        """
        工具装饰器
    
        注册函数为 MCP 工具,自动应用输出限制。
    
        Args:
            name: 工具名称,默认使用函数名
            description: 工具描述
    
        Returns:
            装饰后的函数
        """
    
        def decorator(func: Callable) -> Callable:
            # 应用输出限制
            limited_func = limit_output(func)
    
            # 注册到工具注册表
            tool_name = name or func.__name__
            TOOL_REGISTRY.register(
                name=tool_name,
                func=limited_func,
                description=description or func.__doc__ or "",
            )
    
            # 返回原函数,不修改其行为
            return func
    
        return decorator
  • The handle_list_tools function that generates MCP Tool schemas from registered functions. It automatically infers input parameters from function signatures, converting Python types (int, bool, str) to JSON schema types. For get_friends, it creates a schema with 'n' (integer, default 10) and 'save_avatar' (boolean, default false) parameters.
    # MCP 协议处理器
    @MCP_SERVER.list_tools()
    async def handle_list_tools() -> list[Tool]:
        """
        处理 list_tools 请求
    
        返回所有已注册的工具列表。
        """
        tools = []
    
        for name, tool_info in TOOL_REGISTRY.get_all_tools().items():
            # 获取函数签名以推断参数
            func = tool_info["func"]
            sig = inspect.signature(func)
    
            # 构建输入模式
            input_schema = {
                "type": "object",
                "properties": {},
            }
    
            if sig.parameters:
                required = []
                for param_name, param in sig.parameters.items():
                    param_type = "string"
    
                    # 简单的类型推断
                    if param.annotation == int:
                        param_type = "integer"
                    elif param.annotation == bool:
                        param_type = "boolean"
                    elif param.annotation == float:
                        param_type = "number"
                    elif param.annotation == str:
                        param_type = "string"
    
                    input_schema["properties"][param_name] = {
                        "type": param_type,
                    }
    
                    # 检查是否有默认值
                    if param.default == inspect.Parameter.empty:
                        required.append(param_name)
                    else:
                        input_schema["properties"][param_name]["default"] = param.default
    
                if required:
                    input_schema["required"] = required
    
            tools.append(
                Tool(
                    name=name,
                    description=tool_info.get("description", ""),
                    inputSchema=input_schema,
                )
            )
    
        logger.info(f"返回工具列表: {len(tools)} 个工具")
        return tools
  • ContactInfo dataclass model that defines the structure of friend contact information returned by get_friends. Contains fields: name, alias, remark, chat_type, tags, avatar, signature, source, and mutual_groups. Provides to_dict() method for JSON serialization.
    @dataclass
    class ContactInfo:
        """
        联系人信息模型
    
        Attributes:
            name: 昵称
            alias: 微信号
            remark: 备注名
            chat_type: 聊天类型
            tags: 标签列表
            avatar: 头像路径
            signature: 个性签名
            source: 来源
            mutual_groups: 共同群聊数
        """
        name: str
        alias: Optional[str] = None
        remark: Optional[str] = None
        chat_type: ChatType = ChatType.FRIEND
        tags: list[str] = field(default_factory=list)
        avatar: Optional[str] = None
        signature: Optional[str] = None
        source: Optional[str] = None
        mutual_groups: Optional[str] = None
    
        def to_dict(self) -> dict[str, Any]:
            """转换为字典"""
            return {
                "name": self.name,
                "alias": self.alias,
                "remark": self.remark,
                "chat_type": self.chat_type.value if isinstance(self.chat_type, ChatType) else self.chat_type,
                "tags": self.tags,
                "avatar": self.avatar,
                "signature": self.signature,
                "source": self.source,
                "mutual_groups": self.mutual_groups
            }
    
        @property
        def display_name(self) -> str:
            """获取显示名称(优先使用备注)"""
            return self.remark or self.name
  • The format_result helper function used by get_friends to format the response as a JSON string. It takes success (bool), message (str), and optional data (dict) parameters and returns a formatted JSON response with structure: {success, message, data}.
    def format_result(success: bool, message: str, data: Optional[dict[str, Any]] = None) -> str:
        """
        格式化操作结果为 JSON 字符串
    
        Args:
            success: 操作是否成功
            message: 结果消息
            data: 附加数据
    
        Returns:
            JSON 格式的结果字符串
        """
        result = {
            "success": success,
            "message": message,
            "data": data or {},
        }
        return json.dumps(result, ensure_ascii=False, indent=2)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cluic/wxauto-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server