microsoft/aspire · error · RuntimeError

Not connected to AppHost

Error message

Not connected to AppHost

What it means

The client's _check_connection guard raises RuntimeError('Not connected to AppHost') when an API method (ping, authenticate, invoke_capability, etc.) is called before a connection to the AppHost server has been established, and no stored connection error exists. The client tracks a _connected flag under its lock; calling methods on a fresh or disconnected client hits this path.

Solutions

  1. Call connect() (or start the AppHost and connect) before issuing any API calls.
  2. Check the AppHost is actually running and its endpoint/port is reachable.
  3. Recreate the client after a disconnect instead of reusing the stale instance.
  4. Wrap usage in a helper that asserts client connectivity before calls.

Example fix

// before
client = AspireClient(host, port)
client.ping()
// after
client = AspireClient(host, port)
client.connect()
client.ping()
Defensive patterns

Strategy: validation

Validate before calling

def ensure_connected(client):
    if not getattr(client, '_connected', False):
        raise RuntimeError('call connect() before using the client')
    return client

Type guard

def is_ready(client) -> bool:
    return bool(getattr(client, '_connected', False))

Prevention

When it happens

Trigger: Calling ping(), authenticate(), or invoke_capability() on a client that was constructed but whose connect() was never called, failed silently, or whose connection was closed/disconnected beforehand.

Common situations: Instantiating the client and immediately calling methods; a prior connection drop set _connected=False; tests constructing the client without a running AppHost; calling methods after close/disconnect.

Understand the failure class

Background: ECONNREFUSED and "connection refused" / "could not connect to server" errors: what they mean and how to fix them — this error's family across 44 libraries.

Related errors


AI-assisted analysis of microsoft/aspire@25830f84bd (2026-09-16). Data as JSON: /api/errors/d8ebb170415ef224. Report an issue: GitHub.

Appendix: source

Thrown at src/Aspire.Hosting.CodeGeneration.Python/PythonModuleBuilder.cs:1119

                    else:
                        _logger.info("-> %s", message)
                message_str = json.dumps(message, cls=_AspireJSONEncoder)
                message_bytes = message_str.encode("utf-8")
                content_length = len(message_bytes)

                # Send with HTTP-style headers (HeaderDelimitedMessageHandler format)
                header = f"Content-Length: {content_length}\r\n\r\n"
                header_bytes = header.encode("utf-8")
                with self._lock:
                    typing.cast(_PipeSocket, self._socket).sendall(header_bytes + message_bytes)

            def _check_connection(self) -> None:
                '''Check if connected and raise stored connection error if present.'''
                with self._lock:
                    if self._connection_error:
                        raise self._connection_error
                    if not self._connected:
                        raise RuntimeError("Not connected to AppHost")

            def ping(self) -> str:
                '''Ping the server'''
                self._check_connection()
                return self._send_request("ping")

            def authenticate(self, token: str) -> None:
                '''Authenticate to the AppHost server with a session token.'''
                if not bool(self._send_request("authenticate", token)):
                    raise RuntimeError("Failed to authenticate to the AppHost server.")

            def invoke_capability(
                self,
                capability_id: str,
                args: dict[str, typing.Any] | None = None,
                kwargs: typing.Mapping[str, typing.Any] | None = None
            ) -> typing.Any:
                '''

View on GitHub (pinned to 25830f84bd)