Skip to main content
OpenCode implements the Model Context Protocol (MCP) to integrate external tools and services, providing the AI assistant with access to specialized capabilities beyond built-in tools.

What is MCP?

The Model Context Protocol (MCP) is a standardized way for AI assistants to interact with external tools and services. It provides:
  • Standardized interface for tool discovery and execution
  • Multiple transport types (stdio, SSE)
  • Dynamic tool registration at runtime
  • Consistent permission model across all tools
OpenCode uses the mcp-go library to implement MCP client functionality.

How MCP works in OpenCode

1

Server configuration

You configure MCP servers in .opencode.json with connection details and authentication
2

Initialization

When OpenCode starts, it connects to configured MCP servers and discovers available tools
3

Tool registration

MCP tools are registered alongside built-in tools with a {server-name}_{tool-name} naming pattern
4

Tool execution

When AI calls an MCP tool, OpenCode creates a new client connection, executes the tool, and returns results

Connection types

OpenCode supports two MCP transport types:
Standard Input/Output transportCommunicate with tools via stdin/stdout, perfect for local executables.
{
  "mcpServers": {
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"],
      "env": []
    }
  }
}
Configuration fields:
type
string
required
Must be "stdio"
command
string
required
Executable command to run (e.g., npx, python, /usr/local/bin/mcp-server)
args
array
Command-line arguments to pass to the executable
env
array
Environment variables to set (format: ["KEY=value"])
Best for:
  • Local tools and scripts
  • Python/Node.js MCP servers
  • Command-line utilities
  • File system access

Configuration

MCP servers are configured in .opencode.json under the mcpServers key:
{
  "mcpServers": {
    "server-name": {
      "type": "stdio" | "sse",
      // ... type-specific configuration
    }
  }
}
The server name becomes part of the tool identifier: {server-name}_{tool-name}

Complete configuration example

{
  "mcpServers": {
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/allowed-directory"
      ],
      "env": []
    },
    "github": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-github"
      ],
      "env": [
        "GITHUB_TOKEN=ghp_your_token_here"
      ]
    },
    "web-search": {
      "type": "sse",
      "url": "https://mcp.example.com/search",
      "headers": {
        "Authorization": "Bearer your-token",
        "Content-Type": "application/json"
      }
    }
  }
}

Available MCP servers

The MCP ecosystem includes many pre-built servers:

Filesystem

@modelcontextprotocol/server-filesystem
  • Read/write file operations
  • Directory listing
  • File search
  • Safe path restrictions
npx @modelcontextprotocol/server-filesystem /allowed/path

GitHub

@modelcontextprotocol/server-github
  • Repository operations
  • Issue management
  • Pull request workflows
  • Code search
Requires: GITHUB_TOKEN

PostgreSQL

@modelcontextprotocol/server-postgres
  • Query execution
  • Schema inspection
  • Table operations
  • Safe query validation
Requires: Database connection string

Web Search

@modelcontextprotocol/server-brave-search
  • Web search capabilities
  • News search
  • Safe search filtering
Requires: Brave API key

Slack

@modelcontextprotocol/server-slack
  • Send messages
  • Channel management
  • User lookup
Requires: Slack bot token

Google Drive

@modelcontextprotocol/server-gdrive
  • File access
  • Document reading
  • Upload/download
Requires: OAuth credentials
Find more MCP servers at the MCP Servers Registry

Tool naming and discovery

Tool name format

MCP tools are automatically named: {server-name}_{tool-name} Example: If you configure a server named github that provides a tool called create_issue, the tool becomes available as github_create_issue.

Tool discovery

1

Server initialization

On startup, OpenCode connects to each configured MCP server
2

Tool listing

Sends ListTools request to discover available tools
3

Registration

Each discovered tool is registered with schema:
  • Tool name (prefixed with server name)
  • Description
  • Input parameters and types
  • Required fields
4

Availability

Tools become available to the AI assistant alongside built-in tools

Example: filesystem server

If the filesystem server provides these tools:
  • read_file
  • write_file
  • list_directory
They become:
  • filesystem_read_file
  • filesystem_write_file
  • filesystem_list_directory

Permission model

MCP tools follow the same permission system as built-in tools:
Each MCP tool execution requires permission approval:
┌─ Permission Required ──────────────────┐
│ Tool: github_create_issue              │
│ Action: execute                        │
│                                        │
│ Parameters:                            │
│ {                                      │
│   "title": "Bug in user auth",        │
│   "body": "Description...",           │
│   "labels": ["bug"]                   │
│ }                                      │
│                                        │
│ [Allow] [Allow for Session] [Deny]    │
└────────────────────────────────────────┘
Grant permission for entire session:
  • Press A in permission dialog
  • Permission persists for all future calls
  • Scoped to specific tool and session
  • Tool parameters are visible in permission prompt
  • Sensitive data (tokens, passwords) shown in permissions
  • Review all parameters before approval
  • Session permissions don’t persist across restarts

