opencode icon indicating copy to clipboard operation
opencode copied to clipboard

Tool names differing only in characters normalized to _ silently collide

Open feiiiiii5 opened this issue 2 months ago • 6 comments

Description

Tool registrations are keyed by effectiveName, which normalizes the name before keying it:

// packages/core/src/tool/runtime.ts:274
export const normalizedName = (tool: Tool.Info) => tool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
export const effectiveName = (tool: Tool.Info) =>
  tool.options?.namespace === undefined
    ? normalizedName(tool)
    : `${tool.options.namespace.replaceAll(".", "_")}_${normalizedName(tool)}`

So two registrations whose names are visibly different can land on the same key, and the second silently replaces the first — packages/core/src/tool.ts:184 is a plain editor.tools.set(id, …) with no collision check. registrationError (tool.ts:304) cannot catch it either, because the charset test runs on normalizedName(tool), i.e. after the characters that would collide have already been replaced.

Computing the ids for pairs a user can actually write:

registered as key
deploy.staging deploy_staging
deploy_staging deploy_staging
my tool my_tool
a/b a_b
ns a.b + tool c a_b_c
ns a + tool b_c a_b_c

Every pair above collides, and every one of them passes registrationError. The result is that one tool disappears from the model's tool list with no diagnostic anywhere. Case is not affected (MyTool and mytool stay distinct), and - is preserved, so the vector is specifically ., /, space and any other character outside [A-Za-z0-9_-] in a tool name, plus . in a namespace.

This is not the documented override. docs/custom-tools.mdx:82 covers the case where a tool deliberately uses a built-in's name, and the note there says to prefer unique names "unless you intentionally want to replace a built-in tool" — that behaviour works and I'd keep it. The gap is that two names which look unique to the author still collide, so the advice in that note does not help.

Three ways to close it:

  1. Report it. When two registrations with different original names produce the same key, add a RegistrationError (or a warning) naming both. Same-name overrides keep working unchanged. This matches how a duplicate plugin id is already reported loudly in #48706.
  2. Document it. State in custom-tools.mdx that keys are normalized, so a.b and a_b are the same tool. Cheapest, but a user hitting it still has no signal.
  3. Narrow the normalization. Reject or escape the characters that create the ambiguity instead of folding them to _. Most correct, but it would break existing tools whose names rely on the current folding.

I'd lean towards 1. Happy to take any of them.

Steps to reproduce

  1. Create .opencode/tools/deploy.staging.ts and .opencode/tools/deploy_staging.ts, each exporting a tool with a distinct description.
  2. Start opencode and list the available tools.
  3. Only one deploy_staging is present; nothing reports that the other was dropped.

OpenCode version

v2, 5556ad563

Operating System

macOS

feiiiiii5 avatar Oct 01 '26 03:10 feiiiiii5

This issue might be a duplicate of existing issues. Please check:

  • #51651: Two tool registrations resolving to the same effective ID silently replace one another, with no collision diagnostic.

github-actions[bot] avatar Oct 01 '26 03:10 github-actions[bot]

#51651 is our own earlier report, and it is closed: the compliance bot auto-closed it for not using the Bug report template's Description field, so it was never a live report and nothing was decided on it.

The substance here is narrower than #51651 in one respect and wider in another. Narrower: a deliberate same-name override is documented behaviour (docs/custom-tools.mdx:82, added by #14313) and is not what this reports. Wider: the collision is created by normalizedName, so the two registered names are visibly different — deploy.staging and deploy_staging — and registrationError validates the charset after normalization, so it cannot detect them.

feiiiiii5 avatar Oct 01 '26 03:10 feiiiiii5

Thanks for the detailed report. I reproduced this on the latest dev (891a020bc).

The script below registers two tools with different names in one registry update, for each of these pairs:

  • deploy.staging / deploy_staging
  • my tool / my_tool
  • a/b / a_b
  • namespace a.b + c / namespace a + b_c

In every case only the second tool is left in the registry and in the tool list sent to the model. Nothing is logged and no registration error is recorded, so the first tool disappears with no warning.

I tested at the tool-registry level and didn't start the app with files in .opencode/tools/. Both files would still end up under the same id.

Reproduction script (tool-collision.test.ts)
// Reproduction for anomalyco/opencode#52420.
// Copy into packages/core/test/ of an opencode checkout and run:
//   cd packages/core && bun test test/tool-collision.test.ts
import { describe, expect } from "bun:test"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Image } from "@opencode/core/image"
import { PluginHooks } from "@opencode/core/plugin/hooks"
import { Tool } from "@opencode/core/tool"
import type { Info } from "@opencode/schema/tool"
import { LayerNode } from "@opencode/util/effect/layer-node"
import { Effect, Layer, Schema } from "effect"
import { testEffect } from "./lib/effect"

