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

# 8.1 Introduction to the MCP Protocol

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

***

In previous chapters, we took a deep dive into OpenCode's built-in Tool system -- a set of core tools (such as Bash, Read, Edit, Write, etc.) created by the `Tool.define()` factory function and carefully designed. These tools cover most everyday programming scenarios, but real-world needs are far richer than any fixed set of tools can satisfy: a team might need an Agent to connect to Jira for task management, call the Figma API to fetch design specs, or query an internal knowledge base to retrieve documentation. If every such need required adding a new built-in tool to the OpenCode core codebase, the code would quickly become bloated and maintenance would become unsustainable.

**MCP (Model Context Protocol)** was created precisely to solve this problem. It defines a standardized protocol that allows AI applications (like OpenCode) to connect to arbitrary external tool servers in a unified way. This section introduces the core concepts and design goals of MCP, as well as its role within OpenCode.

## 8.1.1 Design Goals and Core Concepts of MCP

> **Extended Explanation: What is MCP (Model Context Protocol)?**
>
> MCP is an open protocol specification released by Anthropic in 2024. Its design was inspired by **LSP (Language Server Protocol)** -- if you have used VS Code, you may have already experienced LSP indirectly: VS Code does not need to build in syntax highlighting and code completion logic for every programming language. Instead, it communicates with independent "language servers" via the LSP protocol, and these language servers provide language-specific functionality.
>
> MCP borrows this idea: **AI applications do not need to write custom integration code for each external tool. Instead, they communicate with independent "tool servers" via the MCP protocol, and these tool servers provide tool definitions and execution logic.**
>
> More specifically, MCP defines a **Client-Server architecture**:
>
> * **MCP Host**: The environment running the AI application -- in our case, this is OpenCode.
> * **MCP Client**: A component within the host, responsible for establishing a connection and communicating with the MCP Server.
> * **MCP Server**: An independent process or remote service that exposes tools, resources, and prompts for the Client to use.
>
> The core value of this architecture lies in **decoupling**: tool implementations are completely separated from the AI application. Anyone can develop an MCP Server, and any AI application that supports MCP can connect to it.

### MCP vs. Function Calling

Beginners may be confused: LLMs already have Function Calling capabilities, so why is MCP needed? The relationship between the two is as follows:

| Dimension           | Function Calling                                                         | MCP                                                                                           |
| ------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------- |
| **Level**           | An LLM-level capability -- the model decides when to call which function | An application-level protocol -- defines how tools are discovered and executed                |
| **Tool Definition** | Tool lists are hardcoded or manually defined by the application          | Dynamically provided by the MCP Server, supporting runtime discovery                          |
| **Tool Execution**  | The application implements the execution logic itself                    | The MCP Server handles execution; the application only passes parameters and receives results |
| **Ecosystem**       | Each application maintains its own tool set independently                | Tools exist as independent services and can be reused by any MCP Client                       |
| **Protocol**        | No standard protocol; each LLM provider has its own format               | Standardized JSON-RPC 2.0 protocol                                                            |

An analogy to help understand: Function Calling is like "I know there's a function called `get_weather` that I can call," while MCP is like "there's a weather service that I can connect to, it will tell me what tools it provides, and I can call them at any time." MCP builds on top of Function Calling -- tools provided by MCP Servers are ultimately presented to the LLM in the form of Function Calling.

### MCP's Role in OpenCode

Within OpenCode's tool ecosystem, MCP serves as the "external tool bridge":

```
┌─────────────────────────────────────────────────┐
│                   OpenCode                       │
│                                                  │
│  ┌──────────────┐    ┌───────────────────────┐   │
│  │  Built-in    │    │   MCP Client          │   │
│  │  Tools       │    │   (mcp/index.ts)      │   │
│  │  (Tool Sys)  │    │                       │   │
│  │  • Bash      │    │  ┌─── MCP Server A ──┐│   │
│  │  • Read      │    │  │  • tool_1          ││   │
│  │  • Edit      │    │  │  • tool_2          ││   │
│  │  • Write     │    │  └────────────────────┘│   │
│  │  • Glob      │    │                       │   │
│  │  • Grep      │    │  ┌─── MCP Server B ──┐│   │
│  │  • Task      │    │  │  • tool_3          ││   │
│  │  • ...       │    │  │  • tool_4          ││   │
│  │              │    │  └────────────────────┘│   │
│  └──────┬───────┘    └───────────┬───────────┘   │
│         │                       │                │
│         └───────────┬───────────┘                │
│                     ▼                            │
│           ┌─────────────────┐                    │
│           │  AI SDK Tool    │                    │
│           │  Unified API    │                    │
│           └────────┬────────┘                    │
│                    ▼                             │
│           ┌─────────────────┐                    │
│           │    LLM          │                    │
│           │  (streamText)   │                    │
│           └─────────────────┘                    │
└──────────────────────────────────────────────────┘
```

Whether it is a built-in tool or an MCP tool, they are all ultimately converted to the AI SDK's `Tool` type, presenting a completely consistent interface to the LLM. The LLM cannot distinguish whether a tool is built into OpenCode or comes from an MCP Server -- and this is precisely the elegance of MCP.

## 8.1.2 Three Transport Methods: Stdio, SSE, and StreamableHTTP

The MCP protocol is flexible at the transport layer -- it is not bound to a specific transport method. The MCP SDK supports three transport methods, all of which OpenCode has implemented:

### 1. Stdio (Standard Input/Output)

```
OpenCode (Host Process)               MCP Server (Child Process)
┌─────────────┐                   ┌─────────────────┐
│             │    stdin (JSON)    │                 │
│  MCP Client ├──────────────────►│  Process Request │
│             │                   │                 │
│             │◄──────────────────┤  Return Result   │
│             │   stdout (JSON)   │                 │
└─────────────┘                   └─────────────────┘
```

This is the most common transport method and corresponds to the `type: "local"` configuration in OpenCode. How it works:

* OpenCode, as the parent process, spawns a child process to run the MCP Server.
* Communication occurs through the child process's stdin (standard input) and stdout (standard output).
* Each message is a complete JSON-RPC 2.0 message, delimited by newlines.
* The child process's stderr (standard error) is listened to separately for log output.

Implementation in OpenCode source code:

```typescript
// mcp/index.ts - Local MCP Server connection
const [cmd, ...args] = mcp.command
const transport = new StdioClientTransport({
  stderr: "pipe",       // Pipe stderr for logging
  command: cmd,         // Command to execute, e.g., "npx"
  args,                 // Command arguments, e.g., ["-y", "@some/mcp-server"]
  cwd,                  // Working directory
  env: {
    ...process.env,     // Inherit current environment variables
    ...(cmd === "opencode" ? { BUN_BE_BUN: "1" } : {}),  // Special handling
    ...mcp.environment,  // User-defined environment variables
  },
})
```

**Use cases**: Local development tools, file system operations, tools that need access to local resources.

### 2. SSE (Server-Sent Events)

```
OpenCode                          Remote MCP Server
┌─────────────┐                   ┌─────────────────┐
│             │   HTTP POST       │                 │
│  MCP Client ├──────────────────►│  Receive Request │
│             │                   │                 │
│             │◄──────────────────┤  SSE Event Stream│
│             │   text/event-stream│  (Continuous)   │
└─────────────┘                   └─────────────────┘
```

SSE is a unidirectional push technology based on HTTP. In the context of MCP:

* The Client sends requests via HTTP POST.
* The Server continuously pushes responses via SSE (Server-Sent Events).
* This was the remote transport method in earlier versions of the MCP protocol.

> **Extended Explanation: What is SSE?**
>
> SSE (Server-Sent Events) is part of the HTML5 specification, allowing a server to continuously push events to the client over an HTTP connection. Unlike WebSocket, SSE is unidirectional (the server can only push to the client), but its advantages are: it is based on standard HTTP protocol, supports automatic reconnection, and natively supports event type classification. In MCP, SSE is used to carry JSON-RPC responses.

### 3. StreamableHTTP

```
OpenCode                          Remote MCP Server
┌─────────────┐                   ┌─────────────────┐
│             │   HTTP POST       │                 │
│  MCP Client ├──────────────────►│  Receive Request │
│             │                   │                 │
│             │◄──────────────────┤  HTTP Streaming  │
│             │   (chunked/SSE)   │  Response        │
└─────────────┘                   └─────────────────┘
```

StreamableHTTP is a transport method introduced in a newer version of the MCP protocol. It is more flexible:

* Supports a hybrid of standard HTTP request/response and streaming push.
* More versatile than pure SSE and can adapt to more server environments.
* In OpenCode, MCP Servers configured with `type: "remote"` will first attempt StreamableHTTP. If that fails, it automatically falls back to SSE.

