> 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.4_mcp_configuration.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 8.4 MCP Configuration

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

***

In the previous three sections, we dove deep into MCP's protocol concepts, Client implementation, and OAuth authentication. This section returns to the user's perspective, examining how to configure MCP Servers in OpenCode and the data structure of the Resource model.

## 8.4.1 mcpServers Configuration Structure

OpenCode's MCP configuration is defined through the `mcp` field in `opencode.json` (project-level) or the global configuration file. The configuration system uses Zod for strict type validation.

### Local MCP Server Configuration (McpLocal)

```typescript
// config/config.ts
export const McpLocal = z.object({
  type: z.literal("local"),      // Type identifier
  command: z.string().array(),    // Command and arguments array
  environment: z.record(z.string(), z.string()).optional(),  // Environment variables
  enabled: z.boolean().optional(),   // Whether enabled (default true)
  timeout: z.number().int().positive().optional(),  // Timeout (milliseconds)
}).strict()
```

A typical local MCP Server configuration example:

```json
{
  "mcp": {
    "filesystem": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
      "environment": {
        "NODE_ENV": "production"
      },
      "timeout": 10000
    }
  }
}
```

Configuration field reference:

| Field         | Type                     | Description                                                                                     |
| ------------- | ------------------------ | ----------------------------------------------------------------------------------------------- |
| `type`        | `"local"`                | Identifies this as a local MCP Server                                                           |
| `command`     | `string[]`               | Startup command; the first element is the executable, the rest are arguments                    |
| `environment` | `Record<string, string>` | Additional environment variables (merged on top of the current process's environment variables) |
| `enabled`     | `boolean`                | Whether enabled; when `false`, no connection attempt is made                                    |
| `timeout`     | `number`                 | Connection and request timeout (milliseconds), default 30,000ms                                 |

The `command` field uses an array format rather than a string, which avoids shell injection security risks and ensures paths with spaces are handled correctly. When starting a local MCP Server, OpenCode destructures this array:

```typescript
const [cmd, ...args] = mcp.command
// For example: cmd = "npx", args = ["-y", "@some/mcp-server"]
```

### Remote MCP Server Configuration (McpRemote)

```typescript
export const McpRemote = z.object({
  type: z.literal("remote"),     // Type identifier
  url: z.string(),               // Remote server URL
  enabled: z.boolean().optional(),   // Whether enabled
  headers: z.record(z.string(), z.string()).optional(),  // Custom request headers
  oauth: z.union([McpOAuth, z.literal(false)]).optional(),  // OAuth configuration
  timeout: z.number().int().positive().optional(),  // Timeout
}).strict()
```

Remote MCP Server configuration examples:

```json
{
  "mcp": {
    "remote-tools": {
      "type": "remote",
      "url": "https://mcp.example.com/v1",
      "headers": {
        "X-API-Key": "sk-..."
      }
    },
    "oauth-server": {
      "type": "remote",
      "url": "https://mcp.another.com",
      "oauth": {
        "clientId": "my-app-id",
        "scope": "read write"
      }
    },
    "simple-remote": {
      "type": "remote",
      "url": "https://mcp.simple.com",
      "oauth": false
    }
  }
}
```

| Field     | Type                     | Description                                                    |
| --------- | ------------------------ | -------------------------------------------------------------- |
| `type`    | `"remote"`               | Identifies this as a remote MCP Server                         |
| `url`     | `string`                 | The remote server's URL (StreamableHTTP/SSE endpoint)          |
| `headers` | `Record<string, string>` | Custom HTTP request headers (for API Key authentication, etc.) |
| `oauth`   | `McpOAuth \| false`      | OAuth configuration; `false` disables OAuth                    |
| `enabled` | `boolean`                | Whether enabled                                                |
| `timeout` | `number`                 | Timeout (milliseconds)                                         |

### OAuth Configuration (McpOAuth)

```typescript
export const McpOAuth = z.object({
  clientId: z.string().optional(),     // OAuth Client ID
  clientSecret: z.string().optional(), // OAuth Client Secret
  scope: z.string().optional(),        // Requested permission scope
}).strict()
```

There are three modes for OAuth configuration:

1. **Auto-discovery mode** (default): The `oauth` field is omitted or provided as an empty object `{}`. When connecting to a remote Server, OpenCode automatically detects whether OAuth is required and attempts dynamic client registration.
2. **Pre-registered client mode**: A `clientId` (and optionally a `clientSecret`) is provided. This is suitable for scenarios where the client has already been registered with the authorization server.
3. **Disabled mode**: Set `oauth: false`. This is suitable for remote Servers that do not require OAuth (e.g., services using API Keys or with no authentication).

The handling logic in the source code:

```typescript
// mcp/index.ts - create() function
const oauthDisabled = mcp.oauth === false
const oauthConfig = typeof mcp.oauth === "object" ? mcp.oauth : undefined

if (!oauthDisabled) {
  authProvider = new McpOAuthProvider(
    key,
    mcp.url,
    {
      clientId: oauthConfig?.clientId,
      clientSecret: oauthConfig?.clientSecret,
      scope: oauthConfig?.scope,
    },
    { onRedirect: ... },
  )
}
```

### Type Safety with Discriminated Union

The `Mcp` type is a discriminated union of `McpLocal` and `McpRemote`:

```typescript
export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
```

This means that Zod automatically selects the correct validation mode based on the `type` field when parsing the configuration -- a `type: "local"` configuration will not be required to provide a `url` field, and a `type: "remote"` configuration will not be required to provide a `command` field. If an incorrect combination of fields is provided, Zod will give a precise type error message.

The helper function `isMcpConfigured()` serves as a runtime type guard:

```typescript
function isMcpConfigured(entry: McpEntry): entry is Config.Mcp {
  return typeof entry === "object" && entry !== null && "type" in entry
}
```

### Global Timeout Configuration

In addition to setting `timeout` individually for each MCP Server, OpenCode also provides a global experimental configuration option:

```typescript
// In the tools() function
const cfg = await Config.get()
const defaultTimeout = cfg.experimental?.mcp_timeout
// ...
const timeout = entry?.timeout ?? defaultTimeout
```

The priority order is: MCP Server's own `timeout` > global `experimental.mcp_timeout` > default value (30,000ms).

## 8.4.2 MCP Resource Model

As mentioned in Section 8.1, one of MCP's three core primitives is Resource. OpenCode defines the Resource data model using Zod:

```typescript
// mcp/index.ts
export const Resource = z.object({
  name: z.string(),              // Resource name
  uri: z.string(),               // Resource URI
  description: z.string().optional(),  // Description
  mimeType: z.string().optional(),     // MIME type
  client: z.string(),            // Name of the owning MCP Server
})
export type Resource = z.infer<typeof Resource>
```

Resource URIs follow the standard URI format, allowing MCP Servers to identify resources using any scheme. For example:

* `file:///path/to/document.md` -- a file resource
* `db://users/123` -- a database record
* `https://api.example.com/data` -- an API endpoint

The `client` field records which MCP Server this resource comes from, used to route subsequent `readResource()` calls to the correct client.

### Fetching and Reading Resources

```typescript
// List Resources from all connected MCP Servers
export async function resources() {
  const clientsSnapshot = await clients()
  const result = Object.fromEntries(
    (await Promise.all(
      Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
        if (s.status[clientName]?.status !== "connected") return []
        return Object.entries(
          (await fetchResourcesForClient(clientName, client)) ?? {}
        )
      }),
    )).flat(),
  )
  return result
}

// Read the content of a specific Resource
export async function readResource(
  clientName: string,
  resourceUri: string
) {
  const client = clientsSnapshot[clientName]
  return client.readResource({ uri: resourceUri })
}
```

Resources also use the prefix naming strategy (`ServerName:ResourceName`) to avoid conflicts.

### Configuration Best Practices

Here are several common MCP configuration scenarios:

**Scenario 1: Local Filesystem Tool**

```json
{
  "mcp": {
    "fs": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."],
      "timeout": 5000
    }
  }
}
```

**Scenario 2: Remote Service Requiring an API Key**

```json
{
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://mcp-jira.example.com",
      "headers": {
        "Authorization": "Bearer your-api-token"
      },
      "oauth": false
    }
  }
}
```

**Scenario 3: Remote Service Requiring OAuth**

```json
{
  "mcp": {
    "github-tools": {
      "type": "remote",
      "url": "https://mcp-github.example.com",
      "oauth": {
        "clientId": "your-github-app-id",
        "scope": "repo read:org"
      }
    }
  }
}
```

**Scenario 4: Temporarily Disabling an MCP Server**

```json
{
  "mcp": {
    "expensive-server": {
      "type": "remote",
      "url": "https://expensive-mcp.example.com",
      "enabled": false
    }
  }
}
```

Setting `enabled` to `false` preserves the configuration without establishing a connection, avoiding unnecessary resource consumption. This is more convenient than deleting the configuration, since re-enabling it only requires changing the value back to `true`.

***

> **Section Summary**
>
> OpenCode's MCP configuration system achieves type-safe validation through Zod's Discriminated Union -- `type: "local"` and `type: "remote"` configuration modes each have their own set of required fields. The core of local configuration is the `command` array (avoiding shell injection), while the core of remote configuration is `url` and `oauth` (supporting auto-discovery, pre-registered, and disabled modes). Timeout supports three levels of priority: Server-level, global-level, and default value. The Resource model uses URIs as identifiers and associates with specific MCP Servers through the `client` field.

***

> **Chapter 8 Summary**
>
> This chapter provided a complete analysis of OpenCode's MCP system, from protocol concepts to source code implementation. MCP (Model Context Protocol) provides OpenCode with a standardized bridge for connecting to external tool ecosystems, with its core value lying in the complete decoupling of tool implementations from the AI application. OpenCode's MCP implementation consists of four key modules:
>
> 1. **mcp/index.ts** (935 lines): The MCP client core, managing connections, the state machine, and tool conversion.
> 2. **mcp/auth.ts** (133 lines): Secure OAuth credential storage with URL binding validation.
> 3. **mcp/oauth-provider.ts** (155 lines): Implements the MCP SDK's OAuth interface, supporting dynamic client registration and PKCE.
> 4. **mcp/oauth-callback.ts** (201 lines): A local HTTP callback server with CSRF protection and race condition handling.
>
> From an engineering perspective, the MCP module showcases many design patterns worth studying: the transport layer's fallback strategy (StreamableHTTP to SSE), the five-state connection state machine, multi-layered OAuth security (PKCE + State + URL binding), and the race condition handling of registering callbacks before opening the browser. While these details may amount to just a few lines of difference in the source code, they represent deep consideration for security and robustness -- the key distinction between "working" and "reliable."
