> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_08_mcp/8.3_mcp_oauth_authentication.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 8.3 MCP OAuth Authentication

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

Remote MCP Servers typically require authentication to access. Unlike internal APIs that use simple API Keys, the MCP protocol adopts the industry-standard **OAuth 2.0** protocol as its authentication scheme. OpenCode implements the complete OAuth 2.0 Authorization Code Flow, including the PKCE extension, dynamic client registration, a local callback server, and more. This section will walk through the source code implementation of each of these components.

> **Extended Explanation: OAuth 2.0 and Authorization Code Flow**
>
> OAuth 2.0 is an open authorization standard adopted by virtually all major internet services, including Google, GitHub, and Microsoft. Its core idea is: **a user can authorize a third-party application (such as OpenCode) to access their resources on a given service without sharing their password with the third-party application.**
>
> The Authorization Code Flow is the most secure authorization method in OAuth 2.0. The process works as follows:
>
> 1. The application redirects the user to the authorization server's login page.
> 2. The user logs in on the authorization server and consents to the authorization.
> 3. The authorization server redirects the user back to the application, with an "authorization code" included in the URL.
> 4. The application exchanges the authorization code for an "access token" by making a request to the authorization server.
> 5. The application uses the access token to access the user's resources.
>
> **PKCE (Proof Key for Code Exchange)** is a security enhancement to the Authorization Code Flow, specifically designed for "public clients" (such as CLI applications that cannot securely store a client\_secret). It introduces a pair of `code_verifier` (a random string) and `code_challenge` (its hash value) into the flow, ensuring that even if the authorization code is intercepted, an attacker cannot use it to obtain an access token.

## 8.3.1 mcp/auth.ts: Authentication Credential Storage

OAuth authentication involves multiple types of data that need to be persisted -- access tokens, refresh tokens, client registration information, PKCE code verifiers, CSRF state parameters, and more. The `McpAuth` module is responsible for managing the storage and retrieval of this data.

### Data Model

```typescript
// mcp/auth.ts
export namespace McpAuth {
  // OAuth tokens
  export const Tokens = z.object({
    accessToken: z.string(),             // Access token
    refreshToken: z.string().optional(), // Refresh token (optional)
    expiresAt: z.number().optional(),    // Expiration time (Unix timestamp)
    scope: z.string().optional(),        // Authorization scope
  })

  // Client registration information (from dynamic client registration)
  export const ClientInfo = z.object({
    clientId: z.string(),                      // Client ID
    clientSecret: z.string().optional(),        // Client secret
    clientIdIssuedAt: z.number().optional(),    // Issuance time
    clientSecretExpiresAt: z.number().optional(), // Expiration time
  })

  // Complete authentication entry
  export const Entry = z.object({
    tokens: Tokens.optional(),           // OAuth tokens
    clientInfo: ClientInfo.optional(),   // Client information
    codeVerifier: z.string().optional(), // PKCE code verifier
    oauthState: z.string().optional(),   // CSRF state parameter
    serverUrl: z.string().optional(),    // The server URL these credentials correspond to
  })
}
```

Each MCP Server corresponds to one `Entry`, containing all the data that needs to be persisted throughout the entire OAuth lifecycle.

### Storage Location and Security

Authentication data is stored in the user's global data directory:

```typescript
const filepath = path.join(Global.Path.data, "mcp-auth.json")
// Typical path: ~/.local/share/opencode/mcp-auth.json
```

When writing, the file permission `0o600` is used, meaning only the file owner (the current user) can read and write it, with no access for other users or groups:

```typescript
await Bun.write(file, JSON.stringify(data, null, 2), { mode: 0o600 })
```

> **Extended Explanation: Unix File Permission 0o600**
>
> In Unix/Linux systems, file permissions consist of three groups of rwx (read/write/execute) bits, corresponding to the file owner, the owning group, and other users respectively. `0o600` in octal notation expands to `rw-------`:
>
> * Owner: read and write (6 = 4+2)
> * Group: no permissions (0)
> * Others: no permissions (0)
>
> This is the standard permission setting for files storing sensitive credentials, similar to the permission requirements for SSH's `~/.ssh/id_rsa` file.

### URL Binding Validation

