# space-doctor

Adopt this skill: https://proskills.md/skills/other/huggingface-hf-mcp-server-monitor-distribution-skills-space-doctor

Page: https://proskills.md/skills/other/huggingface-hf-mcp-server-monitor-distribution-skills-space-doctor
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: monitor/distribution/skills/space-doctor/SKILL.md
size: 7198
upstream: https://github.com/huggingface/hf-mcp-server/blob/main/monitor/distribution/skills/space-doctor/SKILL.md

````text
---
name: space-doctor
description: Diagnose broken Hugging Face Gradio Spaces from their actual logs and pinned source, then prepare a minimal verified source fix as candidate files. Use for scheduled Space monitoring, BUILD_ERROR or RUNTIME_ERROR triage, Gradio and ZeroGPU failures, source analysis, and patch preparation. Read-only against the Hub - it never uploads, publishes, or restarts anything.
compatibility: "Requires Python 3.10+ and fast-agent shell access. Remote reads require either a connected Hugging Face MCP server or the hf CLI."
metadata:
  author: space-doctor
  version: "2.0.0"
---

# Space Doctor

Diagnose a broken Hugging Face Space and, when a narrow reversible source fix is
appropriate, write the complete fixed files into the candidate directory you
were given. You have **no Hub write access**: never attempt an upload, PR,
restart, or any other mutation. The parent process opens a PR from your
candidate files and performs any restart itself.

Use fast-agent for reasoning and Hub reads. Diagnose from the observed failure,
actual Hub logs, and the pinned source; static patterns and generic automated
rewrites are not a repair decision.

## Scheduled contract

A scheduled request provides the Space ID, exact failing revision, run ID,
observed status/stage/detail, previous restart outcome for that revision (when
one exists), and a workspace containing a `candidate/` directory. Treat the
restart outcome as evidence, not proof that the current failure has the same
cause. Emit exactly one final structured result matching the configured JSON
schema, only after all work is complete:

- `status: "fix-proposed"` with `changed_files`, `fix_summary`, and `pr_title`
  when you have written complete fixed files (paths relative to the Space
  repository root) into `candidate/`.
- `status: "needs-human"` with `needs_human_reason` otherwise.

Diagnose exactly the requested revision. If the Space has moved to a different
revision, report `needs-human` with reason `revision-changed`. Never place
credentials, tokens, or local filesystem paths in any output field.

## Workflow

### 1. Inspect remote state

Prefer connected Hugging Face MCP tools. With the `hf` CLI:

```bash
hf spaces info <namespace/name> --expand runtime --format json
hf spaces logs <namespace/name> --tail 300
hf spaces logs <namespace/name> --build --tail 300   # for BUILD_ERROR
```

Record runtime stage, hardware, revision, `runtime.raw.errorMessage`, and the
first actionable error. Read both build and runtime logs when relevant and
compare them with the observed status/stage/detail supplied in the request.
Always use the full 40-character repository SHA. Do not treat `RUNNING` alone
as healthy.

### 2. Acquire source at the failing revision

```bash
mkdir -p <workspace>/source
hf download <namespace/name> --repo-type space \
  --revision <full-sha> --local-dir <workspace>/source \
  --exclude '*.safetensors' --exclude '*.safetensors.index.json' \
  --exclude '*.bin' --exclude '*.pt' --exclude '*.pth' --exclude '*.ckpt' \
  --exclude '*.onnx' --exclude '*.gguf' --exclude '*.h5' --exclude '*.tflite'
```

Never download a moving default branch when diagnosing a specific failure.
Acquire source, configuration, and dependency manifests needed to reproduce the
failure, but do not download model weights or launch a large model locally. If
a required source file is absent, fetch that named file at the same full SHA.

### 3. Run deterministic checks

Read the source and log context yourself. Compile Python without writing
`__pycache__` into the tree:

```bash
python3 -I -c '
import pathlib, sys
root = pathlib.Path(sys.argv[1])
for path in sorted(root.rglob("*.py")):
    compile(path.read_text(encoding="utf-8"), str(path), "exec")
' <workspace>/source
```

Classify findings by full SHA, stage, and timestamp. If a new build stops
earlier than a historical runtime failure, report the old failure as superseded
rather than the active root cause.

### 4. Decide whether a fix is safe

Report `needs-human` when:

- actual Space runtime evidence establishes an authentication, permissions,
  secrets, or grants failure and no independent code fix is available;
- billing, storage, or hardware must change;
- the failure appears transient or platform-wide;
- a fix would change product behavior or model choice;
- dependency resolution needs a broad or major-version upgrade;
- no clear root cause is supported by logs and source.

Never repair access by adding or rotating a secret. Safe candidates are narrow,
reversible fixes directly supported by a deterministic failure.

### 5. Prepare the candidate

Make a source-aware edit only when the logs and source establish a narrow,
reversible root cause. First copy the complete acquired source tree to
`<workspace>/verify/` and edit that complete tree. Do not edit a partial
candidate directory. Once verified, create `<workspace>/candidate/` containing
only each changed file's complete contents at its repository-relative path; list
exactly those paths in `changed_files`.

ZeroGPU rules:

