Skip to content

5.9b HTTP API Reference

💡 One-line summary: OpenCode server provides a complete REST API for programmatic interaction with OpenCode.

📝 Course Notes

Key concepts from this lesson:

5.9b HTTP API Reference Notes


What You'll Learn

  • Understand the overall structure of OpenCode API
  • Manage sessions and messages using the API
  • Execute commands and operate files via API
  • Listen to SSE event streams

API Overview

OpenCode server publishes an OpenAPI 3.1 specification, viewable with interactive documentation at:

http://<hostname>:<port>/doc

Example: http://localhost:4096/doc


Authentication

If the server has OPENCODE_SERVER_PASSWORD environment variable set, all API requests require HTTP Basic Auth authentication.

curl Example

bash
# With Basic Auth
curl -u opencode:your-password http://localhost:4096/global/health

# Or manually set Authorization header
curl -H "Authorization: Basic $(echo -n 'opencode:your-password' | base64)" \
  http://localhost:4096/global/health

Authentication Parameters

ParameterDescription
UsernameDefault opencode, or value of OPENCODE_SERVER_USERNAME environment variable
PasswordValue of OPENCODE_SERVER_PASSWORD environment variable

Global API

/global

MethodPathDescriptionResponse
GET/global/healthServer health status{ healthy: true, version: string }
GET/global/eventGlobal event stream (SSE)Event stream

Example:

bash
# Check server health (no auth)
curl http://localhost:4096/global/health

# If server has password set
curl -u opencode:your-password http://localhost:4096/global/health

Response:

json
{
  "healthy": true,
  "version": "1.0.48"
}

Source: opencode/packages/opencode/src/server/server.ts:131-150


Project API

/project

MethodPathDescriptionResponse
GET/projectList all projectsProject[]
GET/project/currentGet current projectProject

Source: opencode/packages/web/src/content/docs/server.mdx:88-94


Path & Version Control API

/path, /vcs

MethodPathDescriptionResponse
GET/pathGet current pathPath
GET/vcsGet VCS info for current projectVcsInfo

Source: opencode/packages/web/src/content/docs/server.mdx:97-103


Instance API

/instance

MethodPathDescriptionResponse
POST/instance/disposeDestroy current instanceboolean

Source: opencode/packages/web/src/content/docs/server.mdx:106-111


Configuration API

/config

MethodPathDescriptionResponse
GET/configGet configuration infoConfig
PATCH/configUpdate configurationConfig
GET/config/providersList providers and default models{ providers: Provider[], default: Record<string, string> }

Source: opencode/packages/web/src/content/docs/server.mdx:114-121


Provider API

/provider

MethodPathDescriptionResponse
GET/providerList all providers{ all: Provider[], default: {...}, connected: string[] }
GET/provider/authGet provider auth methods{ [providerID: string]: ProviderAuthMethod[] }
POST/provider/{id}/oauth/authorizeInitiate OAuth authorizationProviderAuthAuthorization
POST/provider/{id}/oauth/callbackHandle OAuth callbackboolean

Source: opencode/packages/web/src/content/docs/server.mdx:124-132


Session API

/session

This is the most commonly used API for managing conversation sessions.

MethodPathDescriptionNotes
GET/sessionList all sessionsReturns Session[]
POST/sessionCreate new sessionbody: { parentID?, title? }
GET/session/statusGet all session statuses{ [sessionID: string]: SessionStatus }
GET/session/:idGet session detailsReturns Session
DELETE/session/:idDelete session and its dataReturns boolean
PATCH/session/:idUpdate session propertiesbody: { title? }
GET/session/:id/childrenGet child sessionsReturns Session[]
GET/session/:id/todoGet session todo listReturns Todo[]
POST/session/:id/initAnalyze app and create AGENTS.mdbody: { messageID, providerID, modelID }
POST/session/:id/forkFork session from specified messagebody: { messageID? }
POST/session/:id/abortAbort running sessionReturns boolean
POST/session/:id/shareShare sessionReturns Session
DELETE/session/:id/shareUnshare sessionReturns Session
GET/session/:id/diffGet session file diffquery: messageID?
POST/session/:id/summarizeSummarize sessionbody: { providerID, modelID }
POST/session/:id/revertRevert messagebody: { messageID, partID? }
POST/session/:id/unrevertRestore all reverted messagesReturns boolean
POST/session/:id/permissions/:permissionIDRespond to permission requestbody: { response, remember? }

