# NexusDock Integrations REST API

Use NexusDock Cloud as a remote device capability discovery and durable tool execution API over plain HTTPS—no MCP client required.

- **Base URL**: `https://mcp.nexusdock.co`
- **Documentation Hub**: https://docs.nexusdock.co/
- **API Reference Guide**: https://docs.nexusdock.co/docs/reference/api
- **Interactive API Reference**: `https://mcp.nexusdock.co/docs/api`
- **Public OpenAPI 3.1 Contract**: `https://mcp.nexusdock.co/docs/openapi.json`
- **OAuth Authorization Server Metadata (RFC 8414)**: `https://mcp.nexusdock.co/.well-known/oauth-authorization-server`
- **Integrations Protected Resource Metadata (RFC 9728)**: `https://mcp.nexusdock.co/.well-known/oauth-protected-resource/v1/integrations`
- **Official Agent Skill (`nexusdock-rest`)**: https://github.com/uvwt/agentdock-skills/tree/main/skills/nexusdock-rest

> HTTPS is required in production (loopback `http://127.0.0.1` is allowed for local development only).
> Never send any `tenant_id` or Workspace selector in headers, query parameters, or JSON bodies—the Workspace is always derived solely from your validated Bearer credential.

---

## 1. Authentication: OAuth Device Flow vs Workspace PAT

All `/v1/integrations/*` endpoints accept a standard Bearer header:

```http
Authorization: Bearer <token>
```

| Method | Prefix | Recommended For | Scope & Isolation |
|---|---|---|---|
| **OAuth 2.0 Device Flow (RFC 8628)** | `ndoa_...` | AI Agents, CLIs, desktop apps, third-party apps (no localhost callback, no manual token pasting) | Bound to `resource=https://mcp.nexusdock.co/v1/integrations` and `scope=integrations`. Cannot be used on `/mcp`, and MCP OAuth tokens cannot be used here. |
| **Workspace PAT** | `ndc_...` | Single-user scripts, backend automation, CI jobs | Created in Workspace Settings (`/workspace/settings`). Grants access to both `/mcp` and `/v1/integrations/*`. Resetting invalidates the old PAT immediately. |

### OAuth 2.0 Device Flow Steps

1. **Dynamic client registration** (`POST /oauth/register`) — register a public client with `grant_types: ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"]` and `token_endpoint_auth_method: "none"` (no `redirect_uris` needed).
2. **Request device & user codes** (`POST /oauth/device_authorization`, `application/x-www-form-urlencoded`) with `client_id`, `scope=integrations`, and `resource=https://mcp.nexusdock.co/v1/integrations`.
3. **Show human-facing prompt only** — display `verification_uri_complete` (or `verification_uri`, e.g. `https://mcp.nexusdock.co/activate`) and `user_code` to the user. **Never** print or expose `device_code`, access tokens, or refresh tokens.
4. **Poll for token** (`POST /oauth/token`, `application/x-www-form-urlencoded`) with `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `device_code`, `client_id`, and `resource=https://mcp.nexusdock.co/v1/integrations`.
   - Respect `interval` (seconds). Handle `authorization_pending` (keep waiting), `slow_down` (increase interval), `access_denied`, and `expired_token`.
5. **Refresh with serialization** (`POST /oauth/token`, `grant_type=refresh_token`) — refresh tokens rotate on use; reusing an already-rotated refresh token can revoke the grant, so serialize refreshes with a lock.
6. **Revoke on logout** (`POST /oauth/revoke`) with `token` and `client_id`.

---

## 2. Standard 10-Step Execution Workflow

1. Call `GET /v1/integrations/devices` and select a device with `online: true`.
2. Call `GET /v1/integrations/capabilities?node_id=<node_id>&type=tool&q=<keyword>` to discover available Tools.
3. Immediately before executing, call `GET /v1/integrations/capabilities/{id}` to fetch the authoritative live Tool contract.
4. Read `input_schema` and `contract_hash` from the detail response. Never guess arguments from tool names, older sessions, or another device.
5. Generate **one stable `Idempotency-Key`** for this logical execution attempt. Reuse it only for transport retries of the exact same request.
6. Call `POST /v1/integrations/executions` with `Idempotency-Key`, `capability_id`, `contract_hash`, `input`, and optional `timeout_ms` (`1000..1800000`, default `120000`).
7. Observe the returned `execution.id` using SSE (`GET /v1/integrations/executions/{id}/events` with `Last-Event-ID`) or polling (`GET /v1/integrations/executions/{id}`).
8. On `succeeded`, read the final `result` from `GET /v1/integrations/executions/{id}` (and download any signed artifact URLs via `GET /artifacts/public/{node_id}/{artifact_id}/{filename}`).
9. On `failed` or `cancelled`, report the terminal status/error. Best-effort cancellation (`POST /v1/integrations/executions/{id}/cancel`) does not roll back side effects already performed by the Tool.
10. On `unknown`, **DO NOT automatically re-execute**. The Tool may already have executed with side effects. Inspect external state or ask the user before starting a new execution.

---

## 3. Public Endpoint Summary

| Group | Method | Path | Auth | Notes |
|---|---|---|---|---|
| Auth | `GET` | `/.well-known/oauth-authorization-server` | Public | RFC 8414 OAuth server metadata |
| Auth | `GET` | `/.well-known/oauth-protected-resource/v1/integrations` | Public | RFC 9728 protected resource metadata |
| Auth | `POST` | `/oauth/register` | Public | RFC 7591 dynamic public client registration |
| Auth | `POST` | `/oauth/device_authorization` | Public | RFC 8628 start Device Authorization Grant |
| Auth | `POST` | `/oauth/token` | Public | Exchange device code or rotate refresh token |
| Auth | `POST` | `/oauth/revoke` | Public | Revoke an OAuth token/grant |
| Discovery | `GET` | `/v1/integrations/devices` | Bearer | List authorized devices (`online`, `capabilities` summary) |
| Discovery | `GET` | `/v1/integrations/capabilities` | Bearer | Filter by `node_id`, `type` (`tool|skill|mcp_server`), `q` |
| Discovery | `GET` | `/v1/integrations/capabilities/{id}` | Bearer | Authoritative live `input_schema`, `output_schema`, `contract_hash` |
| Executions | `POST` | `/v1/integrations/executions` | Bearer | Create durable execution (requires `Idempotency-Key`) |
| Executions | `GET` | `/v1/integrations/executions` | Bearer | List executions (`status`, `before`, `limit=1..100`) |
| Executions | `GET` | `/v1/integrations/executions/{id}` | Bearer | Get execution detail, status, error, and final `result` |
| Executions | `POST` | `/v1/integrations/executions/{id}/cancel` | Bearer | Request best-effort cancellation |
| Executions | `GET` | `/v1/integrations/executions/{id}/events` | Bearer | SSE status stream (`Accept: text/event-stream`, `Last-Event-ID`) |
| Artifacts | `GET` / `HEAD` | `/artifacts/public/{node_id}/{artifact_id}/{filename}` | Signed URL | Download artifact returned by a Tool (`exp` + `sig` query params) |

---

## 4. Idempotency, `contract_hash`, State Machine & SSE Rules

### Idempotency & Contract Safety
- `202 Accepted`: New execution persisted and queued.
- `200 OK` with `Idempotency-Replayed: true`: Identical `Idempotency-Key` + identical request body returned the existing execution without re-running it.
- `409 CAPABILITY_SCHEMA_CHANGED`: Tool schema changed since discovery. Re-fetch `GET /v1/integrations/capabilities/{id}`, rebuild `input`, and use a **new** `Idempotency-Key` once verified.
- `409 IDEMPOTENCY_KEY_REUSED`: Same `Idempotency-Key` was already used with a different payload. Never mutate payloads under an existing key.
- `429 RATE_LIMITED`: Respect `Retry-After` (per-tenant limit: 300 creates/min, max 64 concurrent `queued/running`). Keep the same `Idempotency-Key` when retrying after backoff.

### Execution Status Semantics

| Status | Meaning | Automatic Re-execution |
|---|---|---|
| `queued` | Persisted in Cloud, not yet dispatched to device | No — wait or observe |
| `running` | Claimed and may have been dispatched to device | No — wait or observe |
| `succeeded` | Terminal success; final `result` available on detail endpoint | Not needed |
| `failed` | Terminal failure; inspect `error` | Only after evaluating error and user intent |
| `cancelled` | Cancellation processed (best effort) | No |
| `unknown` | Dispatch reached or may have reached device, final outcome unproven (disconnect/restart/timeout) | **NEVER automatically re-execute** |

### SSE (`Last-Event-ID`)
- Connect with `Accept: text/event-stream`. Reconnect with `Last-Event-ID: <version>` to resume without missing transitions.
- SSE events carry status/version metadata only—not the large final Tool output. Once a terminal status arrives (`succeeded`, `failed`, `cancelled`, `unknown`), call `GET /v1/integrations/executions/{id}` to read the complete payload.

### Signed Artifact Downloads
- When a Tool produces downloadable files/images, the result includes signed URLs pointing to `/artifacts/public/{node_id}/{artifact_id}/{filename}?exp=...&sig=...`.
- Download directly with `GET` (or inspect headers via `HEAD`) before `exp` expires; do not alter query parameters or path segments.

---

## 5. Examples

### cURL: Discover, Execute & Observe

```bash
export NEXUSDOCK_BASE_URL="https://mcp.nexusdock.co"
export NEXUSDOCK_TOKEN="ndc_or_ndoa_token"

# 1. List online devices
curl -fsS "$NEXUSDOCK_BASE_URL/v1/integrations/devices" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN"

# 2. Search tools on an online device
curl -fsS "$NEXUSDOCK_BASE_URL/v1/integrations/capabilities?node_id=node_xxx&type=tool&q=exec" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN"

# 3. Fetch live capability detail (read input_schema and contract_hash)
curl -fsS "$NEXUSDOCK_BASE_URL/v1/integrations/capabilities/cap_xxx" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN"

# 4. Create idempotent durable execution
curl -fsS -X POST "$NEXUSDOCK_BASE_URL/v1/integrations/executions" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: exec-attempt-0195c0f1-a2b3-7c4d-8e5f-0123456789ab" \
  -d '{
    "capability_id": "cap_xxx",
    "contract_hash": "sha256:...",
    "input": { "command": "git status" },
    "timeout_ms": 120000
  }'

# 5. Stream status events via SSE (resume with Last-Event-ID if reconnecting)
curl -N "$NEXUSDOCK_BASE_URL/v1/integrations/executions/exec_xxx/events" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN" \
  -H "Accept: text/event-stream"

# 6. Fetch final execution result after terminal state
curl -fsS "$NEXUSDOCK_BASE_URL/v1/integrations/executions/exec_xxx" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN"

# Optional: Request best-effort cancellation
curl -fsS -X POST "$NEXUSDOCK_BASE_URL/v1/integrations/executions/exec_xxx/cancel" \
  -H "Authorization: Bearer $NEXUSDOCK_TOKEN"
```

### Python (Standard Library Only)

```python
import json
import os
import time
import urllib.request
import uuid

BASE_URL = os.environ.get("NEXUSDOCK_BASE_URL", "https://mcp.nexusdock.co").rstrip("/")
TOKEN = os.environ["NEXUSDOCK_TOKEN"]

def api_request(method: str, path: str, body=None, extra_headers=None):
    headers = {"Authorization": f"Bearer {TOKEN}", "Accept": "application/json"}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode("utf-8")
    if extra_headers:
        headers.update(extra_headers)
    req = urllib.request.Request(f"{BASE_URL}{path}", data=data, headers=headers, method=method)
    with urllib.request.urlopen(req, timeout=30) as resp:
        return resp.status, json.loads(resp.read().decode("utf-8"))

# 1. Pick an online device
_, devices_resp = api_request("GET", "/v1/integrations/devices")
online_device = next(d for d in devices_resp["devices"] if d.get("online"))

# 2. Discover tools & read live schema
_, caps_resp = api_request("GET", f"/v1/integrations/capabilities?node_id={online_device['node_id']}&type=tool")
cap_id = caps_resp["items"][0]["id"]
_, cap_detail = api_request("GET", f"/v1/integrations/capabilities/{cap_id}")

# 3. Create execution with stable Idempotency-Key and live contract_hash
idempotency_key = f"py-{uuid.uuid4()}"
_, created = api_request(
    "POST",
    "/v1/integrations/executions",
    body={
        "capability_id": cap_detail["id"],
        "contract_hash": cap_detail["contract_hash"],
        "input": {},  # Build strictly from cap_detail["input_schema"]
        "timeout_ms": 120000,
    },
    extra_headers={"Idempotency-Key": idempotency_key},
)
exec_id = created["execution"]["id"]

# 4. Poll until terminal state (never blindly re-run on 'unknown')
while True:
    _, detail = api_request("GET", f"/v1/integrations/executions/{exec_id}")
    status = detail["execution"]["status"]
    if status in {"succeeded", "failed", "cancelled", "unknown"}:
        if status == "unknown":
            raise RuntimeError(f"Execution {exec_id} ended in unknown state; do not retry blindly.")
        print(json.dumps(detail["execution"], indent=2))
        break
    time.sleep(1.5)
```
