Skip to main content
Glama
adrighem

Domoticz MCP Server

by adrighem

set_switch_state

Control smart switches and lights by turning them on or off using device index or name.

Instructions

Set a switch or light to On or Off.

Args: state: Must be 'On' or 'Off'. idx: Device index. name: Device name (case-insensitive).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
stateYes
idxNo
nameNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'set_switch_state' tool. It accepts state ('On'/'Off'), idx, and name, validates inputs, resolves the device index, and sends the switchlight command to Domoticz.
    @mcp.tool()
    async def set_switch_state(state: str, idx: int | None = None, name: str | None = None) -> str:
        """Set a switch or light to On or Off. 
        
        Args:
            state: Must be 'On' or 'Off'.
            idx: Device index.
            name: Device name (case-insensitive).
        """
        if idx is None and name is None:
            return '{"status": "error", "message": "Must provide either idx or name"}'
        if state.lower() not in ['on', 'off']:
            return '{"status": "error", "message": "state must be \'On\' or \'Off\'"}'
        async with create_client() as client:
            resolved_idx = await _resolve_device_idx(client, idx, name)
            if resolved_idx is None:
                return '{"status": "error", "message": "Device not found"}'
            response = await _do_request(client, "GET", f"{DOMOTICZ_API_URL}?type=command¶m=switchlight&idx={resolved_idx}&switchcmd={state.capitalize()}")
            return response.text
  • The tool is registered via the @mcp.tool() decorator on the set_switch_state function. The mcp object is a FastMCP instance ('Domoticz') created at line 70.
    @mcp.tool()
  • The input schema is defined in the function signature and docstring: state (str, required, must be 'On' or 'Off'), idx (int, optional), name (str, optional). Validation occurs at lines 589-592.
    """Set a switch or light to On or Off. 
    
    Args:
        state: Must be 'On' or 'Off'.
        idx: Device index.
        name: Device name (case-insensitive).
    """
  • Helper function _resolve_device_idx used by set_switch_state to resolve a device name or idx to a numeric idx via cached API data.
    async def _resolve_device_idx(client: "httpx.AsyncClient", idx: Optional[int] = None, name: Optional[str] = None) -> Optional[int]:
        """Resolve a device to its idx."""
        return await _resolve_idx(client, idx, name, _device_cache, f"{DOMOTICZ_API_URL}?type=command¶m=getdevices&filter=all&used=true")
  • HTTP request helper _do_request used by set_switch_state to make API calls with automatic retry on 401 (token refresh).
    async def _do_request(client: httpx.AsyncClient, method: str, url: str, **kwargs) -> httpx.Response:
        """Perform a request with a single retry on 401 Unauthorized to handle expired tokens."""
        global _oauth_token_cache
        
        try:
            resp = await client.request(method, url, **kwargs)
            if resp.status_code == 401:
                # Token might be expired. Clear cache and retry once.
                _oauth_token_cache = None
                
                # Re-fetch token (this will trigger OAuth flow if needed)
                new_token = await _fetch_oauth_token(force_refresh=True)
                if new_token:
                    # Update headers for the retry
                    if "headers" not in kwargs:
                        kwargs["headers"] = {}
                    kwargs["headers"]["Authorization"] = f"Bearer {new_token}"
                    
                    # Retry the request
                    resp = await client.request(method, url, **kwargs)
            
            resp.raise_for_status()
            return resp
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 401:
                raise Exception("Authentication failed. Please check your credentials or re-authenticate.")
            raise e
Behavior3/5

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

No annotations are provided, so the description must disclose behavior. It states it sets a state, but does not mention reversibility, authorization needs, or behavior when both idx and name are provided. It is minimally adequate.

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

Conciseness5/5

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

The description is extremely concise, using a structured Args format with no fluff. Every sentence adds value.

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

Completeness4/5

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

For a simple tool, the description captures the essential behavior. It does not cover error cases or output, but the existence of an output schema partially mitigates this.

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

Parameters3/5

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

Schema coverage is 0%, so description compensates by specifying state must be 'On' or 'Off' and naming idx and name. However, it does not explain resolution logic between idx and name or provide format details.

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 explicitly states the tool sets a switch or light to On or Off, clearly defining the action and resource. This distinguishes it from siblings like toggle_switch or set_dimmer_level.

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

Usage Guidelines4/5

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

The description implies usage for binary on/off control. While it does not explicitly exclude alternatives, the purpose is clear enough for an agent to decide when to invoke it.

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/adrighem/domoticz-mcp'

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