GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — support custom tools (#2668) · AndyS77/opencode@3b6c0ec

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • .opencode/tool
    • foo.ts
  • bun.lock
  • packages
    • opencode
      • src
        • config
          • config.ts
        • plugin
          • index.ts
        • server
          • server.ts
        • tool
          • registry.ts
          • tool.ts
      • test/tool
        • register.test.ts
    • plugin
      • package.json
      • src
        • example.ts
        • index.ts
        • tool.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎.opencode/tool/foo.ts‎

Copy file name to clipboard
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import z from "zod/v4"
2+
3+
export default {
4+
description: "foo tool for fooing",
5+
args: {
6+
foo: z.string().describe("foo"),
7+
},
8+
async execute() {
9+
return "Hey fuck you!"
10+
},
11+
}
Collapse file

‎bun.lock‎

Copy file name to clipboardExpand all lines: bun.lock
+1Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Collapse file

‎packages/opencode/src/config/config.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/config/config.ts
+18-3Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ export namespace Config {
4848
}
4949

5050
result.agent = result.agent || {}
51+
52+
const directories = [
53+
Global.Path.config,
54+
...(await Array.fromAsync(
55+
Filesystem.up({ targets: [".opencode"], start: Instance.directory, stop: Instance.worktree }),
56+
)),
57+
]
58+
5159
const markdownAgents = [
5260
...(await Filesystem.globUp("agent/**/*.md", Global.Path.config, Global.Path.config)),
5361
...(await Filesystem.globUp(".opencode/agent/**/*.md", Instance.directory, Instance.worktree)),
@@ -203,7 +211,10 @@ export namespace Config {
203211
result.keybinds.agent_cycle_reverse = result.keybinds.switch_agent_reverse
204212
}
205213

206-
return result
214+
return {
215+
config: result,
216+
directories,
217+
}
207218
})
208219

209220
export const McpLocal = z
@@ -655,7 +666,11 @@ export namespace Config {
655666
}),
656667
)
657668

658-
export function get() {
659-
return state()
669+
export async function get() {
670+
return state().then((x) => x.config)
671+
}
672+
673+
export async function directories() {
674+
return state().then((x) => x.directories)
660675
}
661676
}
Collapse file

‎packages/opencode/src/plugin/index.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/plugin/index.ts
+3-14Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { Hooks, Plugin as PluginInstance } from "@opencode-ai/plugin"
1+
import type { Hooks, PluginInput, Plugin as PluginInstance } from "@opencode-ai/plugin"
22
import { Config } from "../config/config"
33
import { Bus } from "../bus"
44
import { Log } from "../util/log"
@@ -7,7 +7,6 @@ import { Server } from "../server/server"
77
import { BunProc } from "../bun"
88
import { Instance } from "../project/instance"
99
import { Flag } from "../flag/flag"
10-
import { ToolRegistry } from "../tool/registry"
1110