```typescript
// mcp/index.ts - Fallback strategy for remote MCP Server connections
const transports: Array<{ name: string; transport: TransportWithAuth }> = [
  {
    name: "StreamableHTTP",  // Try first
    transport: new StreamableHTTPClientTransport(new URL(mcp.url), {
      authProvider,
      requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
    }),
  },
  {
    name: "SSE",  // Fallback option
    transport: new SSEClientTransport(new URL(mcp.url), {
      authProvider,
      requestInit: mcp.headers ? { headers: mcp.headers } : undefined,
    }),
  },
]
```

This fallback strategy is an engineering practice worth learning -- it ensures maximum compatibility with different versions of MCP Servers.

## 8.1.3 Core Primitives of MCP: Tool, Resource, and Prompt

The MCP protocol defines three core primitives, each corresponding to a dimension of interaction between the AI application and the external world:

### Tool

Tool is the most central primitive of MCP. Tools exposed by an MCP Server are conceptually identical to the built-in Tools we studied in Chapter 5 -- they define operations that the LLM can invoke.

An MCP Tool definition includes:

* **name**: The tool name (e.g., `search_issues`)
* **description**: A description of the tool (for the LLM to understand when to use it)
* **inputSchema**: A JSON Schema definition of the parameters

When the LLM decides to invoke an MCP Tool, the flow is as follows:

```
LLM decides to call → OpenCode forwards the request to the MCP Server →
MCP Server executes → Returns result → OpenCode forwards it to the LLM
```

### Resource

Resource represents data resources that an MCP Server can provide. Unlike Tools, Resources are **passively provided** -- they represent data that can be read, rather than operations that can be executed.

In OpenCode, Resource is defined as:

```typescript
// mcp/index.ts
export const Resource = z.object({
  name: z.string(),          // Resource name
  uri: z.string(),           // Resource URI identifier
  description: z.string().optional(),  // Resource description
  mimeType: z.string().optional(),     // MIME type
  client: z.string(),        // Name of the MCP Server it belongs to
})
```

Typical use cases for Resources include: document content, database records, API response data, etc.

### Prompt (Prompt Template)

Prompt is a predefined prompt template provided by an MCP Server. It allows the MCP Server to offer prompts optimized for specific tasks to the AI application.

For example, a code review MCP Server might provide a Prompt named `review_code` that contains optimized review instructions. Users can use MCP Prompts to leverage these templates without needing to write complex prompts themselves.

In OpenCode, MCP Prompts can be triggered via slash commands (`/`). OpenCode lists all Prompts exposed by connected MCP Servers for the user to select from.

### Relationship Among the Three

```
┌─────────────────────────────────────────────┐
│                 MCP Server                   │
│                                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐   │
│  │  Tools   │  │Resources │  │ Prompts  │   │
│  │          │  │          │  │          │   │
│  │ LLM can  │  │ App can  │  │ User can │   │
│  │ actively │  │ passively│  │ choose   │   │
│  │ invoke   │  │ read     │  │ to use   │   │
│  └──────────┘  └──────────┘  └──────────┘   │
└─────────────────────────────────────────────┘
```

* **Tool** is LLM-facing: The LLM autonomously decides whether to invoke it based on context.
* **Resource** is application-facing: Application code can read resource content, typically used for context injection.
* **Prompt** is user-facing: The user explicitly selects a predefined prompt template to use.

In OpenCode's implementation, Tool is the most widely used primitive -- almost all MCP integration scenarios are implemented through Tools. Resource and Prompt are used relatively less, but they provide possibilities for more advanced integration scenarios.

***

> **Section Summary**
>
> MCP (Model Context Protocol) is a standardized protocol that allows AI applications to connect to external tool servers in a unified way. It borrows the design philosophy of LSP, completely decoupling tool implementations from the AI application. MCP supports three transport methods (Stdio, SSE, and StreamableHTTP), and OpenCode automatically attempts fallback when connecting to remote servers to ensure maximum compatibility. MCP defines three core primitives -- Tool (actively invoked by the LLM), Resource (passively read by the application), and Prompt (template selection by the user) -- among which Tool is the most central and most commonly used primitive. In the following sections, we will dive into OpenCode's MCP Client source code to see how these concepts are concretely implemented.
