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

# 8.2 MCP Client Implementation

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

***

In the previous section, we covered the core concepts of the MCP protocol and its three transport mechanisms. This section dives into the source code of OpenCode's `mcp/index.ts`, providing a detailed analysis of the MCP Client implementation -- from client initialization and connection management to state machine design and how MCP tools are converted into OpenCode's internal Tool format.

## 8.2.1 mcp/index.ts Source Code Analysis

`mcp/index.ts` is the core file of OpenCode's MCP module, consisting of 935 lines of code. It organizes all functionality within an `MCP` namespace. Let's start by examining the architecture through its dependency imports.

### Dependencies

```typescript
// AI SDK - for converting MCP tools to AI SDK format
import { dynamicTool, type Tool, jsonSchema, type JSONSchema7 } from "ai"

// MCP SDK - the official MCP client library
import { Client } from "@modelcontextprotocol/sdk/client/index.js"
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js"
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"
import { UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js"
import {
  CallToolResultSchema,
  type Tool as MCPToolDef,
  ToolListChangedNotificationSchema,
} from "@modelcontextprotocol/sdk/types.js"
```

These dependencies fall into two groups:

1. **`@modelcontextprotocol/sdk`**: The official MCP SDK, providing the `Client` class and three transport implementations (`StdioClientTransport`, `SSEClientTransport`, `StreamableHTTPClientTransport`). This is the infrastructure for communicating with MCP Servers.
2. **`ai` (Vercel AI SDK)**: Provides the `dynamicTool()` function for converting MCP tools into the AI SDK's Tool format. This serves as the bridge connecting the MCP world to the LLM world.

### Instance.state() State Management

The MCP module uses the `Instance.state()` pattern introduced in Chapter 3 to manage state:

```typescript
const state = Instance.state(
  // Initialization function: start all configured MCP Servers
  async () => {
    const cfg = await Config.get()
    const config = cfg.mcp ?? {}
    const clients: Record<string, MCPClient> = {}
    const status: Record<string, Status> = {}

    await Promise.all(
      Object.entries(config).map(async ([key, mcp]) => {
        if (!isMcpConfigured(mcp)) {
          log.error("Ignoring MCP config entry without type", { key })
          return
        }

        // Disabled MCP Servers are directly marked as disabled
        if (mcp.enabled === false) {
          status[key] = { status: "disabled" }
          return
        }

        const result = await create(key, mcp).catch(() => undefined)
        if (!result) return

        status[key] = result.status
        if (result.mcpClient) {
          clients[key] = result.mcpClient
        }
      }),
    )
    return { status, clients }
  },

  // Destruction function: close all MCP client connections
  async (state) => {
    await Promise.all(
      Object.values(state.clients).map((client) =>
        client.close().catch((error) => {
          log.error("Failed to close MCP client", { error })
        }),
      ),
    )
    pendingOAuthTransports.clear()
  },
)
```

> **Recap: Instance.state()**
>
> As we learned in Chapter 3, `Instance.state()` is OpenCode's "per-project-directory isolation" state management pattern. Each project directory has its own independent set of MCP connections. When OpenCode starts, the `state()` initialization function is called, iterating over all MCP Servers in the configuration and attempting to establish connections. When the project directory is switched or OpenCode exits, the destruction function is called to gracefully close all connections.

An important engineering detail here is that all MCP Server connections are established **in parallel** (`Promise.all`). This ensures that even if a particular MCP Server is slow to start or times out, it will not block other Servers from connecting.

### The `create()` Function: Core Connection Logic

`create()` is the most critical function in the entire MCP module. It is responsible for establishing a connection to a single MCP Server. Depending on the `type` field, the connection flow splits into two paths:

**Remote MCP Server (`type: "remote"`):**

```typescript
async function create(key: string, mcp: Config.Mcp) {
  if (mcp.type === "remote") {
    // 1. Create an OAuth Provider (unless explicitly disabled)
    let authProvider: McpOAuthProvider | undefined
    if (!oauthDisabled) {
      authProvider = new McpOAuthProvider(key, mcp.url, { ... }, { ... })
    }

    // 2. Build the transport layer list: StreamableHTTP first, SSE as fallback
    const transports = [
      { name: "StreamableHTTP", transport: new StreamableHTTPClientTransport(...) },
      { name: "SSE",            transport: new SSEClientTransport(...) },
    ]

    // 3. Try to connect with each transport in order
    for (const { name, transport } of transports) {
      try {
        const client = new Client({
          name: "opencode",
          version: Installation.VERSION,
        })
        await withTimeout(client.connect(transport), connectTimeout)
        registerNotificationHandlers(client, key)
        mcpClient = client
        status = { status: "connected" }
        break  // Connection successful, exit the loop
      } catch (error) {
        // Handle OAuth errors
        if (error instanceof UnauthorizedError) {
          // Store the transport for completing the OAuth flow later
          pendingOAuthTransports.set(key, transport)
          status = { status: "needs_auth" }
          break
        }
        // Transport failed, try the next one
        status = { status: "failed", error: lastError.message }
      }
    }
  }
  // ...
}
```

