Skip to main content
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

curl -fsSL https://opencode.ai/install | bash
For other installation methods, see the OpenCode official website: https://opencode.ai/docs/#install

Start OpenCode

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:
{
  "$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 PackageAPI TypeUse Case
@ai-sdk/openai-compatibleChat Completion APIGPT, Claude, and most other models
@ai-sdk/openaiResponse APICodex 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. opencode_input_api_key

Start Using

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

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.
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())

  1. Add the local MCP to opencode.json
{
  "mcp": {
    "calc_mcp": {
      "type": "local",
      "command": ["python3", "{your_local_path}/calc_mcp.py"],
      "enabled": true
    }
  }
}
  1. Use /mcps to check MCP connection status. When in Enabled state, OpenCode can invoke it.
opencode_mcp