CoplayDev/unity-mcp · error · ValueError

unity_instance value must not be empty.

Error message

unity_instance value must not be empty.

What it means

Raised by UnityInstanceMiddleware.resolve when the supplied unity_instance string is empty after stripping whitespace. It is an input-validation guard at the top of the resolver so downstream port/hash lookups never see a blank value.

Source

Thrown at Server/src/transport/unity_instance_middleware.py:154

                    raise
                logger.debug("Stdio instance discovery failed (%s)", type(exc).__name__, exc_info=True)

        return results

    async def _resolve_instance_value(self, value: str, ctx) -> str:
        """
        Resolve a unity_instance string to a validated instance identifier.

        Accepts:
          - Bare port number like "6401" (stdio only) -> resolved Name@hash
          - "Name@hash" exact match
          - Hash prefix (unique prefix match against running instances)

        Raises ValueError with a user-friendly message on failure.
        """
        value = value.strip()
        if not value:
            raise ValueError("unity_instance value must not be empty.")

        transport = (config.transport_mode or "stdio").lower()

        # Port number (stdio only) — resolve to Name@hash via status file lookup
        if value.isdigit():
            if transport == "http":
                raise ValueError(
                    f"Port-based targeting ('{value}') is not supported in HTTP transport mode. "
                    "Use Name@hash or a hash prefix. Read mcpforunity://instances for available instances."
                )
            port_int = int(value)
            instances = await self._discover_instances(ctx)
            for inst in instances:
                if getattr(inst, "port", None) == port_int:
                    return inst.id
            available = ", ".join(
                f"{getattr(i, 'id', '?')} (port {getattr(i, 'port', '?')})"
                for i in instances

View on GitHub (pinned to c21bf496bc)

Solutions

  1. Omit the unity_instance argument entirely so the middleware auto-selects, rather than sending an empty string.
  2. Validate the argument is non-empty before constructing the tool call.
  3. Fix the upstream source of the value (env var, config, UI field) so it carries a real Name@hash or hash prefix.

Example fix

// before
unity_instance = os.environ.get('UNITY_INSTANCE', '')  # '' when unset
await call_unity_tool('manage_gameobject', {...}, unity_instance=unity_instance)
// after
unity_instance = os.environ.get('UNITY_INSTANCE') or None
await call_unity_tool('manage_gameobject', {...}, unity_instance=unity_instance)
Defensive patterns

Strategy: validation

Validate before calling

if unity_instance is not None:
    assert unity_instance.strip(), 'unity_instance must be non-empty if provided'
unity_instance = unity_instance.strip() or None

Type guard

def is_valid_instance_token(v: str | None) -> bool:
    return v is None or v.strip() != ''

Try / catch

try:
    await call_unity_tool(cmd, params, unity_instance=unity_instance)
except ValueError as e:
    if 'must not be empty' in str(e):
        unity_instance = None
        await call_unity_tool(cmd, params)

Prevention

When it happens

Trigger: A tool call passes unity_instance='' or a whitespace-only string (e.g. a UI field left blank, or a templated value that resolved to empty). The strip() check at unity_instance_middleware.py:152-154 fails.

Common situations: Client binds an empty env var into the unity_instance argument; a script interpolates an unset variable; the user cleared the active-instance field but the client still sent the key with an empty value.

Related errors


AI-assisted analysis of CoplayDev/unity-mcp@c21bf496bc (2026-08-13). Data as JSON: /api/errors/aae7c40145725442. Report an issue: GitHub.