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

Most of the /session, /file, and /event paths covered below belong to the V1 API. v1.18.22 retains V1 while extending V2 through /api/*; upgrading does not automatically convert existing V1 calls to V2.

Source: packages/sdk/js/package.json:12-20, V1 sdk.gen.ts:431-700, V2 sdk.gen.ts:5426-5873

V2 API Extensions

V2 is more than a model catalog. In the target version, it extends sessions, questions, the current location, event streams, paginated history, runtime operations, and permission requests:

MethodPathDescription
GET/api/locationResolve the current directory/workspace location
GET / POST/api/sessionList sessions with pagination / create a session
GET/api/session/:sessionIDGet a session
GET/api/session/:sessionID/historyRead a bounded page of events using after and limit
GET/api/session/:sessionID/eventReplay and then continuously subscribe to events for the session
POST/api/session/:sessionID/interruptInterrupt an active execution owned by the current process
GET/api/session/:sessionID/questionList pending questions for the session
POST/api/session/:sessionID/question/:requestID/replyAnswer a pending question
POST/api/session/:sessionID/question/:requestID/rejectReject a pending question
GET / POST/api/session/:sessionID/permissionList or create session-level permission requests
GET/api/permission/requestList pending permission requests by location
GET/api/eventV2 server-event SSE stream

Source: sdk.gen.ts:5038-5058, sdk.gen.ts:5171-5424, sdk.gen.ts:5426-5793, sdk.gen.ts:6319-6405, sdk.gen.ts:6549-6559


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
# No authentication is required when no server password is configured
curl http://localhost:4096/global/health

# After configuring OPENCODE_SERVER_PASSWORD, health also requires Basic Auth
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/revertUndo to a specific message/part and roll back related file patches by defaultbody: { messageID, partID? }
POST/session/:id/unrevertRedo the reverted message and file stateReturns Session
POST/session/:id/permissions/:permissionIDRespond to permission requestbody: { response }

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

revert does more than hide chat messages: the service locates the target boundary, collects subsequent patches, restores the snapshot, and updates the session diff. unrevert restores the original snapshot and clears the revert state. Both operations require the session to be idle. Setting snapshot: false disables only file-snapshot undo/redo; message-boundary revert semantics remain available.

Source: session/revert.ts:38-98, config.ts:52-55, V1 sdk.gen.ts:678-700

Example - Create new session:

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

Workspace API (Experimental)

In v1.18.22, workspaces are adapter-driven. The built-in adapter is worktree, and the API can list adapters, create or discover workspaces, inspect connection status, and warp sessions. Requests can use the directory / workspace query parameters for workspace-aware routing; warp with copyChanges copies the Git patch.

MethodPathDescription
GET/experimental/workspace/adapterList adapters available to the current project
GET / POST/experimental/workspaceList / create workspaces
POST/experimental/workspace/sync-listRegister workspaces discovered by an adapter but not yet recorded
GET/experimental/workspace/statusGet connection status
POST/experimental/workspace/warpMove a session, optionally with copyChanges

Historical boundary

The v1.16.0 release promised that managed workspace cloning would preserve dirty and untracked files. In the target tag, the current implementation has moved to the adapter/worktree path. That historical capability must not be treated as current v1.18.22 API behavior: the implementation evidence for copyChanges is a Git patch, with no promise to copy all untracked files.

Current implementation: workspace API paths:12-47, workspace API endpoints:53-127, workspace.ts:492-538, workspace.ts:559-620, workspace-routing.ts:148-185. Historical evidence: v1.16.0 Release, commit 5661af203487b90cf9ee0844b198b03cce26c412.


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?: {               // Optional, specify model
    providerID: string,
    modelID: string
  },
  agent?: string,         // Optional, specify agent
  noReply?: boolean,      // Optional, don't wait for reply
  system?: string,        // Optional, system prompt
  tools?: Record<string, boolean>, // Deprecated; prefer permission configuration
  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/anomalyco/opencode/blob/v1.18.22/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.