const it = testEffect(
  AppNodeBuilder.build(LayerNode.group([Tool.node, PluginHooks.node]), [
    Image.node.replace(Layer.mock(Image.Service, { normalize: (_r, c) => Effect.succeed(c) })),
  ]),
)

const make = (name: string, description: string, namespace?: string): Info => ({
  name,
  description,
  input: Schema.Struct({ text: Schema.String }),
  output: Schema.Struct({ text: Schema.String }),
  execute: ({ text }) => Effect.succeed({ output: { text }, content: text }),
  options: namespace === undefined ? { codemode: false } : { namespace, codemode: false },
})

const pairs: [Info, Info][] = [
  [make("deploy.staging", "first: deploy.staging"), make("deploy_staging", "second: deploy_staging")],
  [make("my tool", "first: my tool"), make("my_tool", "second: my_tool")],
  [make("a/b", "first: a/b"), make("a_b", "second: a_b")],
  [make("c", "first: ns a.b + c", "a.b"), make("b_c", "second: ns a + b_c", "a")],
]

describe("#52420 tool name collisions", () => {
  for (const [first, second] of pairs) {
    it.effect(`'${first.options?.namespace ?? ""}/${first.name}' vs '${second.options?.namespace ?? ""}/${second.name}'`, () =>
      Effect.gen(function* () {
        const service = yield* Tool.Service
        yield* service.transform((editor) => {
          editor.add(first)
          editor.add(second)
        })
        const listed = yield* service.list()
        const defs = (yield* service.snapshot()).definitions
        console.log(
          "registered 2 distinct names ->",
          listed.map((t) => `${t.id} (${t.description})`),
          "| model sees:",
          defs.map((d) => d.name),
        )
        // Expected: both tools present, or a registration error naming both. Actual: one silently dropped.
        expect(listed.length).toBe(2)
      }),
    )
  }
})

Run it: bun tool-collision.test.ts

opencodejr[bot] avatar Oct 28 '26 00:10 opencodejr[bot]

The same collision happens with MCP tools. The registry key is <namespace>_<tool>, and the server name is normalized (McpTool.namespace / McpTool.name in packages/core/src/tool/mcp.ts). So servers named my.server and my_server, or server a with tool b_c and server a_b with tool c, produce the same key, and only the last one survives (commit → editor.tools.set in packages/core/src/tool.ts). Since the permission action is the same name(server, tool), rules written for one server's tool also apply to the other.

Our app lets users add MCP servers from a catalog. For that, we'd prefer the registry to refuse both colliding registrations and record a registration error (the existing errors list and the "Skipping invalid tool registration" log) rather than keep either one. Keeping the first one would depend on load order across reloads. Today we patch packages/core/src/mcp/index.ts to drop colliding MCP tools. A check in the registry would cover plugin tools too.

impharaon avatar Nov 12 '26 09:11 impharaon

Confirmed the MCP path lands in the same key: McpTool builds <namespace>_<name> before tool.ts sees it, so my.server + x and my_server + x both become my_server_x. That makes a registry-level check the right place, since it covers file tools, plugin tools and MCP tools in one guard.

On the two options: I agree with recording both colliding registrations as errors rather than keeping one. "First wins" would make the surviving tool depend on MCP reload order, which is not something a user can reason about.

The discriminator should be the original tuple, not the normalized key: two different originals (deploy.staging / deploy_staging) are an error naming both, while an identical original name keeps the documented override behaviour. That keeps docs/custom-tools.mdx:82 intact.

No separate issue needed for the MCP half; the examples above can go into the test already on this issue.

feiiiiii5 avatar Nov 13 '26 00:11 feiiiiii5

I prepared a documentation-only patch explaining the current normalization and override behavior, including namespace-boundary collisions, and how plugin authors can inspect active effective names:

https://github.com/1052326311/opencode/compare/5b131f5995a9f7fad458c59a7a5e39686237beb8...tool-name-guide

Seven cases exercise the real registry → model definitions → tool execution, with same-name override and distinct case/hyphen controls. Site generation/typecheck/build and the root 35-task check pass. This documents current behavior; it does not implement collision rejection or resolve this report.

PR creation is currently denied for my account, so the reviewable patch is on the fork.

1052326311 avatar Nov 13 '26 12:11 1052326311