Skip to main content
Glama
cluic
by cluic

add_friend

Add new contacts to WeChat by searching keywords, sending verification messages, and setting permissions. This automation tool helps manage friend requests through AI assistants.

Instructions

添加新好友。参数: keywords (搜索关键词,必填), addmsg (验证消息,可选), remark (备注名,可选), tags (标签列表,可选), permission (权限,可选:朋友圈/仅聊天,默认朋友圈), timeout (超时时间,默认5秒)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
keywordsYes
addmsgNo
remarkNo
tagsNo
permissionNo朋友圈
timeoutNo

Implementation Reference

  • Main handler function for add_friend tool. Decorated with @tool to register it, takes parameters (keywords, addmsg, remark, tags, permission, timeout), validates input, calls wrapper.wx.AddNewFriend(), and returns formatted JSON results.
    @tool(
        name="add_friend",
        description="添加新好友。参数: keywords (搜索关键词,必填), addmsg (验证消息,可选), remark (备注名,可选), tags (标签列表,可选), permission (权限,可选:朋友圈/仅聊天,默认朋友圈), timeout (超时时间,默认5秒)"
    )
    def add_friend(
        keywords: str,
        addmsg: Optional[str] = None,
        remark: Optional[str] = None,
        tags: Optional[list[str]] = None,
        permission: str = "朋友圈",
        timeout: int = 5
    ) -> str:
        """
        添加新好友
    
        Args:
            keywords: 搜索关键词,可以是昵称、微信号、手机号等(必填)
            addmsg: 添加好友时的附加消息(可选)
            remark: 添加好友后的备注(可选)
            tags: 添加好友后的标签列表(可选)
            permission: 添加好友后的权限,可选值:'朋友圈' 或 '仅聊天'(默认'朋友圈')
            timeout: 超时时间(秒,默认5)
    
        Returns:
            JSON 格式的操作结果
        """
        if not keywords:
            return format_result(False, "搜索关键词不能为空")
    
        wrapper = _get_wrapper()
        if not wrapper:
            return format_result(False, "微信未初始化")
    
        try:
            # 调用 AddNewFriend 方法
            response = wrapper.wx.AddNewFriend(
                keywords=keywords,
                addmsg=addmsg,
                remark=remark,
                tags=tags or [],
                permission=permission,
                timeout=timeout
            )
    
            # 切换回聊天页面
            try:
                wrapper.wx.SwitchToChat()
            except:
                pass  # 如果切换失败,不影响主要功能
    
            # 检查响应
            if hasattr(response, 'success') and response.success:
                return format_result(
                    True,
                    f"已发送好友请求: {keywords}",
                    {"keywords": keywords, "remark": remark, "tags": tags}
                )
            else:
                error_msg = getattr(response, 'message', '添加好友失败')
                return format_result(False, f"添加好友失败: {error_msg}")
    
        except Exception as e:
            logger.error(f"添加好友失败: {e}")
            return format_result(False, f"添加好友失败: {e}")
  • The @tool decorator that registers functions as MCP tools. Applies output limiting via limit_output wrapper and registers to TOOL_REGISTRY with name, function, and description.
    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
  • Helper function format_result() that formats operation results as JSON strings with success status, message, and optional data dictionary. Used by add_friend to return standardized responses.
    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)
  • Helper function _get_wrapper() that retrieves the WeChatWrapper instance. Used by add_friend to get access to WeChat automation functionality.
    def _get_wrapper():
        """获取 WeChatWrapper 实例"""
        if not WECHAT_AVAILABLE:
            return None
        try:
            return get_wechat()
        except Exception as e:
            logger.error(f"获取 WeChat 实例失败: {e}")
            return None
  • ToolRegistry class that manages all registered MCP tools. The register() method stores tool metadata (name, func, description, group, unsafe flag) and maintains groups. Used by the @tool decorator to register add_friend.
    class ToolRegistry:
        """
        工具注册表
    
        管理所有已注册的 MCP 工具,提供扩展分组功能。
        """
    
        def __init__(self) -> None:
            self._tools: dict[str, dict[str, Any]] = {}
            self._groups: dict[str, list[str]] = {}
    
        def register(
            self,
            name: str,
            func: Callable,
            group: str = "default",
            description: Optional[str] = None,
            unsafe: bool = False,
        ) -> None:
            """
            注册工具
    
            Args:
                name: 工具名称
                func: 工具函数
                group: 扩展分组
                description: 工具描述
                unsafe: 是否为不安全操作
            """
            self._tools[name] = {
                "func": func,
                "group": group,
                "description": description,
                "unsafe": unsafe,
            }
    
            if group not in self._groups:
                self._groups[group] = []
            self._groups[group].append(name)
    
            logger.debug(f"已注册工具: {name} (分组: {group}, 不安全: {unsafe})")
    
        def get_tool(self, name: str) -> Optional[dict[str, Any]]:
            """获取指定工具"""
            return self._tools.get(name)
    
        def get_group(self, group: str) -> list[str]:
            """获取指定分组的所有工具名称"""
            return self._groups.get(group, [])
    
        def get_all_tools(self) -> dict[str, dict[str, Any]]:
            """获取所有工具"""
            return self._tools.copy()
    
        def get_all_groups(self) -> dict[str, list[str]]:
            """获取所有分组"""
            return self._groups.copy()
    
        def is_unsafe(self, name: str) -> bool:
            """检查工具是否为不安全操作"""
            tool_info = self._tools.get(name)
            return tool_info.get("unsafe", False) if tool_info else False
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions a timeout parameter with default 5 seconds, which hints at potential delays or failures, but doesn't describe what happens on success/failure, whether the operation is reversible, what permissions are needed, or how it interacts with the friend request workflow. The description is minimal and leaves critical behavioral aspects unspecified.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately concise and front-loaded with the core purpose. The parameter explanations are efficiently listed in a single sentence with clear labels. No wasted words, though the structure could be slightly improved with bullet points or separation of purpose from parameters.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a mutation tool (adding friends) with no annotations and no output schema, the description is incomplete. It doesn't explain what the tool returns on success/failure, error conditions, side effects, or how it fits into the broader friend management workflow. The parameter semantics are helpful, but critical behavioral context is missing.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It provides meaningful semantics for all 6 parameters: 'keywords' as search terms (required), 'addmsg' as verification message, 'remark' as nickname, 'tags' as tag list, 'permission' with enum values (朋友圈/仅聊天), and 'timeout' with default. This adds substantial value beyond the bare schema, though it doesn't explain parameter interactions or constraints.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as '添加新好友' (add new friend), which is a specific verb+resource combination. It distinguishes from siblings like 'accept_new_friend' (which accepts pending requests) and 'get_friends' (which retrieves existing friends). However, it doesn't explicitly mention how it differs from these siblings beyond the basic action.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., whether the friend must be found via search first), when not to use it (e.g., for existing friends), or clarify the relationship with 'accept_new_friend' for handling incoming friend requests.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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