opencode serve command runs a headless HTTP server that exposes an OpenAPI-compliant REST API. This architecture enables multiple clients (TUI, web, IDE plugins, custom integrations) to interact with the same OpenCode instance programmatically.
Architecture Overview
When you runopencode, it starts both:
- Server: HTTP API server (Hono + Bun runtime) exposing OpenAPI 3.1 endpoints
- TUI Client: Terminal interface that communicates with the server via HTTP
- Multiple simultaneous clients connecting to one server
- Programmatic control via HTTP APIs
- Real-time event streaming via Server-Sent Events (SSE)
- Cross-platform compatibility (local, remote, containerized)
The TUI and server communicate over HTTP on
localhost. When using proxies, you must bypass localhost and 127.0.0.1 to prevent routing loops.Starting the Server
Standalone Mode
Run a dedicated server without the TUI:Port to listen on. Use
0 to auto-assign a free port.Hostname/IP to bind to. Use
0.0.0.0 to accept connections from any interface (requires authentication).Enable mDNS (Bonjour) service discovery for local network clients.
Custom domain name for the mDNS service announcement.
Additional CORS origins to allow. Can be specified multiple times.
Example with CORS
Connect to Existing Server
When starting the TUI, specify connection details:Authentication
HTTP Basic Auth
Protect your server with username/password authentication:opencode serve(standalone server)opencode web(web interface + server)
Authentication Flow
- Server reads
OPENCODE_SERVER_PASSWORDat startup - All requests (except OPTIONS preflight) require HTTP Basic Auth
- Username defaults to
opencodeor usesOPENCODE_SERVER_USERNAME - Invalid credentials return
401 Unauthorized
OpenAPI Specification
The server publishes a complete OpenAPI 3.1 spec:Using the Spec
Generate SDK clients
Generate SDK clients
Use tools like
openapi-generator or swagger-codegen to generate type-safe clients:Import into Postman/Insomnia
Import into Postman/Insomnia
- Open Postman/Insomnia
- Import → OpenAPI URL
- Enter:
http://localhost:4096/doc?format=json - All endpoints will be available for testing
Validate API contracts
Validate API contracts
Use the spec for contract testing:
Core API Endpoints
Health & Events
Always
true if server is running.OpenCode version (e.g.,
1.2.3).Real-time Events (SSE)
server.connected- Initial connection eventserver.heartbeat- Keepalive every 10 seconds- All bus events (session lifecycle, file changes, etc.)
SSE connections include
X-Accel-Buffering: no header to prevent proxy buffering issues.Project Context
directory parameter (query or header) to scope operations:
Sessions
Create and manage AI conversation sessions:Session title. Auto-generated if omitted.
Parent session ID for creating branched conversations.
Send Messages
Array of message parts (text, images, files).
Override model (format:
provider/model, e.g., openai/gpt-4.1).Agent to use (e.g.,
task, research).Send message without waiting for AI response.
Async Messaging
For fire-and-forget messages, use the async endpoint:GET /event).
TUI Control API
Programmatically control the TUI (used by IDE plugins):/tui/append-prompt- Add text to prompt input/tui/submit-prompt- Submit current prompt/tui/clear-prompt- Clear prompt input/tui/open-sessions- Open session selector/tui/open-models- Open model selector/tui/show-toast- Display notification/tui/execute-command- Run slash command
Advanced Features
File Operations
LSP & Formatters
Session Sharing
Error Handling
The server returns structured errors:NamedError pattern with:
name- Error class namemessage- Human-readable descriptiondata- Contextual error details
Server Implementation Details
Technology Stack
- Runtime: Bun (high-performance JavaScript runtime)
- Framework: Hono (lightweight HTTP framework)
- WebSockets: Native Bun websocket support
- SSE: Hono streaming utilities
- Validation: Zod schemas with hono-openapi
CORS Policy
Default allowed origins:http://localhost:*(any port)http://127.0.0.1:*(any port)tauri://localhost(Tauri desktop apps)https://*.opencode.ai(official web clients)- Custom origins via
--corsflag
Request Lifecycle
- CORS preflight - OPTIONS requests bypass auth
- Authentication - HTTP Basic Auth if
OPENCODE_SERVER_PASSWORDis set - Logging - Request method and path logged (except
/logendpoint) - Instance resolution - Extract
directoryfrom query/header, load project instance - Route handler - Execute endpoint logic
- Error handling - Convert exceptions to structured JSON responses
- Response - JSON or SSE stream
Performance Characteristics
- Idle timeout: Disabled (connections can stay open indefinitely)
- SSE heartbeat: 10-second intervals
- Port fallback: If
--port 0, tries 4096 first, then random - Graceful shutdown: Unpublishes mDNS before stopping
Use Cases
Custom Clients
Build custom UI clients (mobile apps, web dashboards) using the HTTP API.
CI/CD Integration
Automate code review, testing, and documentation generation in pipelines.
IDE Plugins
Create editor extensions that communicate with OpenCode server.
Remote Development
Run OpenCode server on remote machines, connect from local clients.
Next Steps
Network Configuration
Configure proxies, certificates, and mDNS discovery.
Session Sharing
Learn about sharing sessions and collaboration features.
JavaScript SDK
Use the official TypeScript/JavaScript SDK for type-safe API access.
Troubleshooting
Diagnose and fix common server issues.