- eager module-scope model loading and `.to("cuda")` placement are normally
  correct after `import spaces`; actual CUDA computation belongs inside
  `@spaces.GPU`;
- do not move model construction into a request handler merely to make it lazy;
- do not add platform-managed `gradio`, `spaces`, or `huggingface_hub` to
  `requirements.txt` solely because they are imported.

### 6. Verify before reporting

Before reporting `fix-proposed`:

- compile all modified Python and relevant entrypoint source in the complete
  `<workspace>/verify/` tree with in-memory `compile(...)`, never `py_compile`;
- inspect the complete verified tree, not the partial candidate, and confirm
  the root-cause failure is gone or directly mitigated without a new error;
- compare `source/` and `verify/`, then ensure `candidate/` contains only the
  changed complete files, with no secret, cache, run artifact, or unrelated
  file.

For dependency repairs, reconstruct the exact platform install inputs from the
failing build (dependency file, injected Gradio/Spaces/torch requirements,
Python version) and verify the resolution; a reduced synthetic resolver is
exploratory evidence only. For gated models, verify authenticated read access
without downloading weights when authorized credentials are available. An
unauthenticated model probe returning 401/403 does not establish an access
failure in the actual Space runtime: the Space may have its own authorized
credentials. Do not infer a human hold from that probe alone (including Krea).
A verified independent code repair may be `fix-proposed` for a PR even when
model access remains unverified. Include a warning finding describing the probe
context and verification limitation; do not claim full runtime success.
For access issues, report `needs-human` only when actual Space runtime evidence
establishes access failure and no independent fix is available. Never add,
rotate, or expose secrets to repair access. Do not launch a large model locally.

Finally, re-read the remote revision. If it no longer matches the requested
revision, report `needs-human` with reason `revision-changed`.
````

## File: README.md
upstream: https://github.com/huggingface/hf-mcp-server/blob/main/README.md

````text
# Hugging Face Official MCP Server 

<img src='https://github.com/evalstate/hf-mcp-server/blob/main/hf-logo.svg' width='100'>

Welcome to the official Hugging Face MCP Server 🤗. Connect your LLM to the Hugging Face Hub and thousands of Gradio AI Applications.

## Installing the MCP Server

Follow the instructions below to get started:

<details>
<summary>Install in <b>Claude Desktop</b> or <b>claude.ai</b></summary>
<br />

Click [here](https://claude.ai/redirect/website.v1.67274164-23df-4883-8166-3c93ced276be/directory/37ed56d5-9d61-4fd4-ad00-b9134c694296) to add the Hugging Face connector to your account. 

Alternatively, navigate to [https://claude.ai/settings/connectors](https://claude.ai/settings/connectors), and add "Hugging Face" from the gallery.

<img src='docs/claude-badge.png' width='50%' align='center' />

</details>

<details>
<summary>Install in <b>Claude Code</b></summary>
<br />

Enter the command below to install in <b>Claude Code</b>:

```bash
claude mcp add hf-mcp-server -t http https://huggingface.co/mcp?login
```

Then start `claude` and follow the instructions to complete authentication.

```bash
claude mcp add hf-mcp-server \
  -t http https://huggingface.co/mcp \
  -H "Authorization: Bearer <YOUR_HF_TOKEN>"
```

</details>

<details>
<summary>Install in <b>Gemini CLI</b></summary>
<br />

Enter the command below to install in <b>Gemini CLI</b>:

```bash
gemini mcp add -t http huggingface https://huggingface.co/mcp?login
```

Then start `gemini` and follow the instructions to complete authentication.

</details>

<details>

<summary>Install in <b>VSCode</b></summary>
<br />

Click <a href="vscode:mcp/install?%7B%22name%22%3A%22huggingface%22%2C%22gallery%22%3Atrue%2C%22url%22%3A%22https%3A%2F%2Fhuggingface.co%2Fmcp%3Flogin%22%7D">here</a> to add the Hugging Face connector directly to VSCode. Alternatively, install from the gallery at [https://code.visualstudio.com/mcp](https://code.visualstudio.com/mcp): 

<img src='docs/vscode-badge.png' width='50%' align='center' />

If you prefer to configure manually or use an auth token, add the snippet below to your `mcp.json` configuration:

```JSON
"huggingface": {
    "url": "https://huggingface.co/mcp",
    "headers": {
        "Authorization": "Bearer <YOUR_HF_TOKEN>"
    }
```

</details>

<details>
<summary>Install in <b>Cursor</b></summary>
<br />

Click <a href="https://cursor.com/en/install-mcp?name=Hugging%20Face&config=eyJ1cmwiOiJodHRwczovL2h1Z2dpbmdmYWNlLmNvL21jcD9sb2dpbiJ9">here</a> to install the Hugging Face MCP Server directly in <b>Cursor</b>. 

If you prefer to use configure manually or specify an Authorization Token, use the snippet below:

```JSON
"huggingface": {
    "url": "https://huggingface.co/mcp",
    "headers": {
        "Authorization": "Bearer <YOUR_HF_TOKEN>"
    }
```
</details>

Once installed, navigate to https://huggingface.co/settings/mcp to configure your Tools and Spaces.

> [!TIP]
> Add ?no_image_content=true to the URL to remove ImageContent blocks from Gradio Servers.

![hf_mcp_server_small](https://github.com/user-attachments/assets/d30f9f56-b08c-4dfc-a68f-a164a93db564)

## Quick Guide (Repository Packages)

This repo contains:

 - (`/mcp`) MCP Implementations of Hub API and Search endpoints for integration with MCP Servers. 
 - (`/app`) An MCP Server and Web Application for deploying endpoints.

### MCP Server

The following transports are supported:

- STDIO 
- StreamableHTTP in Stateless JSON Mode (**StreamableHTTPJson**)

The Web Application and HTTP Transports start by default on Port 3000.

The StreamableHTTP service is available at `/mcp`. Although not strictly enforced by the specification, this is a common convention.

The public Streamable HTTP deployment serves its MCP Server Card at `/mcp/server-card`. The public card advertises the canonical `https://huggingface.co/mcp` endpoint without authentication-specific query parameters; loopback deployments and explicit non-Hugging Face hosts in `MCP_ALLOWED_HOSTS` advertise their own `/mcp` endpoint. Card responses support cache revalidation with an `ETag`.

The Web Application at `/metrics` reports server status and MCP method metrics.

The **Skills** tab shows process-local catalog health and live Skills activity, filtered by time window (15m/1h/24h), client name/version, method, and outcome. It separates metadata probes (`skills/list`, `skills/get`, directory reads) from successful `SKILL.md` and supporting-file content reads; retrieval does not prove execution or complete installation. Client names/versions are self-reported. Activity is capped at 10,000 events and 24 hours, resets on restart, and flags incomplete coverage. It is independent of `LOG_SKILL_EVENTS`; historical events remain in the configured dataset's `skills/YYYY-MM-DD/` logs. Live activity currently covers the `streamableHttpJson` transport. Health polling never loads/refreshes the catalog and explicitly warns that manifest byte-size verification is not yet implemented. Skills dashboard telemetry contains no target URIs, user hashes, session IDs, or file contents.

The Management Web interface can be placed behind an optional lightweight shared-password gate using `METRICS_PAGE_PASSWORD`. Browser visits to `/` redirect to the MCP welcome page at `/mcp`. Tool selection is resolved independently for each request from the optional Hugging Face user configuration API and the `bouquet`/`mix` query parameters. Note to security researches and bots, this is intentionally lightweight and not considered sensitive or protected data.

Use `?bouquet=openai` to expose Hub filesystem, repository search, details and creation, dynamic Space, Jobs, and sandbox tools. Repository creation, Jobs, dynamic Space, and sandbox tools require Hugging Face authentication.

### Running Locally

You can run the MCP Server locally with either `npx` or `docker`. 

```bash
npx @llmindset/hf-mcp-server       # Start in STDIO mode
npx @llmindset/hf-mcp-server-http  # Start in stateless Streamable HTTP JSON mode
```

To run with docker: 

```bash
docker pull ghcr.io/evalstate/hf-mcp-server:latest
docker run --rm -p 3000:3000 ghcr.io/evalstate/hf-mcp-server:latest
```
![image](https://github.com/user-attachments/assets/2fc0ef58-2c7a-4fae-82b5-e6442bfcbd99)

All commands above start the Management Web interface on http://localhost:3000/metrics. Browser visits to http://localhost:3000/ redirect to the MCP welcome page at http://localhost:3000/mcp. See [Environment Variables](#Environment Variables) for configuration options. Docker defaults to Streamable HTTP (JSON RPC) mode.

## Development

This project uses `pnpm` for build and development. Corepack is used to ensure everyone uses the same pnpm version (10.12.3).

For OAuth discovery, dynamic registration, or Client ID Metadata Document diagnostics, see
[`docs/oauth-diagnostics.md`](docs/oauth-diagnostics.md) and run `pnpm oauth:diagnose`.

Benchmark harnesses, historical results, and optimization plans are maintained
in the separate [`hf-mcp-optimise`](docs/benchmarking.md) workspace.

```bash
# Install dependencies
pnpm install

# Build all packages
pnpm build
```

### Build Commands

`pnpm run clean` -> clean build artifacts

`pnpm run build` -> build packages

`pnpm run start` -> start the mcp server application

`pnpm run buildrun` -> clean, build and start

`pnpm run dev` -> concurrently watch `mcp` and start dev server with HMR

## Docker Build

Build the image:
```bash
docker build -t hf-mcp-server .
```

Run with default settings (Streaming HTTP JSON Mode), with the dashboard at `/metrics` on Port 3000.
HTTP clients must send a Hugging Face token in the `Authorization: Bearer` header:
```bash
docker run --rm -p 3000:3000 hf-mcp-server
```

Run STDIO MCP Server:
```bash
docker run -i --rm -e TRANSPORT=stdio -p 3000:3000 -e DEFAULT_HF_TOKEN=hf_xxx hf-mcp-server
```

`TRANSPORT` can be `stdio` or `streamableHttpJson` (default).

### Transport Endpoints

The different transport types use the fo
````
