# Connecting Clients

> Connect an MCP client to /api/mcp with an API key or browser OAuth, provision OAuth clients, and revoke access.

*Canonical: https://makerkit.dev/docs/void-cloudflare/mcp-server/connecting-clients*

---

A client reaches `/api/mcp` with either an API key or a browser OAuth access token. Turn the matching switches on first ([Turn It On](./overview#turn-it-on)).

| I want to | Section |
|---|---|
| Connect a script or server with a key | [Connect with an API Key](#connect-with-an-api-key) |
| Let a customer connect an app in the browser | [Connect with Browser OAuth](#connect-with-browser-oauth) |
| Cut off a key or a connection | [Revoke Access](#revoke-access) |
| Look up an error code | [When It Fails](#when-it-fails) |

## What a Client Needs

- **Transport:** Streamable HTTP, JSON over `POST`, current `2026-07-28` profile. Legacy handshakes, batches and subscription streams are refused; `GET` and `DELETE` answer 405.
- **Auth:** an `x-api-key` header, or OAuth with PKCE against a client you provisioned. Never both, and never a credential in the URL.
- **Origin:** server clients send none. A browser `Origin` must match `SITE_URL` exactly.

**Which clients work:**

- The kit tests against the official TypeScript SDK (`@modelcontextprotocol/client`, pinned in `pnpm-workspace.yaml`).
- Other MCP clients work when they speak the current profile and let you set a custom header or run OAuth with a pre-registered client ID.
- The kit does not promise compatibility with named proprietary clients.

## Connect with an API Key

**Needs:** `API_ACCESS_KEYS` and `API_ACCESS_MCP` on.

The customer creates a key on **Settings → API keys** (or the organization's page) with the scopes the tools need. Then the client connects with it:

```ts
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';

async function readAccount({ endpoint, key }: { endpoint: string; key: string }) {
  const client = new Client(
    { name: 'my-integration', version: '1.0.0' },
    { versionNegotiation: { mode: 'auto' } },
  );

  try {
    await client.connect(new StreamableHTTPClientTransport(new URL(endpoint), {
      requestInit: { headers: { 'x-api-key': key } },
    }));

    const { tools } = await client.listTools();
    const result = await client.callTool({ name: 'account_context', arguments: {} });

    return { tools, account: result.structuredContent };
  } finally {
    await client.close();
  }
}

await readAccount({
  endpoint: 'https://your-app.com/api/mcp',
  key: process.env.MY_APP_API_KEY!,
});
```

- **Keep the key in the client's secret store or an env var,** never in code or a URL.
- **`listTools` returns only the tools the key's scopes allow.** The server refuses a call to any other tool.
- **A personal key** acts on the user who made it.
- **An organization key** acts on the organization. It keeps working after its creator leaves or is demoted, until someone with `apiKey: delete` revokes it.

## Connect with Browser OAuth

**Needs:** only `API_ACCESS_MCP`.

Dynamic client registration is off, so every OAuth client is one you provision.

### 1. Provision the Client

There is no UI or CLI for this. Call `provisionOwnerMcpClient` from trusted server code, signed in as a platform admin. Put it behind an admin action ([Adding Admin Pages](../admin/adding-admin-pages)) with `requireAdmin` and your own statement:

```ts
import { provisionOwnerMcpClient } from '@kit/api-access/server';

import { getApiAccessConfig } from '#/config/api-access.config.server.ts';
import { getAuth } from '#/config/auth.server.ts';

const client = await provisionOwnerMcpClient({
  auth: getAuth(),
  headers: c.req.raw.headers, // the admin's session
  server: getApiAccessConfig().mcpServer,
  input: {
    name: 'Acme Desktop',
    applicationType: 'native', // or 'web'
    redirectUris: ['http://127.0.0.1:8765/callback'],
    scopes: ['account:read', 'offline_access'],
  },
});
// client.client_id: give this to the client's developer
```

- Redirects must be HTTPS, or HTTP loopback (`127.0.0.1`, `[::1]`) for `native`. Matching is exact, port included. Up to 8.
- `scopes` must come from `mcpServer.scopes` in `config/api-access.config.server.ts`. Add new scopes there and to `apiAccessScopes`.
- Clients are public (no secret), require PKCE and always show consent.
- Ordinary users, banned users and impersonated sessions are refused (`CLIENT_PROVISIONING_DENIED`).

### 2. The Customer Connects

The client discovers the server from `/.well-known/oauth-protected-resource/api/mcp` and runs the authorization-code flow with PKCE. The customer:

1. Signs in, if needed.
2. Lands on `/api-access/consent`, sees the client name and requested permissions, and **picks one account**: personal or one organization.
3. Optionally narrows the permissions, then approves.

- **The access token is bound to that account.** Switching organizations in the app later doesn't move it. Another account needs a new authorization.
- **The member's current roles cap organization permissions,** and the server checks them again on every request.

### 3. Help Customers Find the URL

With MCP on, **Settings → Connected apps** shows a **Connect an app** panel with your server URL, a copy button and short sign-in steps. With API keys on too, it links to API keys settings and explains the `x-api-key` header.

## Revoke Access

| Credential | Where | Takes effect |
|---|---|---|
| Personal key | **Settings → API keys** → Revoke | Next request |
| Organization key | Organization **Settings → API keys** → Revoke (`apiKey: delete`) | Next request |
| Browser connection | **Settings → Connected apps** → Revoke | Next request and next token refresh |

Bans, account deletion, organization deletion and leaving an organization cut access too ([Bans and Account Deletion](../authentication/api-access#bans-and-account-deletion)). Work already authorized may finish.

## When It Fails

Refusals carry a `{ "code": … }` body and no credential:

| Code | Usual cause |
|---|---|
| `MCP_DISABLED` (404) | `API_ACCESS_MCP` is off, or the app wasn't restarted |
| `API_KEYS_DISABLED` (404) | A key sent with `API_ACCESS_KEYS` off |
| `INVALID_API_KEY` (401) | Wrong, revoked or expired key, or the owner is gone or banned |
| `INVALID_ACCESS_TOKEN` (401/403) | No `x-api-key` and no valid OAuth token |
| `MIXED_CREDENTIALS` (400) | Both `x-api-key` and `Authorization` sent |
| `PERMISSION_DENIED` (403) | A browser `Origin` that isn't your `SITE_URL` |
| `RATE_LIMITED` (429) | Over 120 requests/minute for this credential; wait `Retry-After` seconds |

Full table: [Request Error Codes](../authentication/api-access#request-error-codes).
