get_new_friends
Retrieve pending friend requests from WeChat, with options to filter accepted requests for contact management.
Instructions
获取新的好友请求列表。参数: acceptable (是否过滤掉已接受的好友申请,默认true)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| acceptable | No |
Implementation Reference
- Main handler function for get_new_friends tool. Retrieves new friend requests from WeChat, formats them into JSON response with friend content list. Includes error handling for WeChat initialization and API compatibility.
@tool( name="get_new_friends", description="获取新的好友请求列表。参数: acceptable (是否过滤掉已接受的好友申请,默认true)" ) def get_new_friends(acceptable: bool = True) -> str: """ 获取新的好友请求 Args: acceptable: 是否过滤掉已接受的好友申请 Returns: JSON 格式的新好友请求列表 """ wrapper = _get_wrapper() if not wrapper: return format_result(False, "微信未初始化,请先调用 wechat_initialize") try: # 调用 wxauto 的 GetNewFriends 方法 new_friends = wrapper.wx.GetNewFriends(acceptable=acceptable) # 切换回聊天页面 try: wrapper.wx.SwitchToChat() except: pass # 如果切换失败,不影响主要功能 if not new_friends: return format_result(True, "暂无新的好友请求", {"friends": []}) # 格式化结果 formatted = [] for friend in new_friends: # NewFriendElement 对象的属性 friend_info = { "content": friend.content } formatted.append(friend_info) return format_result( True, f"获取成功,共 {len(new_friends)} 个新的好友请求", {"friends": formatted} ) except AttributeError: return format_result(False, "当前微信版本不支持 GetNewFriends 方法,请升级微信或 wxautox4 版本") except Exception as e: logger.error(f"获取新好友请求失败: {e}") return format_result(False, f"获取新好友请求失败: {e}") - src/wxauto_mcp/wxauto_mcp/rpc.py:51-80 (registration)Tool decorator that registers get_new_friends into the TOOL_REGISTRY. This decorator automatically infers the input schema from function signature and applies output limits.
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 - MCP handler that dynamically builds input schema from function signatures. For get_new_friends, infers 'acceptable' as boolean parameter with default value true.
@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 - Utility function used by get_new_friends to format responses as JSON with success status, message, and optional data fields.
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 that retrieves the WeChat wrapper instance used by get_new_friends to interact with the WeChat API.
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