メインコンテンツへスキップ
OpenCode は、開発者向けのオープンソース AI コーディングエージェント(Coding Agent)で、「ターミナルネイティブ」な体験を特徴としています。TUI/CLI を通じて、コマンドライン内で要件の相談、コード生成、リファクタリング、説明、デバッグなどのワークフローを実行できます。OpenCode は「モデル非依存」を重視しており、Claude、GPT、Gemini など複数のモデルサービスに接続できるほか、ローカルまたは OpenAI 互換インターフェースにも対応しているため、コスト、性能、プライバシーのバランスを自由に選択できます。また、OpenCode は拡張可能なプラグイン/ツール機構と設定体系を提供しており、プロジェクトコンテキストやコマンド実行などの機能を自動化フローに組み込めます。ターミナルを多用するユーザーや、AI コーディングワークフローをカスタマイズしたいチームに適しています。

インストールと接続

インストール

curl -fsSL https://opencode.ai/install | bash
その他のインストール方法については、OpenCode 公式サイトを参照してください:https://opencode.ai/docs/#install

OpenCode の起動

cd /path/to/project  # 进入项目路径

opencode  # 启动 OpenCode

JieKou API への接続

  • グローバル設定:~/.config/opencode/opencode.json
  • プロジェクト設定:プロジェクトルートディレクトリ配下の opencode.json
(opencode.json がない場合は、手動で作成できます) 設定は以下のとおりです:
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "myprovider": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "JieKou",
      "options": {
        "baseURL": "https://api.highwayapi.ai/openai/v1"
      },
      "models": {
        "claude-sonnet-4-5-20250929": {
          "name": "claude-sonnet-4-5-20250929"
        },
        "gpt-5.2": {
          "name": "gpt-5.2"
        },
      }
    }
  }
}
サードパーティプロバイダーを設定する際は、正しい npm パッケージを選択する必要があります:
npm パッケージAPI タイプ適用シーン
@ai-sdk/openai-compatibleChat Completion APIGPT、Claude など大半のモデル
@ai-sdk/openaiResponse APICodex シリーズモデル
注意: Codex モデル(例:gpt-5.1-codex)では @ai-sdk/openai(Response API)を使用する必要があります。その他のモデルでは @ai-sdk/openai-compatible(Chat Completion API)を使用します。

KEY の設定

opencode に入り、/connect でプロバイダーを選択した後、API KEY を入力し、enter で確定します。 opencode_input_api_key

使用開始

プロバイダーに接続した後、/models コマンドでモデルを選択できます。 opencode_choose_model

その他の使い方

例:ローカル MCP 設定(計算 MCP を例として)

  1. python + MCP SDK を使用して電卓 mcp server コードを作成し、ローカルパスに保存します
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. opencode.json にローカル mcp を追加します
{
  "mcp": {
    "calc_mcp": {
      "type": "local",
      "command": ["python3", "{your_local_path}/calc_mcp.py"],
      "enabled": true
    }
  }
}
  1. /mcps を使用して mcp の接続状態を確認します。Enabled 状態の場合、opencode に呼び出させることができます。
opencode_mcp