SDK
Type-safe JS client for opencode server.
The opencode JS/TS SDK provides a type-safe client for interacting with the server. Use it to build integrations and control opencode programmatically.
Learn more about how the server works. For examples, check out the projects built by the community.
Install
Install the SDK from npm:
npm install @opencode-ai/sdkCreate client
Create an instance of opencode:
import { createOpencode } from "@opencode-ai/sdk"
const { client } = await createOpencode()This starts both a server and a client
Options
| Option | Type | Description | Default |
|---|---|---|---|
hostname | string | Server hostname | 127.0.0.1 |
port | number | Server port | 4096 |
signal | AbortSignal | Abort signal for cancellation | undefined |
timeout | number | Timeout in ms for server start | 5000 |
config | Config | Configuration object | {} |
Config
You can pass a configuration object to customize behavior. The instance still picks up your opencode.json, but you can override or add configuration inline:
import { createOpencode } from "@opencode-ai/sdk"
const opencode = await createOpencode({ hostname: "127.0.0.1", port: 4096, config: { model: "anthropic/claude-3-5-sonnet-20241022", },})
console.log(`Server running at ${opencode.server.url}`)
opencode.server.close()Client only
If you already have a running instance of opencode, you can create a client instance to connect to it:
import { createOpencodeClient } from "@opencode-ai/sdk"
const client = createOpencodeClient({ baseUrl: "http://localhost:4096",})Options
| Option | Type | Description | Default |
|---|---|---|---|
baseUrl | string | URL of the server | http://localhost:4096 |
fetch | function | Custom fetch implementation | globalThis.fetch |
parseAs | string | Response parsing method | auto |
responseStyle | string | Return style: data or fields | fields |
throwOnError | boolean | Throw errors instead of return | false |
Types
The SDK includes TypeScript definitions for all API types. Import them directly:
import type { Session, Message, Part } from "@opencode-ai/sdk"All types are generated from the server’s OpenAPI specification and available in the types file.
Errors
The SDK can throw errors that you can catch and handle:
try { await client.session.get({ path: { id: "invalid-id" } })} catch (error) { console.error("Failed to get session:", (error as Error).message)}Structured Output
You can request structured JSON output from the model by specifying an format with a JSON schema. The model will use a StructuredOutput tool to return validated JSON matching your schema.
Basic Usage
const result = await client.session.prompt({ path: { id: sessionId }, body: { parts: [{ type: "text", text: "Research Anthropic and provide company info" }], format: { type: "json_schema", schema: { type: "object", properties: { company: { type: "string", description: "Company name" }, founded: { type: "number", description: "Year founded" }, products: { type: "array", items: { type: "string" },