How to package and publish an OpenCode plugin
By Flavio
Updated
Tagged: AI
Package an OpenCode v2 plugin for npm, inspect the tarball, test it in a clean consumer project, and prepare a public release with clear compatibility.
A plugin can work fine in your own project and still break the moment someone else installs it. Maybe a helper file got left out of the package, a relative import reaches outside the folder, or the entry point targets the wrong API.
In this guide, we’ll turn the quote tool from the OpenCode plugin tutorial into a small npm package. Before publishing anything, we’ll pack a local tarball, install it in a fresh project, and verify both registration and calculation.
Everything here uses OpenCode’s v2 API and follows the package publishing documentation. Make sure you install @opencode/plugin, since older @opencode-ai/plugin examples use a different API.
Create a separate package
You’ll need a recent Node.js installation and OpenCode v2. Run opencode --version first to check what you have. If you still keep v1 around, your v2 executable might be opencode2.
Start by creating a folder for the package:
mkdir opencode-quote-package
cd opencode-quote-package
mkdir src
Now create package.json inside it:
{
"name": "@flaviocopes/opencode-quote",
"version": "1.0.0",
"type": "module",
"exports": "./src/index.js",
"files": ["src"],
"license": "MIT",
"scripts": {
"test": "node --test"
}
}
I’m using the @flaviocopes scope in these examples. Swap it for an npm account or organization you control, and update the later imports and tarball filename to match.
exports tells OpenCode which entry file to load, and files limits which source files npm packs (npm already includes standard metadata like README.md and LICENSE on its own). Writing this in plain JavaScript also skips any build step, so there’s no dist folder to forget.
Next, install the plugin SDK:
npm install @opencode/plugin --save-exact
That adds the current SDK version to dependencies. Commit the lockfile in your repository, and test your package against the OpenCode release you plan to support instead of assuming every future SDK will stay compatible.
Keep the implementation inside the package
Our tool calculates a total in integer cents. Create src/quote.js with the calculation logic:
export function quote({ quantity, unitPriceCents }) {
if (!Number.isSafeInteger(quantity) || quantity < 1) {
throw new RangeError('Quantity must be a positive safe integer')
}
if (!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('Total exceeds the supported integer range')
}
return { quantity, unitPriceCents, totalCents }
}
The function validates the inputs even though the tool schema describes them too, and it checks the multiplication result as well. If you adapt this for a real shop, look up your own authoritative prices and handle your currency rules there.
Now wire the tool up in src/index.js:
import { Plugin } from '@opencode/plugin'
import { quote } from './quote.js'
export default Plugin.define({
id: 'tutorial.packaged-quote',
async setup(ctx) {
await ctx.tool.transform(editor => {
editor.namespace({
name: 'shop',
description: 'Deterministic shop calculations'
})
editor.add({
name: 'quote',
description: 'Calculate a quote using integer 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 default export is the same plugin definition you’d use for a local v2 plugin, so you don’t need an npm-specific factory or a v1 hooks object.
Because both files live inside src/, the ./quote.js import still resolves once someone installs the package. The transform declares the tool, and the executor computes the total locally without any network calls or billing logic.
Add a useful test and README
Add quote.test.js at the root of the package so you can verify the math directly:
import test from 'node:test'
import assert from 'node:assert/strict'
import { quote } from './src/quote.js'
test('calculates integer cents and supports a free item', () => {
assert.equal(quote({ quantity: 3, unitPriceCents: 1250 }).totalCents, 3750)
assert.equal(quote({ quantity: 2, unitPriceCents: 0 }).totalCents, 0)
})
test('rejects invalid inputs and overflow', () => {
for (const quantity of [0, -1, 1.5, '3', NaN]) {
assert.throws(() => quote({ quantity, unitPriceCents: 1250 }))
}
assert.throws(() => quote({ quantity: 1, unitPriceCents: -1 }))
assert.throws(() => quote({ quantity: 2, unitPriceCents: Number.MAX_SAFE_INTEGER }))
})
Run npm test to execute it. These tests check the calculation directly without calling a model.
Now add a short README.md:
# OpenCode quote tutorial
An OpenCode v2 server plugin providing the `shop_quote` tool.
It accepts positive integer quantities and non-negative integer unit prices
in cents, then returns the quantity, unit price, and total.
It performs no purchases, file writes, or network requests.
See the package's LICENSE file for its terms.
As the package develops, document the supported OpenCode API and installation steps. You’ll also need a LICENSE file in the repo matching the license you set in package.json. For this example, copy the MIT license text and add your own copyright notice.
Inspect what npm will distribute
Before packing the archive, check which files npm plans to include by running this from the package folder:
npm pack --dry-run
Make sure the list includes src/index.js, src/quote.js, package.json, README.md, and LICENSE, with quote.test.js left out. Scan the output for anything that shouldn’t ship, especially credentials or private fixtures.
Now generate the local tarball with the npm pack command, which builds the archive without publishing anything:
npm pack
That creates flaviocopes-opencode-quote-1.0.0.tgz. List its contents to double-check what made it inside:
tar -tzf flaviocopes-opencode-quote-1.0.0.tgz
tar -xOf flaviocopes-opencode-quote-1.0.0.tgz package/package.json
Verify that exports points to a file inside that archive, and skim the packaged source files too so you catch any secret that might have slipped into an included file.
Install the archive in a fresh project
Testing with a linked development folder can hide missing package files. Instead, create a sibling consumer folder and install the tarball directly:
cd ..
mkdir quote-consumer
cd quote-consumer
npm init -y
npm install ../opencode-quote-package/flaviocopes-opencode-quote-1.0.0.tgz
Create check.mjs in that consumer folder to smoke-test the installed package:
import assert from 'node:assert/strict'
import plugin from '@flaviocopes/opencode-quote'
let registered
await plugin.setup({
tool: {
async transform(edit) {
edit({
namespace() {},
add(definition) { registered = definition }
})
}
}
})
assert.equal(plugin.id, 'tutorial.packaged-quote')
assert.equal(registered.name, 'quote')
assert.equal(registered.options.namespace, 'shop')
const result = await registered.execute({ quantity: 3, unitPriceCents: 1250 })
assert.equal(JSON.parse(result.content).totalCents, 3750)
await assert.rejects(registered.execute({ quantity: -1, unitPriceCents: 1250 }))
console.log('Installed package registers the tool and validates its calculation')
Run node check.mjs. It imports the installed package and runs the tool adapter against a small stand-in catalog, exercising the real SDK import, default export, and executor.
Next, verify that the running OpenCode service discovers the plugin. Save opencode.json in the consumer folder:
{
"$schema": "https://opencode.ai/config.json",
"plugins": ["./node_modules/@flaviocopes/opencode-quote"]
}
Open OpenCode v2 from this folder, start a connected session, and send this prompt:
Use the shop quote tool for 3 items at 1250 cents each.
Don't change any files. Report the total in cents.
Look for a shop_quote tool call returning 3750. The model can compute that number on its own, so verify the tool ran rather than just checking the answer. If you previously installed the local quote example in this same project, remove it first so both copies don’t register the same tool.
We point OpenCode at the installed local folder here because OpenCode’s plugin manager doesn’t accept tarball targets in plugin add. Installing the tarball with npm and loading its installed directory lets you test the packaged files.
If the consumer fails while the source project passes, inspect the installed files first. Run npm ls @opencode/plugin in the consumer folder to see which dependency version resolved, and compare exports with the archive listing. A helper imported from outside the package folder often works in development and breaks after installation. Keep that failing consumer around until you’ve reproduced and fixed the issue.
Prepare the public release
Check whether your package name is free on npm before publishing:
npm whoami
npm view @flaviocopes/opencode-quote name
If the package already exists, you’ll need ownership of it or another name. A not-found response tells you the name is free, and running npm whoami confirms you’re logged into an account that can publish under that scope. If you hit an authentication or network error, resolve it and run the check again before moving on.
Review LICENSE and README.md, run the tests, and pack and inspect a fresh tarball. Bump the package version for every new release you publish.
When everything looks right, publish the tarball you just checked:
npm publish ./flaviocopes-opencode-quote-1.0.0.tgz --access public
Everything up to here stayed local. This is the command that pushes the package to the npm registry.
Under npm’s publishing authentication requirements, interactive publishing requires 2FA, with separately configured token options. Complete the prompt when npm asks, and keep tokens out of source files, examples, and committed .npmrc files.
For CI releases later, set up OIDC with npm’s trusted publishing guide so your release workflow doesn’t need a long-lived publishing token stored in the repo. Check the guide’s current runtime requirements and package settings before setting it up.
After release, install the registry version in a clean consumer and configure its exact package revision in OpenCode’s plugins list. Keep running the tarball check whenever you change the plugin, since it catches packaging mistakes that tests in your source folder won’t see.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: