# How the Doctor Command Detects Working Backends in Agent‑Reach

> Learn how the Agent Reach doctor command detects working backends by checking registered backend classes and aggregating channel health status for a diagnostic report.

- Repository: [Pnant/Agent-Reach](https://github.com/Panniantong/Agent-Reach)
- Tags: internals
- Published: 2026-07-17

---

**The doctor command detects working backends by iterating over registered backend classes in `agent_reach/backends/`, invoking their `check()` methods with configuration from [`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py), and aggregating health status from dependent channels to produce a diagnostic report.**

The `doctor` command is the built‑in diagnostics tool of **Agent‑Reach** that validates environment configuration and backend connectivity before normal operations begin. When invoked, it systematically probes every supported backend adapter and its associated channels to verify that external platform integrations are functional.

## Architecture of the Doctor Command

### Entry Point and CLI Dispatch

The diagnostic process starts in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py), where the CLI parser dispatches the `doctor` sub‑command to the `Doctor` class. The `Doctor.run()` method defined in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) serves as the orchestration engine that coordinates the entire health‑check workflow.

### Backend Discovery and Registry

The `Doctor` class discovers available backends by iterating over the registry in [`agent_reach/backends/__init__.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/__init__.py). Each entry must be a subclass of `BaseBackend`, such as the default implementation found in [`agent_reach/backends/opencli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/opencli.py). This registry pattern allows the diagnostic tool to automatically detect new backends without requiring modifications to the doctor's core logic.

## Detection Mechanism Step-by-Step

### Configuration Loading

Before executing health checks, the doctor retrieves backend‑specific settings via the class method `config_key()`. This method returns a configuration key that maps to values loaded from [`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py), which aggregates YAML files and environment variables. Backends use these credentials and endpoint URLs to initialize their clients.

### Health Check Execution

Each backend implements a `check()` method that performs a lightweight validation of connectivity and authentication. The `Doctor` wraps this call in a `try/except` block: if the method returns `True`, the backend is marked as working; if it raises an exception, the error is captured and the backend is marked as failed. For example, the `OpenCliBackend` in [`agent_reach/backends/opencli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/opencli.py) verifies that its target API endpoint returns a successful response.

### Channel-Level Verification

After a backend passes its initial health check, the doctor proceeds to validate every channel that depends on that backend. Channels are defined in files under `agent_reach/channels/` and inherit from `BaseChannel`. Each channel provides its own `check()` implementation, typically performing a minimal read operation or "ping" request to the target platform. Results are aggregated under the parent backend’s entry in the final report.

## Reporting and Exit Codes

The doctor uses the **rich** library to render a colored table: green rows indicate successful backends and channels, red rows flag failures, and yellow rows denote optional components that lack configuration. The command exits with status 0 if all required backends are healthy; otherwise, it exits with a non‑zero code, enabling CI pipelines to fail fast.

## Practical Examples

### Running the Doctor Command

```bash
$ python -m agent_reach.cli doctor
╭───────────────────────────────────────╮
│   Agent‑Reach Diagnostics – Backend Status   │
╰───────────────────────────────────────╯
✅ OpenCLI backend – reachable (https://api.opencli.dev)
   ✅ Twitter channel – OK
   ✅ Reddit channel – OK
   ⚠️  YouTube channel – missing API key
❌ MCP server backend – connection refused
   ❌  MCP skill integration – unavailable

```

### Programmatic Diagnostic Invocation

```python
from agent_reach.doctor import Doctor

# Returns a dict of {backend_name: bool}

status = Doctor().run()
if not all(status.values()):
    raise RuntimeError("One or more backends are not functional")

```

### Implementing a Custom Backend for Auto‑Detection

```python

# In a new file: agent_reach/backends/myservice.py

from agent_reach.backends.base import BaseBackend

class MyServiceBackend(BaseBackend):
    @classmethod
    def config_key(cls) -> str:
        return "myservice"

    def check(self) -> bool:
        # Simple health‑check request

        resp = self.http.get(self.base_url + "/health")
        resp.raise_for_status()
        return resp.json().get("status") == "ok"

```

After adding the file and updating [`agent_reach/backends/__init__.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/__init__.py), the `doctor` command automatically probes `MyServiceBackend` on the next run.

## Summary

- The doctor command is implemented in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) and invoked via [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py).
- It discovers backends through the registry in [`agent_reach/backends/__init__.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/__init__.py).
- Each backend must implement `config_key()` for configuration lookup and `check()` for health validation.
- Channel health checks in `agent_reach/channels/` provide granular verification of platform connectivity.
- Results are displayed using rich tables, with exit codes indicating overall health status.

## Frequently Asked Questions

### What triggers a backend to fail the doctor check?

A backend fails if its `check()` method raises an exception, such as `ConnectionError` for unreachable endpoints, `AuthenticationError` for invalid credentials, or `KeyError` for missing configuration values in [`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py).

### Can I add a custom backend that the doctor command will automatically detect?

Yes. Create a new file in `agent_reach/backends/`, subclass `BaseBackend`, implement `config_key()` and `check()`, and import it in [`agent_reach/backends/__init__.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/backends/__init__.py). The doctor command will automatically include it in the next diagnostic run.

### How does the doctor command handle partial failures across channels?

The doctor aggregates results hierarchically. If a backend passes its `check()` but one of its channels fails, the backend is marked as degraded with specific channel errors listed. The overall exit code remains non‑zero if any required component fails.

### Where is the exit status logic defined in the source code?

The exit status logic resides in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) within the `Doctor.run()` method, which returns a boolean dictionary converted to a system exit code by the CLI dispatcher in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py).