Skip to content

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:

Terminal window
npm install @opencode-ai/sdk

Create 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

OptionTypeDescriptionDefault
hostnamestringServer hostname127.0.0.1
portnumberServer port4096
signalAbortSignalAbort signal for cancellationundefined
timeoutnumberTimeout in ms for server start5000
configConfigConfiguration 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

OptionTypeDescriptionDefault
baseUrlstringURL of the serverhttp://localhost:4096
fetchfunctionCustom fetch implementationglobalThis.fetch
parseAsstringResponse parsing methodauto
responseStylestringReturn style: data or fieldsfields
throwOnErrorbooleanThrow errors instead of returnfalse

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" },