The `McpAuth` module implements an important security feature -- **URL binding validation**. Each set of credentials records the server URL they correspond to, and this URL is verified upon retrieval:

```typescript
export async function getForUrl(
  mcpName: string,
  serverUrl: string
): Promise<Entry | undefined> {
  const entry = await get(mcpName)
  if (!entry) return undefined

  // If no serverUrl is stored (legacy data), treat as invalid
  if (!entry.serverUrl) return undefined

  // If the URL has changed, the credentials are invalid
  if (entry.serverUrl !== serverUrl) return undefined

  return entry
}
```

This design prevents a subtle but serious security issue: if a user changes an MCP Server's URL (e.g., from a trusted server to a malicious one), old tokens should not be sent to the new URL. `getForUrl()` prevents credential misuse by comparing URLs.

### CRUD Operations

`McpAuth` provides a set of atomic update functions, each modifying only specific fields within the Entry:

```typescript
// Update OAuth tokens
export async function updateTokens(
  mcpName: string, tokens: Tokens, serverUrl?: string
): Promise<void> {
  const entry = (await get(mcpName)) ?? {}
  entry.tokens = tokens
  await set(mcpName, entry, serverUrl)
}

// Update client registration information
export async function updateClientInfo(
  mcpName: string, clientInfo: ClientInfo, serverUrl?: string
): Promise<void> { ... }

// Update PKCE code verifier
export async function updateCodeVerifier(
  mcpName: string, codeVerifier: string
): Promise<void> { ... }

// Update CSRF state parameter
export async function updateOAuthState(
  mcpName: string, oauthState: string
): Promise<void> { ... }

// Check if the token is expired
export async function isTokenExpired(mcpName: string): Promise<boolean | null> {
  const entry = await get(mcpName)
  if (!entry?.tokens) return null     // No tokens
  if (!entry.tokens.expiresAt) return false  // No expiration time, never expires
  return entry.tokens.expiresAt < Date.now() / 1000  // Compare with current time
}
```

## 8.3.2 mcp/oauth-provider.ts: OAuth Provider Implementation

The `McpOAuthProvider` class implements the `OAuthClientProvider` interface defined by the MCP SDK. It serves as the "bridge" in the OAuth flow -- mapping the MCP SDK's OAuth requirements to OpenCode's credential storage system.

### Interface Implementation

```typescript
export class McpOAuthProvider implements OAuthClientProvider {
  constructor(
    private mcpName: string,      // MCP Server name (used as storage key)
    private serverUrl: string,     // Server URL (for URL binding validation)
    private config: McpOAuthConfig,  // User-provided OAuth configuration
    private callbacks: McpOAuthCallbacks,  // Callbacks (e.g., onRedirect)
  ) {}
```

The `OAuthClientProvider` interface requires implementing the following methods, each corresponding to a step in the OAuth flow:

### Callback URL

