# OpenCode Features and Practical Usage
🤖 Turn OpenCode from "a tool you chat with in the terminal" into "a dev server you drive from code." The SDK plus a headless server let you embed AI coding into CI and custom UIs.
🏷️ Title: Type-safe JS client and headless server
🔗 URL:
📘 Overview
OpenCode can run not only as a TUI but as a headless server you control over HTTP. The type-safe `
@opencode-ai/sdk` JavaScript/TypeScript client connects to that server to create sessions, send prompts, and subscribe to events. All types are generated from the server's OpenAPI spec, so completion and type-checking work out of the box.
⚙️ How It Works
・Start the server: `opencode serve` launches a headless server, defaulting to `127.0.0.1:4096`. The SDK's `createOpencode()` can both start the server and hand you a client in one call.
・Connect a client: For an existing server, use `createOpencodeClient({ baseUrl: "http://localhost:4096" })`.
・Core APIs: Create/list/get/update/delete sessions, share/unshare, abort, and revert/unrevert messages. Send prompts with `client.session.prompt()`.
・Structured output: Pass `format: { type: "json_schema", schema: {...} }` to receive validated JSON matching your schema, ideal for downstream machine processing.
・Event stream: `client.event.subscribe()` gives you server-sent events as a stream to monitor long-running operations.
🛠️ Practical Usage
Starting the server from code is a few calls: `createOpencode()` returns both a `client` and `server`, then `client.session.create()` opens a session and `client.session.prompt()` sends a prompt (passing a `format` of `json_schema` for structured output), and `server.close()` shuts it down.
For CI, `noReply: true` is handy when you want to inject context without triggering an AI response.
💡 Use Cases
・A review bot fetches a structured findings JSON via the SDK (instead of `opencode run`) and posts a formatted GitHub PR comment.
・A custom web UI or editor extension uses the `tui` APIs to append/submit prompts and show toasts, building a bespoke frontend.
・A nightly batch sends the same analysis prompt across many repos and stores the resulting JSON in a data platform.
⚠️ Caveats
・SDK config overrides and merges with `opencode.json` rather than replacing it entirely, so watch for lingering unintended settings.
・Structured output retries on validation failure (default 2). If it still fails, ` holds a `StructuredOutputError`. Keep schemas small and focused for reliability.
・Calls like `client.session.get()` throw on an invalid ID, so wrap them in try-catch.
#
OpenCode# #
AIAgents#