How to write an OpenCode plugin with the v2 API

By

Updated

Tagged: AI

Build your first OpenCode v2 plugin in TypeScript, register a custom tool, validate its inputs, test the logic, and understand how v1 plugins change.

An OpenCode plugin lets you add your own tools, commands, or hooks straight to the coding agent. You can use one to expose your project’s data, automate a command you run all the time, or tweak requests before they hit a model.

In this tutorial, we’ll build a small price quote tool. The model hands it a quantity and a unit price, and our code checks those numbers and returns the total in cents.

I kept the example tiny on purpose. You can check the math in your head, and you can test the whole thing locally without spending a cent on model calls. Once you see how the plumbing works, swapping the math for real project logic is straightforward.

You’ll need a recent version of Node.js and OpenCode. Everything here uses the v2 plugin API from @opencode/plugin. If you see examples online importing @opencode-ai/plugin, those are for the older v1 API.

A plugin runs code on your computer

OpenCode loads your plugin right inside its server process, so your code gets the same local access as that process.

That’s very different from dropping rules into AGENTS.md. Instructions only nudge the agent toward a habit, while a plugin runs real code on your machine.

If you just want a reusable review prompt, start with a custom command. If you want the agent to use single quotes, put that in your project instructions. Reach for a plugin when you need code, a custom tool interface, or a lifecycle hook.

Our quote tool stays safe and contained. It won’t read files, talk to a network service, or touch anything on disk, which lets you learn how plugin registration works before worrying about auth or permissions.

Here’s how that fits together:

Choose the smallest OpenCode extensionA reusable review prompt can be a custom command. Project conventions belong in instructions. Executable operations or lifecycle hooks call for a plugin.Saved promptConventionCode or hookBehavior to addWhat does it need?CommandAGENTS.mdPlugin

Create the project

Start by creating a fresh folder for the project:

mkdir opencode-quote
cd opencode-quote
npm init -y
npm pkg set type=module
npm install @opencode/plugin
npm install --save-dev typescript tsx @types/node
mkdir -p .opencode/plugins/quote

If you’re on Omarchy and need Node.js and npm, install them first with omarchy pkg add nodejs npm. Everything else here works the same on macOS and Linux.

Here’s the folder layout we’re aiming for:

opencode-quote/
  package.json
  tsconfig.json
  quote.ts
  quote.test.ts
  .opencode/
    plugins/
      quote/
        index.ts

Notice that the helper files sit at the project root. Keeping them out of .opencode/plugins/ stops OpenCode from trying to load them as standalone plugins.

Next, save this config in tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["*.ts", ".opencode/plugins/**/*.ts"]
}

We’re only using TypeScript for type-checking here, without emitting JavaScript files, and tsx will run the tests directly.

Write the calculation first

Whenever a model calls a tool, it passes in arguments at runtime. TypeScript types disappear once the code runs, so we still need to validate those inputs ourselves.

Put the calculation logic in quote.ts:

export function quote(input: unknown) {
  if (typeof input !== 'object' || input === null) {
    throw new TypeError('A quote needs an object')
  }

  const { quantity, unitPriceCents } = input as Record<string, unknown>

  if (
    typeof quantity !== 'number' ||
    !Number.isSafeInteger(quantity) ||
    quantity < 1
  ) {
    throw new RangeError('Quantity must be a positive safe integer')
  }

  if (
    typeof unitPriceCents !== 'number' ||
    !Number.isSafeInteger(unitPriceCents) ||
    unitPriceCents < 0
  ) {
    throw new RangeError('Unit price must be a non-negative safe integer')
  }

  const totalCents = quantity * unitPriceCents

  if (!Number.isSafeInteger(totalCents)) {
    throw new RangeError('The total exceeds the supported integer range')
  }

  return { quantity, unitPriceCents, totalCents }
}

All prices are integer cents. Floating-point math on decimal prices leads to rounding bugs you don’t want anywhere near billing.

Keep in mind this is just a small learning example. It skips currencies with different minor units, tax, discounts, and any real catalog lookup. In a real store, your server should look up the official price from a product ID instead of letting the model decide what a customer pays.

You also want to check the multiplication result itself, because two valid integers can still multiply into a number past JavaScript’s safe integer limit.

Register the tool

An OpenCode v2 plugin exports a definition with a stable ID and a setup() function. Inside setup(), you register a transform that adds your tool to OpenCode’s tool catalog.

Save this plugin entry point in .opencode/plugins/quote/index.ts:

import { Plugin } from '@opencode/plugin'
import { quote } from '../../../quote.ts'

export default Plugin.define({
  id: 'tutorial.quote',
  async setup(ctx) {
    await ctx.tool.transform(editor => {
      editor.namespace({
        name: 'shop',
        description: 'Deterministic shop calculations'
      })

      editor.add({
        name: 'quote',
        description: 'Calculate a total from a quantity and unit price in cents',
        input: {
          type: 'object',
          properties: {
            quantity: { type: 'integer', minimum: 1 },
            unitPriceCents: { type: 'integer', minimum: 0 }
          },
          required: ['quantity', 'unitPriceCents'],
          additionalProperties: false
        },
        options: { namespace: 'shop', codemode: true },
        async execute(input) {
          return { content: JSON.stringify(quote(input)) }
        }
      })
    })
  }
})

The plugin API gives us Plugin.define() and the catalog editor, while our calculation stays plain TypeScript.

The JSON Schema tells OpenCode and the model what inputs to send. The checks inside quote() still guard the code at runtime, catching edge cases like a multiplication that overflows JavaScript’s safe integer range.

