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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

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
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing error conditions ('If a device doesn't support HomeKit or doesn't have a setup code, an error will be returned'), prerequisites, and format details. It doesn't mention rate limits or authentication requirements, but covers the essential behavioral aspects for this tool.

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 well-structured with clear sections (description, notes, args, returns) and every sentence adds value. It could be slightly more concise in the returns section, but overall it's efficiently organized with zero wasted content.

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

Completeness5/5

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

Given the tool's moderate complexity, no annotations, and the presence of an output schema, the description provides complete context. It covers purpose, prerequisites, limitations, parameter details, and return structure, making it fully adequate for an agent to understand and use this tool correctly.

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

Parameters5/5

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

With 0% schema description coverage, the description fully compensates by explaining the device_identifier parameter with clear examples ('Device name (e.g., "Office Light") or IP address (e.g., "192.168.1.100")'). This adds crucial meaning beyond the bare schema.

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

Purpose5/5

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

The description clearly states the specific action ('Get the HomeKit setup code'), target resource ('for a WeMo device'), and purpose ('can be used to add the device to Apple Home'). It distinguishes this from sibling tools like get_device_status or get_configuration by focusing specifically on HomeKit integration codes.

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

Usage Guidelines5/5

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

The description provides explicit guidance on when to use ('devices that support HomeKit integration'), prerequisites ('device must have been discovered via scan_network first'), and exclusions ('Not all WeMo devices support HomeKit'). It clearly differentiates this from general device status tools.

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

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