Source: opencode/packages/web/src/content/docs/server.mdx:135-157

Example - Create new session:

bash
curl -X POST http://localhost:4096/session \
  -H "Content-Type: application/json" \
  -d '{"title": "Code Review Session"}'

Message API

/session/:id/message

MethodPathDescriptionNotes
GET/session/:id/messageList messagesquery: limit?
POST/session/:id/messageSend message and wait for responsesee body below
GET/session/:id/message/:messageIDGet message detailsReturns { info, parts }
POST/session/:id/prompt_asyncSend message asynchronously (no wait)Returns 204 No Content
POST/session/:id/commandExecute slash commandbody: { command, arguments, ... }
POST/session/:id/shellRun shell commandbody: { agent, model?, command }

Send Message Request Body

typescript
{
  messageID?: string,     // Optional, message ID
  model?: string,         // Optional, specify model
  agent?: string,         // Optional, specify agent
  noReply?: boolean,      // Optional, don't wait for reply
  system?: string,        // Optional, system prompt
  tools?: string[],       // Optional, enabled tools
  parts: Part[]           // Message content
}

Source: opencode/packages/web/src/content/docs/server.mdx:160-170

Example - Send message:

bash
curl -X POST http://localhost:4096/session/abc123/message \
  -H "Content-Type: application/json" \
  -d '{
    "parts": [
      {"type": "text", "text": "Explain what this code does"}
    ]
  }'

Command API

/command

MethodPathDescriptionResponse
GET/commandList all commandsCommand[]

Source: opencode/packages/web/src/content/docs/server.mdx:173-178


File API

/find, /file

MethodPathDescriptionResponse
GET/find?pattern=<pat>Search file contentsArray of matches
GET/find/file?query=<q>Find files by namestring[] (paths)
GET/find/symbol?query=<q>Find workspace symbolsSymbol[]
GET/file?path=<path>List directory contentsFileNode[]
GET/file/content?path=<p>Read file contentFileContent
GET/file/statusGet tracked file statusFile[]

/find/file Query Parameters

ParameterRequiredDescription
queryYesSearch string (fuzzy match)
typeNoLimit to "file" or "directory"
directoryNoOverride project root directory
limitNoMax results (1-200)
dirsNoLegacy parameter, "false" for files only

Source: opencode/packages/web/src/content/docs/server.mdx:181-199

Example - Search files:

bash
# Search for files with "config" in the name
curl "http://localhost:4096/find/file?query=config&limit=10"

# Search file contents
curl "http://localhost:4096/find?pattern=TODO"

Tool API (Experimental)

/experimental/tool

MethodPathDescriptionResponse
GET/experimental/tool/idsList all tool IDsToolIDs
GET/experimental/tool?provider=<p>&model=<m>Get available tools and JSON Schema for modelToolList

Source: opencode/packages/web/src/content/docs/server.mdx:202-208


LSP, Formatter & MCP API

/lsp, /formatter, /mcp

MethodPathDescriptionResponse
GET/lspGet LSP server statusLSPStatus[]
GET/formatterGet formatter statusFormatterStatus[]
GET/mcpGet MCP server status{ [name: string]: MCPStatus }
POST/mcpDynamically add MCP serverbody: { name, config }
POST/mcp/:name/authStart MCP OAuth authentication{ authorizationUrl: string }
POST/mcp/:name/auth/callbackHandle MCP OAuth callbackboolean

Source: opencode/packages/web/src/content/docs/server.mdx:211-218, server.ts:2197-2230


Agent API

/agent

MethodPathDescriptionResponse
GET/agentList all available agentsAgent[]

