# How the LoopX MCP Server Hook Exposes Lifecycle Reads and Writes via the host-integration-surface-v0 Contract

> Learn how the LoopX MCP server hook uses the host-integration-surface-v0 contract to enable lifecycle reads and controlled writes without new authority.

- Repository: [huangruiteng/loopx](https://github.com/huangruiteng/loopx)
- Tags: architecture
- Published: 2026-09-02

---

**The host-integration-surface-v0 contract exposes LoopX's control-plane through a thin façade that maps host operations one-to-one with existing CLI commands, enabling MCP clients to perform lifecycle reads and controlled todo/gate/lease writes without gaining new authority.**

The `host-integration-surface-v0` protocol in the **huangruiteng/loopx** repository defines the authoritative interface between LoopX's core control-plane and external hosts such as Cursor MCP clients, CLI hooks, or loopback servers. This contract ensures that all host interactions remain thin mirrors of standard LoopX CLI behavior, preventing hosts from accumulating hidden authority while enabling deterministic lifecycle management.

## Contract Architecture and Design Principles

The contract specification in [`docs/reference/protocols/host-integration-surface-v0.md`](https://github.com/huangruiteng/loopx/blob/main/docs/reference/protocols/host-integration-surface-v0.md) establishes a strict one-to-one mapping between host operations and existing LoopX CLI commands. According to the source documentation, this design ensures that "the host merely mirrors the CLI's behaviour" rather than creating parallel authority pathways. All exposed operations must be **idempotent where possible** and **fail closed** if the host lacks appropriate credentials or state validation.

## Lifecycle Read Operations

The contract mandates that hosts expose read-only endpoints returning **compact, public-safe facts** that correspond exactly to CLI invocations. These reads must never expose raw transcripts, private file paths, or credentials (see lines 91-100 of the protocol specification).

### Health and Registry Inspection

- **`loopx doctor`**: Returns compact readiness status and identifies missing installation pieces
- **`loopx registry`**: Provides goal boundary data including adapter status, write scope, registered agents, and stop conditions
- **`quota should-run`**: Delivers the interaction contract and execution obligation for a specific goal-agent pair

Implementation note: These endpoints map directly to the CLI's JSON output format (`--format json`) ensuring consistent serialization between direct CLI usage and MCP-mediated access.

### Status and Attention Queue Monitoring

- **`loopx status`**: Exposes first-screen status projections including:
  - User-facing todos
  - Agent-assigned todos
  - Current gate state
  - Active warnings
  - Read-only projections of the task graph

### Review and Audit Access

- **`loopx review-packet`**: Generates human/controller decision packets containing agent hand-off context for specific goal IDs
- **`loopx history`**: Returns compact run IDs, classification metadata, outcome status, and blocker pointers without exposing execution transcripts

## Controlled Write Operations

Write operations follow the same CLI-mirroring pattern but enforce additional guards to prevent unauthorized mutations. All write classes require explicit validation evidence and implement dry-run previews where applicable (lines 115-124).

### Todo Lifecycle Management

**Todo claim and updates** map to `loopx todo claim/update/complete` and require:
- A registered agent ID
- An active-state lock
- Task class specification
- An optional lease key for contention management

**User and agent todo creation** via `loopx todo add --role user|agent` enforces public-safe text constraints, concrete actor attribution, and duplicate detection to prevent injection attacks.

### Gate Decisions and Human Oversight

- **`loopx operator-gate --decision`**: Requires explicit decision parameters and mandates dry-run preview before committing state changes
- **`loopx reward`**: Implements run-bound judgment with public-safe reasoning strings, requiring `--dry-run` validation before explicit write confirmation

### Task Leases and Quota Spending

**Hard lease operations** (`loopx task-lease acquire/renew`) utilize a `(goal_id, todo_id)` contention key managed independently of quota enforcement. This allows hosts to signal intent-to-work without consuming quota slots.

**State refresh and quota consumption** via `loopx refresh-state` and `loopx quota spend-slot` require validation evidence before execution and enforce a strict "one spend per completed automatic turn" policy to prevent double-counting.

## MCP Server Hook Mechanics

The MCP server implementation in [`loopx/kunluncode_goal_mode/server.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/kunluncode_goal_mode/server.py) instantiates a **FastMCP** instance that exposes the contract over HTTP. Key entry points include the `GoalModeMCPConfig` dataclass and the `create_fastmcp_server` factory function, which configure the server's routing and validation layers.

### Activation Flow

Upon initialization, the MCP hook executes a five-phase activation sequence:
1. Resolve the target goal and agent IDs from the execution context
2. Verify CLI presence and health via `loopx doctor`
3. Read the quota decision through `quota should-run` via the shared registry
4. Pass the interaction contract, goal boundary, and next-action hint to the host turn
5. Stop execution when concrete TODO or payload mutation is required, delegating scheduling and write-back to the standard LoopX lifecycle controller

### Cursor Integration

The Cursor-specific integration writes a managed MCP entry to [`.loopx-managed-mcp.json`](https://github.com/huangruiteng/loopx/blob/main/.loopx-managed-mcp.json) via the registration logic in [`loopx/slash_command_install.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/slash_command_install.py). This entry points to the FastMCP server endpoint, enabling the Cursor agent to route tool calls through the LoopX control-plane without direct filesystem access to private workspace data.

## CLI Fallback Guarantee

If the MCP server, hook, or loopback interface becomes unavailable, the contract mandates a deterministic **CLI fallback** that reproduces every exposed operation. The fallback commands—including `loopx todo claim`, `loopx quota spend-slot`, and `loopx operator-gate`—are documented as canonical equivalents in the protocol specification (lines 77-88). This requirement prevents host implementations from becoming "hidden authority" systems that bypass standard LoopX auditing.

## Public/Private Data Boundaries

The contract explicitly protects private workspace data by restricting host access to read-only projections. According to lines 14-22 of the protocol specification, hosts must never copy raw transcripts, credentials, or private file paths into LoopX state. All host-side inputs are treated as **read-only projections** (e.g., `task_graph_projection_v0`) that inform decision-making without granting write authority to sensitive underlying resources.

## Practical Implementation Examples

The following Python snippets demonstrate how hosts interact with the contract endpoints:

```python

# Lifecycle read: Quota evaluation

import requests

BASE = "http://localhost:8000/host-integration/v0"

def read_quota(goal_id, agent_id):
    """Maps to `loopx --format json quota should-run`"""
    resp = requests.get(
        f"{BASE}/quota", 
        params={"goal_id": goal_id, "agent_id": agent_id}
    )
    return resp.json()

```

```python

# Controlled write: Todo claim

def claim_todo(goal_id, todo_id, agent_id):
    """Equivalent to `loopx todo claim` with agent validation"""
    payload = {
        "goal_id": goal_id,
        "todo_id": todo_id,
        "claimed_by": agent_id,
    }
    resp = requests.post(f"{BASE}/todo/claim", json=payload)
    return resp.json()

```

```python

# Gate decision: Approval workflow

def decide_gate(gate_id, decision="approve"):
    """Maps to `loopx operator-gate --decision approve`"""
    resp = requests.post(
        f"{BASE}/gate/decision",
        json={"gate_id": gate_id, "decision": decision}
    )
    return resp.json()

```

Runnable validation examples are available in [`examples/host-integration-surface-smoke.py`](https://github.com/huangruiteng/loopx/blob/main/examples/host-integration-surface-smoke.py), which exercises the full read/write surface against a live server instance.

## Summary

- The **host-integration-surface-v0** contract defines a thin, authoritative interface between LoopX and external hosts, ensuring all operations map 1:1 to existing CLI commands.
- **Lifecycle reads** expose health, registry, status, and review data as compact, public-safe JSON without revealing raw transcripts or credentials.
- **Controlled writes** require explicit agent registration, validation evidence, and dry-run previews for todo mutations, gate decisions, and quota spending.
- The MCP server implementation in [`loopx/kunluncode_goal_mode/server.py`](https://github.com/huangruiteng/loopx/blob/main/loopx/kunluncode_goal_mode/server.py) provides HTTP-based access via FastMCP, while maintaining strict CLI fallback guarantees for deterministic behavior.
- **Public/private boundaries** prevent hosts from accessing sensitive paths, ensuring all interactions remain projections of the underlying LoopX control-plane state.

## Frequently Asked Questions

### What is the primary purpose of the host-integration-surface-v0 contract?

The contract serves as a security and consistency boundary that allows external tools like Cursor or custom dashboards to interact with LoopX without creating parallel authority systems. By mapping every host operation to an equivalent CLI command, the contract ensures that hosts cannot perform actions that the CLI itself could not perform, maintaining audit parity and preventing privilege escalation.

### How does the MCP server handle authentication and authorization?

The MCP server delegates all authorization decisions to the underlying LoopX CLI and registry system. When a host requests a write operation such as `todo/claim`, the server invokes the equivalent `loopx todo claim` command, which validates the requesting agent ID against the registered goal boundary and active-state locks. This design ensures that authentication remains centralized in the LoopX control-plane rather than distributed across host implementations.

### What happens when the MCP server is unavailable?

The contract mandates a CLI fallback mechanism where any operation available via the MCP HTTP interface must also be achievable through direct CLI invocation. For example, if the `/quota` endpoint is unreachable, users or scripts can execute `loopx --format json quota should-run` to obtain identical data. This guarantee prevents host integrations from becoming single points of failure or hidden control planes.

### Why are raw transcripts and private paths excluded from host reads?

The contract restricts reads to **compact, public-safe facts** to prevent information leakage through host integrations. Raw transcripts may contain sensitive user data, while private paths could expose internal workspace structures. By limiting hosts to projections like `task_graph_projection_v0`, LoopX ensures that external tools receive sufficient context for decision-making without compromising data security or violating workspace isolation boundaries.