> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenCode

OpenCode is an open-source AI coding agent designed for developers, featuring a "terminal-native" experience: it uses TUI/CLI to handle requirement discussions, code generation, refactoring, explanation, and debugging workflows directly in the command line. It emphasizes being "model-agnostic" and can connect to Claude, GPT, Gemini, and other model services, as well as local or OpenAI-compatible APIs, allowing you to freely balance cost, performance, and privacy. OpenCode also provides an extensible plugin/tool mechanism and configuration system that can incorporate project context, command execution, and other capabilities into automated workflows, making it ideal for power terminal users and teams that want to customize their AI coding workflow.

# Installation and Integration

## Installation

```bash theme={null}
curl -fsSL https://opencode.ai/install | bash
```

For other installation methods, see the OpenCode official website: [https://opencode.ai/docs/#install](https://opencode.ai/docs/#install)

## Start OpenCode

```bash theme={null}
cd /path/to/project  # Navigate to your project directory

opencode  # Start OpenCode
```

## Connect to Myrouter API

* Global configuration: \~/.config/opencode/opencode.json
* Project configuration: opencode.json in the project root directory

(If opencode.json does not exist, you can create it manually.)

Configuration as follows:

```JSON theme={null}
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "myprovider": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Myrouter",
      "options": {
        "baseURL": "https://api.myrouter.ai/openai/v1"
      },
      "models": {
        "claude-sonnet-4-5-20250929": {
          "name": "claude-sonnet-4-5-20250929"
        },
        "gpt-5.2": {
          "name": "gpt-5.2"
        },
      }
    }
  }
}
```

When configuring third-party providers, make sure to select the correct npm package:

| **npm Package**           | **API Type**        | **Use Case**                       |
| ------------------------- | ------------------- | ---------------------------------- |
| @ai-sdk/openai-compatible | Chat Completion API | GPT, Claude, and most other models |
| @ai-sdk/openai            | Response API        | Codex series models                |

**Note:** Codex models (e.g., gpt-5.1-codex) require @ai-sdk/openai (Response API), while other models use @ai-sdk/openai-compatible (Chat Completion API).

## Configure the KEY

In OpenCode, use `/connect` to select the provider, then enter your API KEY and press Enter to confirm.

<img src="https://mintcdn.com/novita-3abec9fa/6X7voZXY7_xk3Ecs/images/opencode_input_api_key.png?fit=max&auto=format&n=6X7voZXY7_xk3Ecs&q=85&s=36f6c6c50f8b21ebc42aa705e2b4deea" alt="opencode_input_api_key" width="858" height="328" data-path="images/opencode_input_api_key.png" />

## Start Using

After connecting to the provider, use the `/models` command to select a model.

<img src="https://mintcdn.com/novita-3abec9fa/6X7voZXY7_xk3Ecs/images/opencode_choose_model.png?fit=max&auto=format&n=6X7voZXY7_xk3Ecs&q=85&s=c1a694822f9e98537058804cce5f0519" alt="opencode_choose_model" width="848" height="888" data-path="images/opencode_choose_model.png" />

# Other Usage

## Example: Local MCP Configuration (Calculator MCP Example)

1. Write a calculator MCP server using Python + MCP SDK and save it to a local path.

```python theme={null}
import asyncio
import math
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent

# Create server instance
server = Server("calculator")

@server.list_tools()
async def list_tools() -> list[Tool]:
    """List available calculator tools."""
    return [
        Tool(
            name="add",
            description="Add two numbers",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "First number"},
                    "b": {"type": "number", "description": "Second number"},
                },
                "required": ["a", "b"],
            },
        ),
        Tool(
            name="subtract",
            description="Subtract second number from first number",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "First number"},
                    "b": {"type": "number", "description": "Second number to subtract"},
                },
                "required": ["a", "b"],
            },
        ),
        Tool(
            name="multiply",
            description="Multiply two numbers",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "First number"},
                    "b": {"type": "number", "description": "Second number"},
                },
                "required": ["a", "b"],
            },
        ),
        Tool(
            name="divide",
            description="Divide first number by second number",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "Dividend"},
                    "b": {"type": "number", "description": "Divisor"},
                },
                "required": ["a", "b"],
            },
        ),
        Tool(
            name="power",
            description="Raise a number to a power",
            inputSchema={
                "type": "object",
                "properties": {
                    "base": {"type": "number", "description": "Base number"},
                    "exponent": {"type": "number", "description": "Exponent"},
                },
                "required": ["base", "exponent"],
            },
        ),
        Tool(
            name="sqrt",
            description="Calculate square root of a number",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "Number to calculate square root of"},
                },
                "required": ["a"],
            },
        ),
        Tool(
            name="modulo",
            description="Calculate remainder of division",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number", "description": "Dividend"},
                    "b": {"type": "number", "description": "Divisor"},
                },
                "required": ["a", "b"],
            },
        ),
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[TextContent]:
    """Handle tool calls for calculator operations."""
    try:
        if name == "add":
            result = arguments["a"] + arguments["b"]
        elif name == "subtract":
            result = arguments["a"] - arguments["b"]
        elif name == "multiply":
            result = arguments["a"] * arguments["b"]
        elif name == "divide":
            if arguments["b"] == 0:
                return [TextContent(type="text", text="Error: Division by zero")]
            result = arguments["a"] / arguments["b"]
        elif name == "power":
            result = math.pow(arguments["base"], arguments["exponent"])
        elif name == "sqrt":
            if arguments["a"] < 0:
                return [TextContent(type="text", text="Error: Cannot calculate square root of negative number")]
            result = math.sqrt(arguments["a"])
        elif name == "modulo":
            if arguments["b"] == 0:
                return [TextContent(type="text", text="Error: Modulo by zero")]
            result = arguments["a"] % arguments["b"]
        else:
            return [TextContent(type="text", text=f"Error: Unknown tool '{name}'")]

        return [TextContent(type="text", text=str(result))]

    except Exception as e:
        return [TextContent(type="text", text=f"Error: {str(e)}")]

async def main():
    """Run the calculator MCP server."""
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

if __name__ == "__main__":
    asyncio.run(main())

```

2. Add the local MCP to opencode.json

```json theme={null}
{
  "mcp": {
    "calc_mcp": {
      "type": "local",
      "command": ["python3", "{your_local_path}/calc_mcp.py"],
      "enabled": true
    }
  }
}
```

3. Use `/mcps` to check MCP connection status. When in Enabled state, OpenCode can invoke it.

<img src="https://mintcdn.com/novita-3abec9fa/6X7voZXY7_xk3Ecs/images/opencode_mcp.png?fit=max&auto=format&n=6X7voZXY7_xk3Ecs&q=85&s=14c513c09c352ca3f8b6e3c102f354b2" alt="opencode_mcp" width="860" height="370" data-path="images/opencode_mcp.png" />
