Skip to main content
Glama

get_homekit_code

Retrieve HomeKit setup codes for WeMo smart devices to add them to Apple Home. Provide device name or IP address to get the required pairing code for HomeKit integration.

Instructions

Get the HomeKit setup code for a WeMo device.

Retrieves the HomeKit setup code (HKSetupCode) for devices that support HomeKit integration. This code can be used to add the device to Apple Home. The device must have been discovered via scan_network first.

Note: Not all WeMo devices support HomeKit. If a device doesn't support HomeKit or doesn't have a setup code, an error will be returned.

Args:

device_identifier: Device name (e.g., "Office Light") or IP address (e.g., "192.168.1.100")

Returns:

Dictionary containing:
- success: Boolean indicating if the code was retrieved
- device_name: Name of the device
- homekit_code: The HomeKit setup code (format: XXX-XX-XXX)
- device_ip: IP address of the device

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
device_identifierYes

Implementation Reference

  • The `get_homekit_code` function is defined as an MCP tool and handles the retrieval of the HomeKit setup code for a discovered WeMo device. It includes input validation, cache lookup/reconnection, and uses the device's `basicevent` service to fetch the code.
    @mcp.tool()
    async def get_homekit_code(device_identifier: str) -> dict[str, Any]:
        """Get the HomeKit setup code for a WeMo device.
    
        Retrieves the HomeKit setup code (HKSetupCode) for devices that support
        HomeKit integration. This code can be used to add the device to Apple Home.
        The device must have been discovered via scan_network first.
    
        Note: Not all WeMo devices support HomeKit. If a device doesn't support
        HomeKit or doesn't have a setup code, an error will be returned.
    
        Args:
        ----
            device_identifier: Device name (e.g., "Office Light") or IP address (e.g., "192.168.1.100")
    
        Returns:
        -------
            Dictionary containing:
            - success: Boolean indicating if the code was retrieved
            - device_name: Name of the device
            - homekit_code: The HomeKit setup code (format: XXX-XX-XXX)
            - device_ip: IP address of the device
    
        """
        # Validate input
        try:
            param = DeviceIdentifierParam(device_identifier=device_identifier)
        except ValidationError as e:
            return {
                "error": ERR_INVALID_PARAMS,
                "validation_errors": [
                    {"field": err["loc"][0], "message": err["msg"], "input": err["input"]}
                    for err in e.errors()
                ],
                "success": False,
            }
    
        try:
            # Try to find device in memory cache, then reconnect from file cache if needed
            device = _device_cache.get(param.device_identifier)
            if not device:
                device = await _reconnect_device_from_cache(param.device_identifier)
    
            if not device:
                return {
                    "error": f"Device '{param.device_identifier}' not found in cache",
                    "suggestion": ERR_RUN_SCAN_FIRST,
                    "available_devices": [
                        k
                        for k in _device_cache
                        if isinstance(k, str) and not k.replace(".", "").isdigit()
                    ],
                    "success": False,
                }
    
            device_name = device.name
            device_ip = getattr(device, "host", "unknown")
    
            # Check if device has basicevent (required for HomeKit info)
            if not hasattr(device, "basicevent"):
                return {
                    "error": f"Device '{device_name}' does not support HomeKit (no basicevent service)",
                    "device_name": device_name,
                    "device_type": type(device).__name__,
                    "success": False,
                }
    
            # Get HomeKit setup info in a thread pool
            loop = asyncio.get_event_loop()
    
            def get_hk_info():
                return device.basicevent.GetHKSetupInfo()
    
            hk_info = await loop.run_in_executor(None, get_hk_info)
    
            # Extract the HomeKit code
            hk_code = hk_info.get("HKSetupCode")
    
            if not hk_code:
                return {
                    "error": f"Device '{device_name}' does not have a HomeKit setup code",
                    "device_name": device_name,
                    "device_ip": device_ip,
                    "device_type": type(device).__name__,
                    "homekit_info_available": hk_info,
                    "success": False,
                }
    
            result = {
                "success": True,
                "device_name": device_name,
                "homekit_code": hk_code,
                "device_ip": device_ip,
                "device_type": type(device).__name__,
                "message": f"HomeKit setup code for '{device_name}': {hk_code}",
                "timestamp": time.time(),
            }
    
            logger.info(f"HomeKit code retrieved for '{device_name}': {hk_code}")
            return result
    
        except Exception as e:
            logger.error(f"Error getting HomeKit code: {e}", exc_info=True)
    
            # Provide helpful error messages for common issues
            error_msg = str(e)
            if "UPnPError" in error_msg or "Action" in error_msg:
                error_msg = f"Device does not support HomeKit or the HomeKit feature is not available: {error_msg}"
    
            error_response = build_error_response(
                e,
                "Get HomeKit code",
                context={"device_identifier": device_identifier},
            )
            error_response["error"] = f"Failed to get HomeKit code: {error_msg}"
            return error_response

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/apiarya/wemo-mcp-server'

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