This code demonstrates an elegant **fallback connection strategy**:

1. First, attempt the more modern StreamableHTTP transport.
2. If that fails, automatically fall back to SSE transport.
3. If an `UnauthorizedError` (OAuth authentication error) is encountered, don't fail immediately -- instead, mark the connection as `needs_auth` and wait for the user to complete authentication before retrying.

**Local MCP Server (`type: "local"`):**

```typescript
if (mcp.type === "local") {
  const [cmd, ...args] = mcp.command  // Destructure the command and arguments
  const cwd = Instance.directory       // Use the current project directory as the working directory
  const transport = new StdioClientTransport({
    stderr: "pipe",
    command: cmd,
    args,
    cwd,
    env: {
      ...process.env,
      ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),
      ...mcp.environment,
    },
  })

  // Monitor stderr for logging
  transport.stderr?.on("data", (chunk: Buffer) => {
    log.info(`mcp stderr: ${chunk.toString()}`, { key })
  })

  // Connect with timeout
  const client = new Client({ name: "opencode", version: Installation.VERSION })
  await withTimeout(client.connect(transport), connectTimeout)
  registerNotificationHandlers(client, key)
}
```

The local connection is relatively straightforward -- it spawns a child process via `StdioClientTransport`, using the child process's stdin/stdout as the communication channel. Note an interesting detail: when the command is `opencode` itself (a recursive invocation scenario), the environment variable `BUN_BE_BUN: "1"` is set, which is a special flag for the Bun runtime.

**After the connection is established**, regardless of whether it is remote or local, the tool list is immediately fetched to verify that the connection is truly functional:

```typescript
// After a successful connection, immediately fetch the tool list to verify
const result = await withTimeout(
  mcpClient.listTools(),
  mcp.timeout ?? DEFAULT_TIMEOUT
).catch((err) => {
  log.error("failed to get tools from client", { key, error: err })
  return undefined
})

if (!result) {
  // If fetching tools fails, close the connection and mark as failed
  await mcpClient.close().catch(...)
  status = { status: "failed", error: "Failed to get tools" }
}
```

This is an excellent defensive programming practice -- not only must the connection succeed, but the Server must also be able to respond to requests properly.

## 8.2.2 MCP Server Connection Management

### Connection State Machine

OpenCode uses a `Status` type to track the connection state of each MCP Server. This type is defined using Zod's `discriminatedUnion`, ensuring type safety:

```typescript
export const Status = z.discriminatedUnion("status", [
  z.object({ status: z.literal("connected") }),
  z.object({ status: z.literal("disabled") }),
  z.object({ status: z.literal("failed"), error: z.string() }),
  z.object({ status: z.literal("needs_auth") }),
  z.object({
    status: z.literal("needs_client_registration"),
    error: z.string(),
  }),
])
```

> **Extended Explanation: Discriminated Union**
>
> In TypeScript, a Discriminated Union is a commonly used type design pattern. Each variant in the union type shares a common "discriminant field" (in this case, `status`), whose value is a distinct literal type. This allows the TypeScript compiler to automatically narrow the type in `switch` or `if` statements -- for example, when you check `status === "failed"`, TypeScript automatically infers the existence of the `error` field.
>
> Zod's `z.discriminatedUnion()` is the runtime validation counterpart of this pattern, leveraging the discriminant field to select the correct validation branch when parsing JSON data.

The meanings and transition relationships of the five states:

```
               +------------+
    Disabled → |  disabled   |
    by config  +------------+

               +------------+     Success        +-----------+
    Init    → | (connecting) | ───────────────► | connected  |
               +------------+                   +-----------+
                     |                               |
                     | Connection                    | Runtime
                     | failure                       | error
                     v                               v
               +------------+                   +-----------+
               |   failed    | ◄─────────────── |  failed    |
               +------------+                   +-----------+
                     |
                     | OAuth auth required
                     v
               +------------+     Auth done      +-----------+
               | needs_auth  | ───────────────► | connected  |
               +------------+                   +-----------+
                     |
                     | Client registration needed
                     v
               +-------------------------+
               | needs_client_registration|
               +-------------------------+
```