Real-world examples

Example 1: Filesystem operations

Configuration:
{
  "mcpServers": {
    "filesystem": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/projects"
      ],
      "env": []
    }
  }
}
Usage: The AI can now use filesystem_read_file, filesystem_write_file, etc., within the /Users/username/projects directory.

Example 2: GitHub integration

Configuration:
{
  "mcpServers": {
    "github": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": [
        "GITHUB_TOKEN=ghp_xxxxxxxxxxxx"
      ]
    }
  }
}
Usage:
User: Create an issue for the bug we just found

AI uses: github_create_issue
Parameters:
{
  "owner": "myorg",
  "repo": "myproject",
  "title": "Fix authentication error in login flow",
  "body": "...",
  "labels": ["bug", "priority-high"]
}

Example 3: Database queries

Configuration:
{
  "mcpServers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": [
        "DATABASE_URL=postgresql://user:password@localhost:5432/mydb"
      ]
    }
  }
}
Usage:
User: Show me the top 10 users by activity

AI uses: database_query
Parameters:
{
  "query": "SELECT user_id, COUNT(*) as activity FROM events WHERE created_at > NOW() - INTERVAL '7 days' GROUP BY user_id ORDER BY activity DESC LIMIT 10"
}

Example 4: Multi-server workflow

Configuration:
{
  "mcpServers": {
    "github": { /* ... */ },
    "slack": { /* ... */ },
    "database": { /* ... */ }
  }
}
Usage:
User: When PR #123 is merged, analyze the impact and notify the team

AI workflow:
1. Uses github_get_pr to fetch PR details
2. Uses database_query to check affected tables
3. Uses github_list_files to analyze changed files
4. Uses slack_send_message to notify team with summary

Building custom MCP servers

You can create custom MCP servers for specialized functionality:
# server.py
from mcp.server import MCPServer, Tool
from mcp.types import TextContent

server = MCPServer("my-custom-tools")

@server.tool(
    name="analyze_logs",
    description="Analyze application logs for errors",
    parameters={
        "log_path": {
            "type": "string",
            "description": "Path to log file"
        },
        "severity": {
            "type": "string",
            "enum": ["error", "warning", "info"]
        }
    }
)
def analyze_logs(log_path: str, severity: str) -> list[TextContent]:
    # Your implementation
    with open(log_path) as f:
        logs = f.read()
    # Analyze logs...
    return [TextContent(text=f"Found {count} {severity} messages")]

if __name__ == "__main__":
    server.run()
Configuration:
{
  "mcpServers": {
    "custom": {
      "type": "stdio",
      "command": "python",
      "args": ["/path/to/server.py"],
      "env": []
    }
  }
}

Troubleshooting

Check:
  • Command path is correct and executable
  • Required dependencies are installed (npx may need to download packages)
  • Environment variables are set correctly
  • Check OpenCode debug logs: opencode -d
Verify:
  • Server successfully initialized (check logs)
  • Server implements ListTools correctly
  • Tool schemas are valid
  • Restart OpenCode after config changes
Ensure:
  • Authentication tokens are valid
  • File paths are within allowed directories
  • Service accounts have necessary permissions
  • Check MCP server logs for auth errors
Debug:
  • Check tool parameters match schema
  • Verify required fields are provided
  • Review MCP server error logs
  • Test tool directly via MCP server CLI
  • Enable debug mode: "debug": true in config

Best practices

Name servers clearly

Use descriptive names that indicate purpose:
  • github not gh
  • database-prod not db
  • filesystem-safe for restricted access

Scope permissions

Configure minimal necessary access:
  • Filesystem servers: specific directories only
  • Database servers: read-only when possible
  • API servers: scope tokens appropriately

Use environment variables

Store sensitive data securely:
  • Never commit tokens to config files
  • Use environment variables for secrets
  • Consider using secret management tools

Test independently

Verify MCP servers work before integration:
  • Test with MCP CLI tools first
  • Verify authentication separately
  • Check tool schemas are valid

Handle errors gracefully

Design tools for robustness:
  • Validate inputs thoroughly
  • Provide helpful error messages
  • Include fallback behavior

Document tool usage

Help AI use tools correctly:
  • Write clear tool descriptions
  • Document parameter formats
  • Include usage examples

Security considerations

MCP tools can access sensitive systems and data. Follow these security practices:
  • Principle of least privilege: Grant minimum necessary permissions
  • Network isolation: Use stdio for local tools when possible
  • Token rotation: Regularly rotate API keys and tokens
  • Audit logs: Monitor tool usage and review permission grants
  • Input validation: MCP servers should validate all inputs
  • Safe defaults: Configure restrictive defaults, expand as needed

Next steps

MCP Specification

Learn about the Model Context Protocol specification

MCP Servers

Browse available MCP server implementations

Configuration

Complete configuration reference

AI Tools

Explore OpenCode’s built-in tools

Build docs developers (and LLMs) love