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

# 17.3 Lab 3: Building an MCP Server

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

***

In the previous two labs, we built a CLI tool with conversation and tool-calling capabilities. However, those tools were hardcoded inside the program — what if we want tools to be developed independently, deployed independently, and shared across multiple AI applications? This is the problem that MCP (Model Context Protocol) solves.

In Chapter 8 we analyzed OpenCode's MCP Client implementation (`mcp/index.ts`), which uses the `Client` class from `@modelcontextprotocol/sdk` to connect to MCP Servers. In this section, we take a different perspective — **building our own MCP Server** that OpenCode can connect to and use.

## 17.3.1 Objective

Create a custom MCP Server using `@modelcontextprotocol/sdk` with the following capabilities:

1. Communicate with Clients via Stdio (standard input/output) transport protocol
2. Provide a useful tool: GitHub repository information query
3. Configure the MCP Server in OpenCode for hands-on testing

> **Extended Explanation — Why Does MCP Use Stdio Transport?**
>
> MCP supports three transport methods: Stdio (standard input/output), SSE (Server-Sent Events), and StreamableHTTP. Among these, Stdio is the most common transport method for local MCP Servers. Its working principle is very simple:
>
> 1. The Client (e.g., OpenCode) launches the Server as a child process
> 2. The Client sends JSON-RPC requests via the child process's `stdin`
> 3. The Server returns JSON-RPC responses via `stdout`
>
> The advantage of this design is: **no network port required, no HTTP server needed, no authentication to handle** — communication works as long as you can start a process. For local tools, this is the simplest and most reliable approach.
>
> In the OpenCode source code, `StdioClientTransport` implements exactly this:
>
> ```typescript
> const transport = new StdioClientTransport({
>   command: cmd,
>   args,
>   env: { ...process.env, ...mcp.environment },
> })
> ```

## 17.3.2 Implementation Steps

### Step 1: Initialize the Project

```bash
mkdir my-mcp-server && cd my-mcp-server
bun init -y
bun add @modelcontextprotocol/sdk zod
```

`@modelcontextprotocol/sdk` is the official MCP SDK, providing both Client and Server implementations.

### Step 2: Create the MCP Server

Create `server.ts`:

```typescript
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { z } from "zod"

// Create MCP Server instance
const server = new McpServer({
  name: "github-tools",       // Server name
  version: "1.0.0",           // Server version
})

// Register tool: Query GitHub repository information
server.tool(
  "github_repo_info",                              // Tool name
  "Query basic information about a GitHub repository, including stars, description, language, etc.", // Tool description
  {
    owner: z.string().describe("Repository owner (username or organization name)"),
    repo: z.string().describe("Repository name"),
  },
  async ({ owner, repo }) => {
    try {
      const response = await fetch(
        `https://api.github.com/repos/${owner}/${repo}`,
        {
          headers: {
            "Accept": "application/vnd.github.v3+json",
            "User-Agent": "my-mcp-server",
          },
        }
      )

      if (!response.ok) {
        return {
          content: [{
            type: "text" as const,
            text: `Error: Unable to fetch repository ${owner}/${repo}, HTTP ${response.status}`,
          }],
        }
      }

      const data = await response.json()

      const info = [
        `📦 ${data.full_name}`,
        `📝 ${data.description || "No description"}`,
        `⭐ ${data.stargazers_count} stars`,
        `🔀 ${data.forks_count} forks`,
        `👁️ ${data.watchers_count} watchers`,
        `💻 Primary language: ${data.language || "Unknown"}`,
        `📄 License: ${data.license?.name || "None"}`,
        `🔗 ${data.html_url}`,
        `📅 Created: ${new Date(data.created_at).toLocaleDateString()}`,
        `📅 Last updated: ${new Date(data.updated_at).toLocaleDateString()}`,
      ].join("\n")

      return {
        content: [{ type: "text" as const, text: info }],
      }
    } catch (error: any) {
      return {
        content: [{
          type: "text" as const,
          text: `Request failed: ${error.message}`,
        }],
      }
    }
  }
)

// Register a second tool: Search GitHub repositories
server.tool(
  "github_search_repos",
  "Search for repositories on GitHub",
  {
    query: z.string().describe("Search keywords"),
    limit: z.number().min(1).max(10).default(5)
      .describe("Number of results to return, default 5"),
  },
  async ({ query, limit }) => {
    try {
      const response = await fetch(
        `https://api.github.com/search/repositories?q=${
          encodeURIComponent(query)
        }&sort=stars&per_page=${limit}`,
        {
          headers: {
            "Accept": "application/vnd.github.v3+json",
            "User-Agent": "my-mcp-server",
          },
        }
      )

      const data = await response.json()

      if (!data.items?.length) {
        return {
          content: [{
            type: "text" as const,
            text: `No repositories found matching "${query}"`,
          }],
        }
      }

      const results = data.items.map((item: any, i: number) =>
        `${i + 1}. ${item.full_name} ⭐${item.stargazers_count}\n` +
        `   ${item.description || "No description"}\n` +
        `   ${item.html_url}`
      ).join("\n\n")

      return {
        content: [{
          type: "text" as const,
          text: `Search results for "${query}" (${data.total_count} total, showing top ${limit}):\n\n${results}`,
        }],
      }
    } catch (error: any) {
      return {
        content: [{
          type: "text" as const,
          text: `Search failed: ${error.message}`,
        }],
      }
    }
  }
)

// Start the Server using Stdio transport
async function main() {
  const transport = new StdioServerTransport()
  await server.connect(transport)
  // Server is now waiting for requests via stdin/stdout
  // Note: Do not use console.log in the Server — it will interfere with Stdio communication
  console.error("GitHub MCP Server started")
}

main().catch(console.error)
```

Note several key points:

1. **`McpServer` class**: This is the high-level API provided by the MCP SDK, more convenient than using the lower-level `Server` class directly. It includes built-in tool registration, parameter validation, and more.
2. **`server.tool()` method**: The signature for registering a tool is `(name, description, schema, handler)`, where `schema` is defined using Zod — consistent with the style of `Tool.define()` inside OpenCode.
3. **Return value format**: MCP tool return values must follow the `{ content: [{ type: "text", text: string }] }` format — this is the standard structure specified by the MCP protocol.
4. **Use `console.error` instead of `console.log`**: Because `stdout` is occupied by Stdio transport, all logging must be written to `stderr`.

### Step 3: Local Testing

First, verify that the Server starts properly:

```bash
# Run directly; you should see the startup message on stderr
# The Server will wait for stdin input; press Ctrl+C to exit
bun run server.ts
```

### Step 4: Configure in OpenCode

Edit the `opencode.json` in your project root (or `~/.config/opencode/opencode.json`):

```json
{
  "mcp": {
    "github-tools": {
      "type": "local",
      "command": ["bun", "run", "/absolute/path/to/my-mcp-server/server.ts"],
      "timeout": 15000
    }
  }
}
```

This directly corresponds to the `McpLocal` Schema defined in `config/config.ts` of the OpenCode source code:

```typescript
// MCP configuration type definition in OpenCode source code
export const McpLocal = z.object({
  type: z.literal("local"),
  command: z.string().array(),
  environment: z.record(z.string(), z.string()).optional(),
  enabled: z.boolean().optional(),
  timeout: z.number().int().positive().optional(),
})
```

After configuring, restart OpenCode and you can use these two tools in your conversations:

```
You: Look up the information for the anomalyco/opencode repository
```