```typescript
get redirectUrl(): string {
  return `http://127.0.0.1:${OAUTH_CALLBACK_PORT}${OAUTH_CALLBACK_PATH}`
  // -> http://127.0.0.1:19876/mcp/oauth/callback
}
```

The OAuth flow requires a callback URL where the authorization server redirects the browser after the user authorizes. OpenCode uses a local HTTP server (port 19876) to receive this callback -- this is the standard approach for implementing OAuth in CLI applications.

### Client Metadata

```typescript
get clientMetadata(): OAuthClientMetadata {
  return {
    redirect_uris: [this.redirectUrl],
    client_name: "OpenCode",
    client_uri: "https://opencode.ai",
    grant_types: ["authorization_code", "refresh_token"],
    response_types: ["code"],
    token_endpoint_auth_method: this.config.clientSecret
      ? "client_secret_post"  // Has a secret: pass via POST body
      : "none",               // No secret: public client
  }
}
```

This metadata is used during dynamic client registration (RFC 7591). Note the dynamic selection of `token_endpoint_auth_method` -- if the user has configured a `clientSecret`, the `client_secret_post` method is used for authentication; otherwise, the client is marked as public (`none`), relying on PKCE for security.

### Client Information Retrieval

```typescript
async clientInformation(): Promise<OAuthClientInformation | undefined> {
  // 1. Prefer user-configured clientId
  if (this.config.clientId) {
    return {
      client_id: this.config.clientId,
      client_secret: this.config.clientSecret,
    }
  }

  // 2. Fall back to client info from previous dynamic registration
  const entry = await McpAuth.getForUrl(this.mcpName, this.serverUrl)
  if (entry?.clientInfo) {
    // Check if the client secret has expired
    if (entry.clientInfo.clientSecretExpiresAt &&
        entry.clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
      log.info("client secret expired, need to re-register", { ... })
      return undefined  // Expired, need to re-register
    }
    return {
      client_id: entry.clientInfo.clientId,
      client_secret: entry.clientInfo.clientSecret,
    }
  }

  // 3. Neither available -> return undefined, triggering dynamic client registration
  return undefined
}
```

> **Extended Explanation: Dynamic Client Registration (RFC 7591)**
>
> In traditional OAuth, third-party applications need to pre-register with the authorization server to obtain a client\_id and client\_secret. However, for open-source CLI tools, this pre-registration model is impractical -- users may need to connect to arbitrary authorization servers.
>
> RFC 7591 defines a "Dynamic Client Registration" protocol that allows clients to register themselves with the authorization server at runtime via an HTTP request, automatically obtaining a client\_id. The MCP SDK has built-in support for this protocol -- when `clientInformation()` returns `undefined`, the SDK will attempt dynamic registration.

### Token Management

```typescript
// Read stored tokens
async tokens(): Promise<OAuthTokens | undefined> {
  const entry = await McpAuth.getForUrl(this.mcpName, this.serverUrl)
  if (!entry?.tokens) return undefined

  return {
    access_token: entry.tokens.accessToken,
    token_type: "Bearer",
    refresh_token: entry.tokens.refreshToken,
    expires_in: entry.tokens.expiresAt
      ? Math.max(0, Math.floor(entry.tokens.expiresAt - Date.now() / 1000))
      : undefined,
    scope: entry.tokens.scope,
  }
}

// Save new tokens
async saveTokens(tokens: OAuthTokens): Promise<void> {
  await McpAuth.updateTokens(this.mcpName, {
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token,
    expiresAt: tokens.expires_in
      ? Date.now() / 1000 + tokens.expires_in
      : undefined,
    scope: tokens.scope,
  }, this.serverUrl)
}
```

Note the `expires_in` calculation in the `tokens()` method -- it converts an absolute expiration time (`expiresAt`, Unix timestamp) into a relative remaining time (`expires_in`, in seconds), since the OAuth standard uses a relative time format.

### PKCE and State Parameters

```typescript
// Save the PKCE code verifier
async saveCodeVerifier(codeVerifier: string): Promise<void> {
  await McpAuth.updateCodeVerifier(this.mcpName, codeVerifier)
}

async codeVerifier(): Promise<string> {
  const entry = await McpAuth.get(this.mcpName)
  if (!entry?.codeVerifier) {
    throw new Error(`No code verifier saved for MCP server: ${this.mcpName}`)
  }
  return entry.codeVerifier
}

// Save the CSRF state parameter
async saveState(state: string): Promise<void> {
  await McpAuth.updateOAuthState(this.mcpName, state)
}

async state(): Promise<string> {
  const entry = await McpAuth.get(this.mcpName)
  if (!entry?.oauthState) {
    throw new Error(`No OAuth state saved for MCP server: ${this.mcpName}`)
  }
  return entry.oauthState
}
```

These methods are called by the MCP SDK at different stages of the OAuth flow. `codeVerifier` is used for the PKCE security mechanism, and `state` is used for CSRF (Cross-Site Request Forgery) protection -- both are key components of OAuth security best practices.

## 8.3.3 mcp/oauth-callback.ts: OAuth Callback Handling

In OAuth's Authorization Code Flow, after the user completes authorization in the browser, the authorization server needs to send the authorization code back to the application. For CLI applications, the only way to receive this callback is to start a local HTTP server. The `McpOAuthCallback` module is responsible for exactly this task.

### Callback Server

```typescript
export namespace McpOAuthCallback {
  let server: ReturnType<typeof Bun.serve> | undefined
  const pendingAuths = new Map<string, PendingAuth>()  // state -> PendingAuth
  const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000  // 5-minute timeout