It is worth noting that the `needs_auth` and `needs_client_registration` states are specifically designed for OAuth authentication scenarios. When a remote MCP Server requires authentication, OpenCode does not fail outright -- instead, it marks the status as "needs authentication" and notifies the user via a Toast:

```typescript
if (error instanceof UnauthorizedError) {
  if (lastError.message.includes("registration") ||
      lastError.message.includes("client_id")) {
    // Server does not support dynamic client registration
    status = {
      status: "needs_client_registration",
      error: "Server does not support dynamic client registration...",
    }
    Bus.publish(TuiEvent.ToastShow, {
      title: "MCP Authentication Required",
      message: `Server "${key}" requires a pre-registered client ID...`,
      variant: "warning",
      duration: 8000,
    })
  } else {
    // OAuth authentication required
    pendingOAuthTransports.set(key, transport)
    status = { status: "needs_auth" }
    Bus.publish(TuiEvent.ToastShow, {
      title: "MCP Authentication Required",
      message: `Server "${key}" requires authentication. Run: opencode mcp auth ${key}`,
      variant: "warning",
      duration: 8000,
    })
  }
}
```

### ToolsChanged Event Listener

The MCP protocol supports Server-initiated notifications to the Client when the tool list changes. OpenCode listens for this event by registering a notification handler:

```typescript
function registerNotificationHandlers(client: MCPClient, serverName: string) {
  client.setNotificationHandler(ToolListChangedNotificationSchema, async () => {
    log.info("tools list changed notification received", { server: serverName })
    Bus.publish(ToolsChanged, { server: serverName })
  })
}
```

When a `ToolListChangedNotification` is received, OpenCode publishes an `MCP.ToolsChanged` event through the Bus (event bus, detailed in Chapter 11). This event is listened to by higher-level modules (such as the Session system), triggering a re-fetch of the tool list.

This means that MCP Servers can dynamically add or remove tools at runtime, and OpenCode can detect these changes in real time -- this is one way in which the MCP protocol is more flexible than static tool definitions.

### Connection Management API

The MCP module exposes a set of connection management functions that support dynamic connection and disconnection at runtime:

```typescript
// Add/reconnect an MCP Server
export async function add(name: string, mcp: Config.Mcp) { ... }

// Connect a configured but unconnected MCP Server
export async function connect(name: string) { ... }

// Disconnect an MCP Server
export async function disconnect(name: string) { ... }

// Get the status of all MCP Servers
export async function status() { ... }
```

The `connect()` function has a notable implementation detail -- it forcibly sets `enabled` to `true`:

```typescript
export async function connect(name: string) {
  const cfg = await Config.get()
  const mcp = config[name]
  // ...
  const result = await create(name, { ...mcp, enabled: true })  // Force enable
  // ...
}
```

The `add()` function checks for an existing connection with the same name before adding a new one, closing the old connection first to prevent memory leaks:

```typescript
export async function add(name: string, mcp: Config.Mcp) {
  const s = await state()
  const result = await create(name, mcp)
  // ...
  // Close any existing client with the same name to prevent memory leaks
  const existingClient = s.clients[name]
  if (existingClient) {
    await existingClient.close().catch(...)
  }
  s.clients[name] = result.mcpClient
  s.status[name] = result.status
}
```

### Timeout Handling

Both MCP connections and tool invocations use a unified timeout mechanism:

```typescript
const DEFAULT_TIMEOUT = 30_000  // Default: 30 seconds

// Connection timeout
const connectTimeout = mcp.timeout ?? DEFAULT_TIMEOUT
await withTimeout(client.connect(transport), connectTimeout)

// Tool list fetch timeout
await withTimeout(mcpClient.listTools(), mcp.timeout ?? DEFAULT_TIMEOUT)
```

`withTimeout()` is a utility function in OpenCode (located in `util/timeout.ts`) that wraps a Promise and throws a timeout error if it does not resolve within the specified time. Users can set a custom timeout for each MCP Server through the `timeout` field in the configuration, or use the global experimental setting `experimental.mcp_timeout`.

## 8.2.3 Converting MCP Tools to the Internal Tool Format

One of the most critical parts of the MCP system is converting tool definitions provided by MCP Servers into the AI SDK's `Tool` type so they can be invoked by LLMs. This conversion is performed by the `convertMcpTool()` function:

```typescript
async function convertMcpTool(
  mcpTool: MCPToolDef,
  client: MCPClient,
  timeout?: number
): Promise<Tool> {
  const inputSchema = mcpTool.inputSchema

  // Build the JSON Schema, ensuring the type is "object"
  const schema: JSONSchema7 = {
    ...(inputSchema as JSONSchema7),
    type: "object",
    properties: (inputSchema.properties ?? {}) as JSONSchema7["properties"],
    additionalProperties: false,
  }

  return dynamicTool({
    description: mcpTool.description ?? "",
    inputSchema: jsonSchema(schema),
    execute: async (args: unknown) => {
      return client.callTool(
        {
          name: mcpTool.name,
          arguments: (args || {}) as Record<string, unknown>,
        },
        CallToolResultSchema,
        {
          resetTimeoutOnProgress: true,
          timeout,
        },
      )
    },
  })
}
```

The core logic of this function can be broken down into three steps:

1. **Schema Normalization**: The `inputSchema` provided by an MCP Server may not fully conform to the JSON Schema specification (e.g., it might be missing the `type` or `properties` fields). The function spreads the original Schema and forcibly sets `type: "object"` and `additionalProperties: false` to ensure compatibility.
2. **Creating a `dynamicTool()`**: Uses the AI SDK's `dynamicTool()` factory function to create a dynamic tool. `dynamicTool()` is similar to OpenCode's built-in `Tool.define()` that we studied in Chapter 5, but it comes from the AI SDK and is designed for LLM tool invocation scenarios.
3. **Wrapping the Execution Logic**: The `execute` function forwards tool invocation requests to the MCP Server via `client.callTool()`. Note the `resetTimeoutOnProgress: true` option -- this means that if the MCP Server sends a progress notification, the timeout timer is reset, preventing long-running tools from being incorrectly interrupted due to timeout.

### Tool Naming Convention

When exposing MCP tools to LLMs, OpenCode uses a specific naming convention to avoid tool name conflicts across different MCP Servers:

```typescript
export async function tools() {
  const result: Record<string, Tool> = {}
  // ...
  for (const mcpTool of toolsResult.tools) {
    // Sanitize special characters in the Server name and tool name
    const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
    const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
    // Concatenate as "ServerName_ToolName"
    result[sanitizedClientName + "_" + sanitizedToolName] = await convertMcpTool(...)
  }
  return result
}
```

For example, if an MCP Server named `my-jira` exposes a tool named `search_issues`, the tool's name in OpenCode will be `my-jira_search_issues`. This prefix naming convention prevents conflicts when multiple MCP Servers expose tools with the same name.

### Fetching Prompts and Resources

In addition to Tools, the MCP module also provides functions for fetching Prompts and Resources:

```typescript
// Get the Prompt list from all connected MCP Servers
export async function prompts() {
  const clientsSnapshot = await clients()
  // Fetch Prompts from all Servers in parallel
  const prompts = Object.fromEntries(
    (await Promise.all(
      Object.entries(clientsSnapshot).map(async ([clientName, client]) => {
        return Object.entries(
          (await fetchPromptsForClient(clientName, client)) ?? {}
        )
      }),
    )).flat(),
  )
  return prompts
}

// Get a specific Prompt from a specific MCP Server
export async function getPrompt(
  clientName: string,
  name: string,
  args?: Record<string, string>
) {
  const client = clientsSnapshot[clientName]
  return client.getPrompt({ name, arguments: args })
}

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

Prompts and Resources also use a similar prefix strategy: `ServerName:PromptName` / `ServerName:ResourceName`, using a colon rather than an underscore as the separator (slightly different from the Tool naming convention, since they do not need to be passed to the LLM's function calling interface).

***

> **Section Summary**
>
> OpenCode's MCP Client implementation is built on top of `@modelcontextprotocol/sdk` and manages connection lifecycles through `Instance.state()`. The core `create()` function selects the appropriate transport based on the configuration type (local/remote), with remote connections employing a StreamableHTTP to SSE fallback strategy. Connection states are tracked through a five-state state machine, with the `needs_auth` and `needs_client_registration` intermediate states specifically designed for OAuth authentication scenarios. The `convertMcpTool()` function converts MCP Tools into the AI SDK's `dynamicTool()`, enabling MCP tools to seamlessly integrate into the LLM's tool invocation system. All tools use the "ServerName\_ToolName" prefix naming convention to avoid conflicts.