Source: opencode/packages/web/src/content/docs/server.mdx:222-227


Log API

/log

MethodPathDescriptionResponse
POST/logWrite log entryboolean

Request body:

typescript
{
  service: string,           // Service name
  level: "debug" | "info" | "warn" | "error",
  message: string,           // Log message
  extra?: Record<string, any> // Additional metadata
}

Source: opencode/packages/web/src/content/docs/server.mdx:230-235


TUI Control API

/tui

Used for remote control of the TUI interface, primarily used by IDE plugins.

MethodPathDescriptionResponse
POST/tui/append-promptAppend text to prompt boxboolean
POST/tui/open-helpOpen help dialogboolean
POST/tui/open-sessionsOpen session selectorboolean
POST/tui/open-themesOpen theme selectorboolean
POST/tui/open-modelsOpen model selectorboolean
POST/tui/submit-promptSubmit current promptboolean
POST/tui/clear-promptClear prompt boxboolean
POST/tui/execute-commandExecute commandbody: { command }
POST/tui/show-toastShow toast notificationbody: { title?, message, variant }
GET/tui/control/nextWait for next control requestControl request object
POST/tui/control/responseRespond to control requestbody: { body }

Source: opencode/packages/web/src/content/docs/server.mdx:238-253

Example - Remote control TUI:

bash
# Add text to prompt box
curl -X POST http://localhost:4096/tui/append-prompt \
  -H "Content-Type: application/json" \
  -d '{"text": "Please help me review this code"}'

# Submit prompt
curl -X POST http://localhost:4096/tui/submit-prompt

# Show notification
curl -X POST http://localhost:4096/tui/show-toast \
  -H "Content-Type: application/json" \
  -d '{"message": "Operation complete", "variant": "success"}'

Authentication API

/auth

MethodPathDescriptionResponse
PUT/auth/:idSet authentication credentialsboolean

Request body must match the corresponding provider's schema.

Source: opencode/packages/web/src/content/docs/server.mdx:256-261


Event Stream API

/event

MethodPathDescriptionResponse
GET/eventSSE event streamServer-sent events

Upon connection, you first receive a server.connected event, followed by various bus events.

Source: opencode/packages/web/src/content/docs/server.mdx:264-269

Example - Listen to events:

bash
curl -N http://localhost:4096/event

Output example:

event: server.connected
data: {}

event: session.created
data: {"id":"abc123","title":"New Session"}

event: message.created
data: {"sessionID":"abc123","content":"..."}

API Documentation

/doc

MethodPathDescriptionResponse
GET/docOpenAPI 3.1 specification docsHTML page

Source: opencode/packages/web/src/content/docs/server.mdx:272-277


Type Definitions

Complete TypeScript type definitions can be found in the SDK:

https://github.com/opencode-ai/opencode/blob/dev/packages/sdk/js/src/gen/types.gen.ts

Common types:

  • Session - Session info
  • Message - Message info
  • Part - Message content part
  • Provider - Provider info
  • Agent - Agent info
  • Config - Configuration info

Common Pitfalls

IssueCauseSolution
Request returns CORS errorClient origin not whitelistedAdd --cors <origin> when starting
No response after sending messageUsed prompt_asyncUse synchronous /session/:id/message instead
SSE connection drops frequentlyNetwork timeout or proxy issuesCheck proxy settings, increase timeout
404 errorSession or message ID doesn't existVerify resource exists via GET endpoint first
Experimental API unavailableFeature may change or be removedCheck latest docs to confirm

Lesson Summary

You learned:

  1. API Structure: 19 API categories covering sessions, messages, files, tools, etc.
  2. Session Management: Create, query, fork, and share sessions
  3. Message Interaction: Send messages synchronously/asynchronously, execute commands
  4. File Operations: Search, read, and list files
  5. TUI Control: Remote control of TUI interface
  6. Event Listening: Receive real-time events via SSE


Next Lesson Preview

In the next lesson, we'll learn how to develop using the SDK.