1211
export namespace Plugin {
1312
const log = Log.create({ service: "plugin" })
@@ -19,14 +18,12 @@ export namespace Plugin {
1918
})
2019
const config = await Config.get()
2120
const hooks = []
22-
const input = {
21+
const input: PluginInput = {
2322
client,
2423
project: Instance.project,
2524
worktree: Instance.worktree,
2625
directory: Instance.directory,
2726
$: Bun.$,
28-
Tool: await import("../tool/tool").then((m) => m.Tool),
29-
z: await import("zod").then((m) => m.z),
3027
}
3128
const plugins = [...(config.plugin ?? [])]
3229
if (!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS) {
@@ -53,7 +50,7 @@ export namespace Plugin {
5350
})
5451

5552
export async function trigger<
56-
Name extends Exclude<keyof Required<Hooks>, "auth" | "event">,
53+
Name extends Exclude<keyof Required<Hooks>, "auth" | "event" | "tool">,
5754
Input = Parameters<Required<Hooks>[Name]>[0],
5855
Output = Parameters<Required<Hooks>[Name]>[1],
5956
>(name: Name, input: Input, output: Output): Promise<Output> {
@@ -78,14 +75,6 @@ export namespace Plugin {
7875
const config = await Config.get()
7976
for (const hook of hooks) {
8077
await hook.config?.(config)
81-
// Let plugins register tools at startup
82-
await hook["tool.register"]?.(
83-
{},
84-
{
85-
registerHTTP: ToolRegistry.registerHTTP,
86-
register: ToolRegistry.register,
87-
},
88-
)
8978
}
9079
Bus.subscribeAll(async (input) => {
9180
const hooks = await state().then((x) => x.hooks)
Collapse file

‎packages/opencode/src/server/server.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/server/server.ts
+1-47Lines changed: 1 addition & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -52,29 +52,6 @@ const ERRORS = {
5252
export namespace Server {
5353
const log = Log.create({ service: "server" })
5454

55-
// Schemas for HTTP tool registration
56-
const HttpParamSpec = z
57-
.object({
58-
type: z.enum(["string", "number", "boolean", "array"]),
59-
description: z.string().optional(),
60-
optional: z.boolean().optional(),
61-
items: z.enum(["string", "number", "boolean"]).optional(),
62-
})
63-
.meta({ ref: "HttpParamSpec" })
64-
65-
const HttpToolRegistration = z
66-
.object({
67-
id: z.string(),
68-
description: z.string(),
69-
parameters: z.object({
70-
type: z.literal("object"),
71-
properties: z.record(z.string(), HttpParamSpec),
72-
}),
73-
callbackUrl: z.string(),
74-
headers: z.record(z.string(), z.string()).optional(),
75-
})
76-
.meta({ ref: "HttpToolRegistration" })
77-
7855
export const Event = {
7956
Connected: Bus.event("server.connected", z.object({})),
8057
}
@@ -153,29 +130,6 @@ export namespace Server {
153130
return c.json(await Config.get())
154131
},
155132
)
156-
.post(
157-
"/experimental/tool/register",
158-
describeRoute({
159-
description: "Register a new HTTP callback tool",
160-
operationId: "tool.register",
161-
responses: {
162-
200: {
163-
description: "Tool registered successfully",
164-
content: {
165-
"application/json": {
166-
schema: resolver(z.boolean()),
167-
},
168-
},
169-
},
170-
...ERRORS,
171-
},
172-
}),
173-
validator("json", HttpToolRegistration),
174-
async (c) => {
175-
ToolRegistry.registerHTTP(c.req.valid("json"))
176-
return c.json(true)
177-
},
178-
)
179133
.get(
180134
"/experimental/tool/ids",
181135
describeRoute({
@@ -194,7 +148,7 @@ export namespace Server {
194148
},
195149
}),
196150
async (c) => {
197-
return c.json(ToolRegistry.ids())
151+
return c.json(await ToolRegistry.ids())
198152
},
199153
)
200154
.get(
Collapse file

‎packages/opencode/src/tool/registry.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/tool/registry.ts
+55-80Lines changed: 55 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import z from "zod/v4"
21
import { BashTool } from "./bash"
32
import { EditTool } from "./edit"
43
import { GlobTool } from "./glob"
@@ -13,6 +12,12 @@ import { WriteTool } from "./write"
1312
import { InvalidTool } from "./invalid"
1413
import type { Agent } from "../agent/agent"
1514
import { Tool } from "./tool"
15+
import { Instance } from "../project/instance"
16+
import { Config } from "../config/config"
17+
import path from "path"
18+
import { type ToolDefinition } from "@opencode-ai/plugin"
19+
import z from "zod/v4"
20+
import { Plugin } from "../plugin"
1621

1722
export namespace ToolRegistry {
1823
// Built-in tools that ship with opencode
@@ -32,101 +37,71 @@ export namespace ToolRegistry {
3237
TaskTool,
3338
]
3439

35-
// Extra tools registered at runtime (via plugins)
36-
const EXTRA: Tool.Info[] = []
40+
export const state = Instance.state(async () => {
41+
const custom = [] as Tool.Info[]
42+
const glob = new Bun.Glob("tool/*.{js,ts}")
3743

38-
// Tools registered via HTTP callback (via SDK/API)
39-
const HTTP: Tool.Info[] = []
40-
41-
export type HttpParamSpec = {
42-
type: "string" | "number" | "boolean" | "array"
43-
description?: string
44-
optional?: boolean
45-
items?: "string" | "number" | "boolean"
46-
}
47-
export type HttpToolRegistration = {
48-
id: string
49-
description: string
50-
parameters: {
51-
type: "object"
52-
properties: Record<string, HttpParamSpec>
44+
for (const dir of await Config.directories()) {
45+
for await (const match of glob.scan({ cwd: dir, absolute: true })) {
46+
const namespace = path.basename(match, path.extname(match))
47+
const mod = await import(match)
48+
for (const [id, def] of Object.entries<ToolDefinition>(mod)) {
49+
custom.push(fromPlugin(id === "default" ? namespace : `${namespace}_${id}`, def))
50+
}
51+
}
5352
}
54-
callbackUrl: string
55-
headers?: Record<string, string>
56-
}
5753

58-
function buildZodFromHttpSpec(spec: HttpToolRegistration["parameters"]) {
59-
const shape: Record<string, z.ZodTypeAny> = {}
60-
for (const [key, val] of Object.entries(spec.properties)) {
61-
let base: z.ZodTypeAny
62-
switch (val.type) {
63-
case "string":
64-
base = z.string()
65-
break
66-
case "number":
67-
base = z.number()
68-
break
69-
case "boolean":
70-
base = z.boolean()
71-
break
72-
case "array":
73-
if (!val.items) throw new Error(`array spec for ${key} requires 'items'`)
74-
base = z.array(val.items === "string" ? z.string() : val.items === "number" ? z.number() : z.boolean())
75-
break
76-
default:
77-
base = z.any()
54+
const plugins = await Plugin.list()
55+
for (const plugin of plugins) {
56+
for (const [id, def] of Object.entries(plugin.tool ?? {})) {
57+
custom.push(fromPlugin(id, def))
7858
}
79-
if (val.description) base = base.describe(val.description)
80-
shape[key] = val.optional ? base.optional() : base
8159
}
82-
return z.object(shape)
83-
}
8460

85-
export function register(tool: Tool.Info) {
86-
// Prevent duplicates by id (replace existing)
87-
const idx = EXTRA.findIndex((t) => t.id === tool.id)
88-
if (idx >= 0) EXTRA.splice(idx, 1, tool)
89-
else EXTRA.push(tool)
61+
return { custom }
62+
})
63+
64+
function fromPlugin(id: string, def: ToolDefinition): Tool.Info {
65+
return {
66+
id,
67+
init: async () => ({
68+
parameters: z.object(def.args),
69+
description: def.description,
70+
execute: async (args, ctx) => {
71+
const result = await def.execute(args as any, ctx)
72+
return {
73+
title: "",
74+
output: result,
75+
metadata: {},
76+
}
77+
},
78+
}),
79+
}
9080
}
9181

92-
export function registerHTTP(input: HttpToolRegistration) {
93-
const parameters = buildZodFromHttpSpec(input.parameters)
94-
const info = Tool.define(input.id, {
95-
description: input.description,
96-
parameters,
97-
async execute(args) {
98-
const res = await fetch(input.callbackUrl, {
99-
method: "POST",
100-
headers: { "content-type": "application/json", ...(input.headers ?? {}) },
101-
body: JSON.stringify({ args }),
102-
})
103-
if (!res.ok) {
104-
throw new Error(`HTTP tool callback failed: ${res.status} ${await res.text()}`)
105-
}
106-
const json = (await res.json()) as { title?: string; output: string; metadata?: Record<string, any> }
107-
return {
108-
title: json.title ?? input.id,
109-
output: json.output ?? "",
110-
metadata: (json.metadata ?? {}) as any,
111-
}
112-
},
113-
})
114-
const idx = HTTP.findIndex((t) => t.id === info.id)
115-
if (idx >= 0) HTTP.splice(idx, 1, info)
116-
else HTTP.push(info)
82+
export async function register(tool: Tool.Info) {
83+
const { custom } = await state()
84+
const idx = custom.findIndex((t) => t.id === tool.id)
85+
if (idx >= 0) {
86+
custom.splice(idx, 1, tool)
87+
return
88+
}
89+
custom.push(tool)
11790
}
11891

119-
function allTools(): Tool.Info[] {
120-
return [...BUILTIN, ...EXTRA, ...HTTP]
92+
async function all(): Promise<Tool.Info[]> {
93+
const custom = await state().then((x) => x.custom)
94+
return [...BUILTIN, ...custom]
12195
}
12296

123-
export function ids() {
124-
return allTools().map((t) => t.id)
97+
export async function ids() {
98+
return all().then((x) => x.map((t) => t.id))
12599
}
126100

127101
export async function tools(_providerID: string, _modelID: string) {
102+
const tools = await all()
128103
const result = await Promise.all(
129-
allTools().map(async (t) => ({
104+
tools.map(async (t) => ({
130105
id: t.id,
131106
...(await t.init()),
132107
})),
Collapse file

‎packages/opencode/src/tool/tool.ts‎

Copy file name to clipboardExpand all lines: packages/opencode/src/tool/tool.ts
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ export namespace Tool {
88
sessionID: string
99
messageID: string
1010
agent: string
11-
callID?: string
1211
abort: AbortSignal
12+
callID?: string
1313
extra?: { [key: string]: any }
1414
metadata(input: { title?: string; metadata?: M }): void
1515
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.