  export async function ensureRunning(): Promise<void> {
    if (server) return  // Already running

    // Check if the port is occupied (another OpenCode instance may already have a callback server)
    const running = await isPortInUse()
    if (running) {
      log.info("oauth callback server already running on another instance", ...)
      return
    }

    server = Bun.serve({
      port: OAUTH_CALLBACK_PORT,  // 19876
      fetch(req) {
        const url = new URL(req.url)

        // Only handle the callback path
        if (url.pathname !== OAUTH_CALLBACK_PATH) {
          return new Response("Not found", { status: 404 })
        }

        // Extract key information from URL parameters
        const code = url.searchParams.get("code")
        const state = url.searchParams.get("state")
        const error = url.searchParams.get("error")
        // ...
      },
    })
  }
}
```

This callback server is built on Bun's built-in HTTP server and listens on the fixed port 19876. Note the idempotent design of `ensureRunning()` -- if the server is already running, it returns immediately; if the port is occupied (possibly by another OpenCode instance), it does not throw an error.

### CSRF Protection: State Parameter Validation

The core of callback handling is the validation of the State parameter, which is critical for preventing CSRF attacks:

```typescript
// 1. The state parameter must be present
if (!state) {
  const errorMsg = "Missing required state parameter - potential CSRF attack"
  return new Response(HTML_ERROR(errorMsg), { status: 400, ... })
}

// 2. The state must match a pending authentication request
if (!pendingAuths.has(state)) {
  const errorMsg = "Invalid or expired state parameter - potential CSRF attack"
  return new Response(HTML_ERROR(errorMsg), { status: 400, ... })
}
```

How the State parameter works:

```
OpenCode                    Browser                   Auth Server
  |                           |                         |
  |  Generate random state    |                         |
  |  Store in pendingAuths    |                         |
  |                           |                         |
  |  Open authorization URL   |                         |
  |  (includes state) ───────>| ──────────────────────> |
  |                           |                         |
  |                           | <────────────────────── |
  |                           |  Redirect to callback   |
  |                           |  (includes code + state)|
  |                           |                         |
  | <── HTTP callback req ────|                         |
  |  Verify state matches     |                         |
  |  Extract authorization    |                         |
  |  code                     |                         |
```

> **Extended Explanation: CSRF (Cross-Site Request Forgery) Attack**
>
> A CSRF attack tricks users into performing unintended actions without their knowledge. In the OAuth scenario, an attacker could trick a user's browser into sending a forged request to the callback URL, attempting to inject the attacker's own authorization code into the victim's application.
>
> The State parameter is OAuth 2.0's recommended CSRF protection mechanism. When initiating an authorization request, the application generates a random state value and stores it temporarily. When the callback arrives, it verifies whether the state matches -- only authorization flows initiated by the application itself can pass this verification.

### State Parameter Generation

In the `startAuth()` function, the state parameter is created using a cryptographically secure random number generator:

```typescript
// mcp/index.ts - startAuth()
const oauthState = Array.from(crypto.getRandomValues(new Uint8Array(32)))
  .map((b) => b.toString(16).padStart(2, "0"))
  .join("")
await McpAuth.updateOAuthState(mcpName, oauthState)
```

This generates a 64-character hexadecimal string (32 bytes of random data), providing 256 bits of entropy -- sufficient to resist brute-force guessing attacks.

### Callback Result Delivery

When a callback arrives successfully, the authorization code is passed back to the waiting code via a Promise's `resolve`:

```typescript
// Wait for callback
export function waitForCallback(oauthState: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const timeout = setTimeout(() => {
      if (pendingAuths.has(oauthState)) {
        pendingAuths.delete(oauthState)
        reject(new Error("OAuth callback timeout - authorization took too long"))
      }
    }, CALLBACK_TIMEOUT_MS)  // 5-minute timeout

    pendingAuths.set(oauthState, { resolve, reject, timeout })
  })
}
```

This is a classic "Promise + external resolve" pattern -- `waitForCallback` creates a Promise and stores its `resolve` function in a Map. When the callback arrives, the corresponding `resolve` function is retrieved from the Map and invoked, thereby "unwrapping" the awaiting Promise.

### Complete Authentication Flow

Putting all the components together, the complete OAuth authentication flow is as follows:

```typescript
export async function authenticate(mcpName: string): Promise<Status> {
  // 1. Initiate the OAuth flow and obtain the authorization URL
  const { authorizationUrl } = await startAuth(mcpName)

  if (!authorizationUrl) {
    // Already authenticated
    return { status: "connected" }
  }

  // 2. Retrieve the previously generated state parameter
  const oauthState = await McpAuth.getOAuthState(mcpName)

  // 3. Register the callback listener BEFORE opening the browser (to avoid race conditions)
  const callbackPromise = McpOAuthCallback.waitForCallback(oauthState)

  // 4. Open the browser for user authorization
  try {
    const subprocess = await open(authorizationUrl)
    // Wait 500ms to confirm the browser opened successfully
    await new Promise<void>((resolve, reject) => {
      const timeout = setTimeout(() => resolve(), 500)
      subprocess.on("error", (error) => {
        clearTimeout(timeout)
        reject(error)
      })
      subprocess.on("exit", (code) => {
        if (code !== null && code !== 0) {
          clearTimeout(timeout)
          reject(new Error(`Browser open failed with exit code ${code}`))
        }
      })
    })
  } catch (error) {
    // Browser failed to open (e.g., SSH remote environment), publish event for the CLI to display the URL
    Bus.publish(BrowserOpenFailed, { mcpName, url: authorizationUrl })
  }

  // 5. Wait for the callback (after the user completes authorization in the browser)
  const code = await callbackPromise

  // 6. Verify the state parameter (the final line of defense for CSRF protection)
  const storedState = await McpAuth.getOAuthState(mcpName)
  if (storedState !== oauthState) {
    await McpAuth.clearOAuthState(mcpName)
    throw new Error("OAuth state mismatch - potential CSRF attack")
  }

  // 7. Clear the state and complete authentication (exchange the authorization code for a token)
  await McpAuth.clearOAuthState(mcpName)
  return finishAuth(mcpName, code)
}
```

There is a clever engineering detail in this code: **the callback listener is registered before opening the browser** (step 3). This is to avoid a race condition -- if the user's IdP (Identity Provider) has an active SSO session, authorization may complete almost immediately after the browser opens, and the callback could arrive before `waitForCallback` has been registered. By registering first and then opening the browser, no callback is ever missed.

The `finishAuth()` function completes the final step -- exchanging the authorization code for an access token:

```typescript
export async function finishAuth(
  mcpName: string,
  authorizationCode: string
): Promise<Status> {
  const transport = pendingOAuthTransports.get(mcpName)

  // Call the transport layer's finishAuth (token exchange is handled by the MCP SDK)
  await transport.finishAuth(authorizationCode)

  // Clean up the PKCE code verifier
  await McpAuth.clearCodeVerifier(mcpName)

  // Reconnect the MCP Server (this time authentication should succeed)
  pendingOAuthTransports.delete(mcpName)
  const result = await add(mcpName, mcpConfig)
  return result.status[mcpName]
}
```

### User Experience

The OAuth callback page provides friendly user feedback. On success:

```html
<h1 style="color: #4ade80;">Authorization Successful</h1>
<p>You can close this window and return to OpenCode.</p>
<script>setTimeout(() => window.close(), 2000);</script>
```

The page automatically closes after 2 seconds. On failure, detailed error information is displayed.

For environments where a browser cannot be opened (such as SSH remote development or Docker containers), OpenCode publishes a `BrowserOpenFailed` event through the Bus event system, allowing the TUI interface to display the authorization URL so users can manually copy it and open it in a browser.

***

> **Section Summary**
>
> OpenCode's MCP OAuth authentication implementation consists of three modules: `McpAuth` handles persistent credential storage (protecting files with `0o600` permissions), `McpOAuthProvider` implements the MCP SDK's `OAuthClientProvider` interface (supporting both pre-registered client and dynamic client registration modes), and `McpOAuthCallback` receives OAuth callbacks via a local HTTP server (port 19876). The entire authentication flow employs dual security mechanisms -- PKCE extension and State parameter -- and uses URL binding validation to prevent credentials from being misused with different servers. Notable engineering details include: registering the callback before opening the browser to avoid race conditions, cryptographically secure random number generation, and graceful degradation for environments without a browser.
