# How the Doctor Command in Agent Reach Tests Platform Availability

> Discover how the Agent Reach doctor command tests platform availability by running health checks and delivering a color-coded report on channel status. Essential for any Agent Reach user.

- Repository: [Pnant/Agent-Reach](https://github.com/Panniantong/Agent-Reach)
- Tags: how-to-guide
- Published: 2026-07-15

---

**The `doctor` command runs a health check by iterating over every registered platform channel, calling each channel's `check()` method, and rendering a tiered, color-coded report that shows which platforms are ready, which need configuration, and whether any errors occurred.**

The `doctor` command serves as the built-in diagnostic tool for the Agent Reach framework. It probes all supported social platforms—such as Twitter, Reddit, and YouTube—to verify connectivity and credential status. This article explains exactly how the command validates platform availability by examining the source code in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) and its interaction with the channel architecture.

## How the Doctor Command Scans Platform Channels

The core logic resides in the `check_all` function inside [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) (lines 12-35). This function acts as an orchestrator that queries every registered platform channel and aggregates their health status into a structured dictionary.

```python

# https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py#L12-L35

def check_all(config: Config) -> Dict[str, dict]:
    results = {}
    for ch in get_all_channels():
        try:
            status, message = ch.check(config)          # each channel decides ok / warn / off / error

            active = getattr(ch, "active_backend", None)
        except Exception as e:                         # doctor must survive any channel

            status, message, active = "error", f"体检异常：{e}", None
        results[ch.name] = {
            "status": status,
            "name": ch.description,
            "message": message,
            "tier": ch.tier,
            "backends": ch.backends,
            "active_backend": active,
        }
    return results

```

### The Channel Check Contract

Every platform channel inherits from a base class defined in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py). Each concrete implementation must provide a `check(config)` method that returns a tuple of `(status, message)`. The **status** string must be one of four values: `ok`, `warn`, `off`, or `error`. This contract ensures that the `doctor` command can treat Twitter, Reddit, YouTube, and any future platform identically without knowing implementation details.

### Per-Channel Resilience and Error Handling

The `try/except` block wrapping the `ch.check(config)` call (lines 20-26) guarantees that a single broken channel cannot crash the entire health report. If a third-party API is down or a channel's code raises an unexpected exception, the `doctor` command catches the error, assigns a status of `"error"`, and includes the exception message in the results. This **fail-safe design** ensures users always receive a complete availability map, even during partial system outages.

### Rich Metadata in Results

Each channel entry in the returned dictionary contains six key fields:

- **`status`** – The health indicator (`ok`, `warn`, `off`, or `error`)
- **`name`** – Human-readable description from the channel class
- **`message`** – Detailed status text (e.g., "已登录" or "需要提供 client_id")
- **`tier`** – Setup complexity level (0 = ready-to-use, 1 = needs free key/login, 2 = complex setup)
- **`backends`** – List of available backend implementations
- **`active_backend`** – Currently selected backend, if multiple exist

## Rendering the Health Report

After `check_all` aggregates the raw data, the `format_report` function (lines 47-99) transforms it into a human-readable, color-coded string using Rich markup syntax. This function organizes the output to prioritize user attention based on setup requirements.

### Tier-Based Grouping

The report groups channels by their **tier** level to separate zero-config platforms from optional integrations:

1. **Tier 0** – Channels that work immediately without API keys or complex setup
2. **Tier 1** – Channels requiring free API keys or simple login
3. **Tier 2** – Channels needing complex configuration or paid accounts

The function iterates through results and appends formatted lines with emoji-style indicators: `[green]✅[/green]` for available, `[yellow][!][/yellow]` for warnings, and `[red][X][/red]` for errors.

### Security Permission Checks

Beyond platform availability, the `doctor` command includes a security audit of the configuration file. Lines 109-125 check if [`config.yaml`](https://github.com/Panniantong/Agent-Reach/blob/main/config.yaml) (located at `Config.CONFIG_DIR / "config.yaml"`) has overly permissive Unix permissions:

```python

# https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py#L109-L125

config_path = Config.CONFIG_DIR / "config.yaml"
if config_path.exists() and sys.platform != "win0":
    try:
        mode = config_path.stat().st_mode
        if mode & (stat.S_IRGRP | stat.S_IROTH):
            lines.append("")
            lines.append("[bold red][!]  安全提示：config.yaml 权限过宽（其他用户可读）[/bold red]")
            lines.append("   修复：chmod 600 ~/.agent-reach/config.yaml")
    except OSError:
        pass

```

If the file is readable by group or other users, the report appends a warning recommending `chmod 600` to protect sensitive API credentials.

## Running the Doctor Command

You can execute the health check directly from the terminal using the CLI entry point defined in [`agent_reach/cli.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/cli.py):

```bash
$ python -m agent_reach.cli doctor
[bold cyan]Agent Reach 状态[/bold cyan]
[cyan]========================================[/cyan]
图例：[green]✅[/green] 可用  [yellow][!][/yellow] 已装但需配置/登录  [red][X][/red] 未安装

[bold]✅ 装好即用：[/bold]
  [green]✅[/green] Twitter — 已登录
  [yellow][!][/yellow]  Reddit — 需要提供 client_id
  [red][X][/red]  Facebook — 未安装

状态：[yellow]2/5[/yellow] 个渠道可用
还有 2 个可选渠道可以解锁（Bilibili、YouTube），告诉你的 Agent「帮我装 XXX」即可

```

For programmatic access, import the functions directly from [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py):

```python
from agent_reach.config import Config
from agent_reach.doctor import check_all, format_report

cfg = Config.load()
raw_status = check_all(cfg)          # → dict of per-channel results

print(format_report(raw_status))      # → human-readable Rich markup

```

## Summary

- The `doctor` command tests platform availability by calling `check_all` in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py), which iterates through all registered channels from `get_all_channels()`.
- Each channel implements a `check(config)` method (defined in [`agent_reach/channels/base.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/channels/base.py)) returning a status tuple that indicates whether the platform is ready, needs configuration, or is unavailable.
- The command uses defensive exception handling (lines 20-26) to ensure that failures in individual channels never crash the entire diagnostic report.
- Results include metadata tiers (0-2) that classify channels by setup complexity, allowing the report to prioritize zero-config platforms.
- The `format_report` function generates a color-coded, tier-grouped summary and includes a security check for [`config.yaml`](https://github.com/Panniantong/Agent-Reach/blob/main/config.yaml) file permissions (lines 109-125).
- Users can run the command via `python -m agent_reach.cli doctor` or import `check_all` and `format_report` for programmatic health monitoring.

## Frequently Asked Questions

### What platforms does the doctor command check?

The command checks every platform channel registered in the Agent Reach system, including Twitter, Reddit, YouTube, Facebook, and Bilibili. The `get_all_channels()` function dynamically discovers all available channels, so the check automatically includes any new platforms added to the codebase without requiring updates to the [`doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/doctor.py) logic.

### How does the doctor command handle API failures?

According to the source code in [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py) lines 20-26, the command wraps each channel's `check()` call in a `try/except` block. If a channel raises an exception—whether due to network timeouts, API rate limits, or code errors—the `doctor` command catches the exception, assigns a status of `"error"`, and includes the error message in the final report. This ensures the diagnostic completes even when external services are down.

### What do the tier levels mean in the doctor report?

The **tier** field categorizes channels by setup requirements: **Tier 0** channels are ready-to-use with zero configuration; **Tier 1** channels require a free API key or simple login; and **Tier 2** channels need complex setup such as paid accounts or multi-step authentication. The `format_report` function uses these tiers to group the output, showing working Tier 0 channels first before listing optional integrations that need additional configuration.

### Can I run the doctor check programmatically instead of via CLI?

Yes. You can import `check_all` and `format_report` directly from [`agent_reach/doctor.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/doctor.py), load a configuration using `Config.load()` from [`agent_reach/config.py`](https://github.com/Panniantong/Agent-Reach/blob/main/agent_reach/config.py), and pass it to `check_all()`. This returns a dictionary of results that you can process programmatically or convert to a string using `format_report()` for formatted output. This approach is useful for automated monitoring or integration into larger application health checks.