Setting the namespace to shop gives the tool the full ID shop_quote. Turning on codemode: true exposes it to Code Mode, so the agent can chain calls to it in JavaScript.

For the return value, execute() sends back a v2 tool result object with text content, using JSON.stringify() so the fields stay easy to inspect. Returning a raw string straight from execute() is the old v1 pattern.

Why the transform callback is synchronous

OpenCode can rebuild the tool catalog at any point by replaying every registered transform, so treat that callback as a pure description of your tools.

Keep side effects out of it. Never make HTTP requests, charge an account, start timers, or write database rows inside the transform callback, because a catalog rebuild will run all of that again.

If your tool needs config from a remote service, fetch it first and register the transform afterward. When you eventually need a catalog that updates over time, the API gives you reload methods for that, so there’s no reason to add that complexity upfront.

Our callback only declares the shop namespace and the tool. The calculation itself runs later, when execute() gets called.

Fig 1 · 1/3Plugin lifecycle
OpenCode loads the plugin module.

Test before opening an agent

Before firing up OpenCode, write a quick test file in quote.test.ts:

import test from 'node:test'
import assert from 'node:assert/strict'
import { quote } from './quote.ts'

test('calculates a quote in cents', () => {
  assert.deepEqual(quote({ quantity: 3, unitPriceCents: 1250 }), {
    quantity: 3,
    unitPriceCents: 1250,
    totalCents: 3750
  })
})

test('allows a zero price', () => {
  assert.equal(quote({ quantity: 2, unitPriceCents: 0 }).totalCents, 0)
})

test('rejects invalid quantities', () => {
  for (const quantity of [0, -1, 1.5, NaN, Infinity]) {
    assert.throws(() => quote({ quantity, unitPriceCents: 1250 }))
  }
})

test('rejects invalid prices and overflowing totals', () => {
  assert.throws(() => quote({ quantity: 1, unitPriceCents: -1 }))
  assert.throws(() => quote({ quantity: 2, unitPriceCents: Number.MAX_SAFE_INTEGER }))
  assert.throws(() => quote(null))
})

Then run the type checker and the test suite:

npx tsc
npx tsx --test quote.test.ts

That verifies both the plugin definition and the calculation types, and tests the logic without calling a model. With those passing, we’re ready to see if OpenCode picks up the plugin.

Load it in OpenCode

Start OpenCode from inside the opencode-quote directory:

opencode

OpenCode picks up files inside .opencode/plugins/ through automatic discovery, so you don’t need to add anything to a plugins config entry.

Pick any connected model and send this prompt:

Use the shop quote tool to calculate 3 items at 1250 cents each.
Report the total in cents. Don't modify any files.

Watch the output to make sure the agent calls your custom tool and returns 3750 cents. If it replies with “3750” on its own without a tool call, the model did the math in its head and your plugin probably didn’t load.

Next, try a prompt that needs two quotes:

Use the shop quote tool for 3 items at 1250 cents and for 5 items
at 900 cents. Compare the totals. Don't modify files.

You’re looking for 3750 and 4500. Depending on the model and the session, the agent might make two separate tool calls or combine them through Code Mode.

If the tool doesn’t appear

First, run opencode --version. A v1 CLI won’t load a v2 plugin properly. If you have both versions installed side by side, the v2 installer also gives you an opencode2 command.

Next, double-check the file path. OpenCode auto-discovers .opencode/plugins/quote/index.ts, while a root-level plugins/quote/index.ts needs to be registered in your config.

Check the startup logs for errors, too. A broken TypeScript import will stop setup() from finishing. Because index.ts imports quote.ts with a relative path back to the project root, moving index.ts on its own breaks it. Don’t be surprised if opencode plugin list doesn’t show your plugin either, since that command tracks configured packages rather than auto-discovered local files.

OpenCode watches plugin files and reloads them when they change. If an imported helper file doesn’t pick up your edits, run opencode service restart to bounce the service. That restarts the shared service for every session, so wrap up any other work running in OpenCode first.

If you plan to publish the plugin later, keep its dependencies aligned with the OpenCode version you target, and commit your lockfile so anyone else can reproduce your test runs.

Adding access to a real service

Use a plugin for small, project-specific jobs with clear inputs and outputs you can verify, like reading a product record from an internal catalog.

Keep read-only actions separate from risky ones, like splitting a quote lookup from a purchase. Checking a price and charging a card need different permission rules. Jamming both into one tool makes it much harder for the agent, and for you when reviewing tool calls, to tell what’s about to happen.

When your plugin talks to an external service, wire up the permission API for what it does, validate any resource IDs it receives, and forward the cancellation signal from the execution context to requests that support it.

Never hardcode API keys in your source files or echo them back in a tool result. The model only needs the data from the response, and your error handling shouldn’t leak request headers when a call fails.

Porting an older plugin

If you already have a v1 plugin to update, start with the v1 migration guide. Moving the file into the new folder won’t cut it on its own.

The biggest change is how tools and hooks get registered. A v1 plugin returned an object full of tools and hooks. In v2, you register them through ctx inside setup(). Hook callbacks use different event shapes too, so changing the import path alone won’t work.

The cleanest way to port is to keep your core logic or service client untouched, wrap it in tests, and rewrite only the thin adapter that talks to OpenCode. Notice how our quote() function doesn’t know or care which plugin API is calling it.

Once everything works locally, package it for npm and test the installed package itself. Missing files and relative imports have a habit of breaking after packaging even when the local folder runs fine.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: