> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usefusion.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication & Scopes

> OAuth 2.1 authorization, Nostr sign-in consent, scope hierarchy, step-up challenges, and token security for the NeuroFusion Quest MCP Server.

The NeuroFusion Quest MCP Server implements the **MCP `2026-07-28` Authorization Specification** on top of NeuroFusion's existing passwordless Nostr authentication. MCP clients obtain short-lived, audience-bound OAuth 2.1 access tokens without ever handling your Nostr private key or web session token.

## Discovery Endpoints

Unauthenticated requests to `POST /mcp` return `401 Unauthorized` with a `WWW-Authenticate` challenge pointing to the Protected Resource Metadata document:

```http theme={null}
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://neurofusionbackendprd.azurewebsites.net/.well-known/oauth-protected-resource/mcp"
```

Clients use the following discovery endpoints to configure OAuth automatically:

| Endpoint | Standard | Purpose |
| - | - | - |
| `GET /.well-known/oauth-protected-resource/mcp` | RFC 9728 | Path-scoped Protected Resource Metadata for `/mcp` |
| `GET /.well-known/oauth-protected-resource` | RFC 9728 | Root fallback Protected Resource Metadata |
| `GET /.well-known/oauth-authorization-server` | RFC 8414 | OAuth 2.1 Authorization Server Metadata |
| `GET /.well-known/openid-configuration` | OIDC Discovery | Compatibility alias returning Authorization Server Metadata |

### Protected Resource Metadata

```json theme={null}
{
  "resource": "https://neurofusionbackendprd.azurewebsites.net/mcp",
  "authorization_servers": ["https://neurofusionbackendprd.azurewebsites.net"],
  "bearer_methods_supported": ["header"],
  "scopes_supported": [
    "quests:read",
    "quests:write",
    "datasets:read",
    "datasets:write",
    "artifacts:read",
    "artifacts:write"
  ],
  "resource_name": "NeuroFusion Quest MCP Server",
  "resource_documentation": "https://docs.usefusion.ai"
}
```

> [!NOTE]
>
> Per MCP `2026-07-28`, `offline_access` is intentionally omitted from Protected Resource Metadata and `WWW-Authenticate` headers, and is advertised only in Authorization Server Metadata.

### Authorization Server Metadata

```json theme={null}
{
  "issuer": "https://neurofusionbackendprd.azurewebsites.net",
  "authorization_endpoint": "https://neurofusionbackendprd.azurewebsites.net/oauth/authorize",
  "token_endpoint": "https://neurofusionbackendprd.azurewebsites.net/oauth/token",
  "registration_endpoint": "https://neurofusionbackendprd.azurewebsites.net/oauth/register",
  "revocation_endpoint": "https://neurofusionbackendprd.azurewebsites.net/oauth/revoke",
  "response_types_supported": ["code"],
  "response_modes_supported": ["query"],
  "grant_types_supported": ["authorization_code", "refresh_token"],
  "token_endpoint_auth_methods_supported": ["none", "client_secret_post", "client_secret_basic"],
  "revocation_endpoint_auth_methods_supported": ["none", "client_secret_post", "client_secret_basic"],
  "code_challenge_methods_supported": ["S256"],
  "scopes_supported": [
    "quests:read",
    "quests:write",
    "datasets:read",
    "datasets:write",
    "artifacts:read",
    "artifacts:write",
    "offline_access"
  ],
  "client_id_metadata_document_supported": true,
  "authorization_response_iss_parameter_supported": true
}
```

## Client Registration

Two registration mechanisms are supported:

1. **OAuth Client ID Metadata Documents (CIMD — Primary)**:
   * Use an `https://` URL with a non-root path as your `client_id` (for example, `https://client.example.com/oauth/client-metadata.json`).
   * The metadata document's `client_id` must match the URL string-for-string and provide a non-empty `client_name` and `redirect_uris` (`https://` or loopback `http://localhost` / `http://127.0.0.1` / `http://[::1]`).
   * Symmetric `client_secret_*` auth methods are rejected for CIMD clients, and metadata fetches enforce SSRF protection (blocking loopback, private, and link-local IPs).

2. **Dynamic Client Registration (`POST /oauth/register` — RFC 7591)**:
   * Supported for backwards compatibility with clients that do not yet implement CIMD.
   * Supports `application_type` (`web` or `native`) and enforces HTTPS or loopback redirect URIs with no fragments or wildcards.

## Authorization & Consent Flow

**1. Start OAuth Authorization with PKCE S256**

The client opens the browser to `GET /oauth/authorize` with `response_type=code`, `client_id`, `redirect_uri`, `code_challenge`, `code_challenge_method=S256`, `resource=https://neurofusionbackendprd.azurewebsites.net/mcp`, `scope`, and `state`.

**2. Sign In with NeuroFusion Nostr Auth**

If you are not signed in to NeuroFusion, the web app redirects you to `https://usefusion.ai/auth/login` to complete the standard Nostr NIP-04 / NIP-07 login flow, then returns you to `https://usefusion.ai/oauth/authorize`.

**3. Review & Approve Scopes**

The `https://usefusion.ai/oauth/authorize` consent screen displays the client name, client URI, registration method, **redirect URI hostname** (with an explicit warning banner for `localhost`/`127.0.0.1` redirects), and interactive checkboxes so you can approve or narrow the requested scopes.

**4. Exchange Code for Access Token**

NeuroFusion redirects back to `redirect_uri` with `code`, `state`, and `iss` (RFC 9207 mix-up protection). The client exchanges the one-time code and `code_verifier` at `POST /oauth/token` with `resource=https://neurofusionbackendprd.azurewebsites.net/mcp`.

> [!NOTE]
>
> For native loopback clients (`http://127.0.0.1:<port>/callback` or `http://localhost:<port>/callback`), ephemeral port matching is supported per RFC 8252 Section 7.3 as long as the scheme, hostname, path, and query match a registered loopback redirect URI.

## OAuth Scopes & Hierarchy

Each `*:write` scope automatically implies its corresponding `*:read` scope:

| Scope | Implies | Grants Access To |
| - | - | - |
| `quests:read` | — | List organizations, list/inspect quests, view config history, cohorts, subjects, and quest media |
| `quests:write` | `quests:read` | Create, update, clone, publish, unpublish, rollback, and delete quests; generate jsPsych experiments; create cohorts; upload quest media |
| `datasets:read` | — | View dataset summaries, list/filter datasets, read dataset content, list sessions, and create/list/get/cancel async exports (including SAS download URLs) |
| `datasets:write` | `datasets:read` | Permanently delete collected datasets (with mandatory audit reason) |
| `artifacts:read` | — | List quest artifacts and read full HTML content |
| `artifacts:write` | `artifacts:read` | Create, update, publish/unpublish, and delete interactive HTML quest artifacts |
| `offline_access` | — | Issue rotating refresh tokens (30-day default lifetime) |

### Step-Up Authorization (`403 insufficient_scope`)

If a client calls a tool or reads a resource that requires a scope not present in its current token, `/mcp` responds with `403 Forbidden` and a standard RFC 6750 step-up challenge:

```http theme={null}
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="quests:write", resource_metadata="https://neurofusionbackendprd.azurewebsites.net/.well-known/oauth-protected-resource/mcp", error_description="Missing required OAuth scope: quests:write"
```

Clients can re-run authorization requesting the additional scope without disrupting other sessions.

## Token Lifecycle, Rotation & Isolation

| Security Control | Behavior |
| - | - |
| **Access token lifetime** | Short-lived JWT, default **1 hour** (`3600` seconds, configurable via `MCP_ACCESS_TOKEN_TTL_SECONDS`) |
| **Audience binding (RFC 8707)** | Every access token includes `aud: "https://neurofusionbackendprd.azurewebsites.net/mcp"` and `token_use: "mcp_access"` |
| **Strict token isolation** | MCP tokens are rejected on `/api/*` REST routes; NeuroFusion Nostr web JWTs are rejected on `/mcp` |
| **Refresh token issuance & rotation** | Issued only when **both** `offline_access` is granted **and** the client's `grant_types` includes `refresh_token`. Each `grant_type=refresh_token` request rotates the token within its token family (30-day default TTL) |
| **Reuse detection** | Replaying an already-rotated or revoked refresh token immediately revokes the entire token family |
| **Revocation (RFC 7009)** | `POST /oauth/revoke` requires client authentication (`client_id` in body or HTTP Basic auth, plus `client_secret` for confidential clients; missing or invalid client auth returns `401 invalid_client`). Only revokes tokens bound to the authenticated `client_id` (and their token family); unknown or other-client tokens return `200 OK` without revoking |

## Transport & Header Security

Requests to `POST /mcp` enforce additional MCP `2026-07-28` safeguards:

* **Origin Validation (DNS Rebinding Protection)**: When an `Origin` header is present, it must match an allowed origin (configured `FRONTEND_URL`, server origin, `https://usefusion.ai`, or `MCP_ALLOWED_ORIGINS`; loopback origins are allowed in non-production). Untrusted origins receive `403 Forbidden`.
* **Header-vs-Body Consistency**: If `MCP-Protocol-Version`, `Mcp-Method`, or `Mcp-Name` headers are sent, they must match the JSON-RPC payload (`params._meta["io.modelcontextprotocol/protocolVersion"]`, `method`, and `params.name` / `params.uri`); mismatches return `400 Bad Request`.

## Self-Hosting / Local Development Configuration

When running NeuroFusion locally or self-hosting, these optional server environment variables control the OAuth & MCP endpoints:

| Variable | Default | Description |
| - | - | - |
| `MCP_ISSUER_URL` | Request origin | Canonical OAuth 2.1 Authorization Server issuer URL (no trailing slash) |
| `MCP_RESOURCE_URI` | `${MCP_ISSUER_URL}/mcp` | Canonical MCP Protected Resource URI (`aud` claim) |
| `MCP_ACCESS_TOKEN_TTL_SECONDS` | `3600` | Access token lifetime in seconds (minimum `60`) |
| `MCP_REFRESH_TOKEN_TTL_DAYS` | `30` | Refresh token lifetime in days (minimum `1`) |
| `MCP_ALLOWED_ORIGINS` | `FRONTEND_URL` + server origin | Comma-separated allowlist for browser `Origin` checks on `/mcp` |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.