Skip to content

Commit 169423f

Browse files
EBrownclaude
andcommitted
fix: resolve 4 bugs — payload bloat, MCP subagents, tool names, token counting
- anomalyco#14543: Cap diagnostics stored in tool metadata to errors-only (max 10/file). Strip full before/after file content from edit/apply_patch metadata — UI only uses diffs. Prevents 780MB+ JSON payloads. - anomalyco#16491: MCP tools now available in subagent sessions. task.ts passes MCP tool names as allow permissions and explicitly enables them in the tools map. llm.ts lets explicitly-enabled tools bypass agent-level deny rules. - anomalyco#3523: MCP tool names truncated to 64 chars (OpenAI API limit). Uses smart truncation: keeps tool name intact, truncates server prefix, appends FNV hash suffix for uniqueness. - anomalyco#3314: Token counting unified across all providers. Always computes total from adjusted components instead of trusting provider-reported totalTokens, which caused 2x inflation for OpenRouter/Copilot. Co-Authored-By: Claude Opus 4.6 <[email protected]>
1 parent d7ce0ed commit 169423f

7 files changed

Lines changed: 90 additions & 26 deletions

File tree

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

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,58 @@ export namespace MCP {
600600
s.status[name] = { status: "disabled" }
601601
}
602602

603+
// OpenAI API enforces a 64-character limit on tool names.
604+
const MAX_TOOL_NAME_LENGTH = 64
605+
606+
/**
607+
* Build a combined MCP tool name that fits within MAX_TOOL_NAME_LENGTH.
608+
*
609+
* Strategy:
610+
* 1. If "server_tool" fits, use it as-is.
611+
* 2. Otherwise, truncate the server name portion to make room, keeping
612+
* the tool name intact (it carries more semantic meaning).
613+
* 3. If the tool name alone already exceeds the limit, truncate the
614+
* tool name and omit the server prefix entirely.
615+
* 4. Append a short hash suffix when any truncation occurs so that
616+
* distinct original names remain unique after truncation.
617+
*/
618+
function buildToolName(sanitizedServer: string, sanitizedTool: string): string {
619+
const separator = "_"
620+
const combined = sanitizedServer + separator + sanitizedTool
621+
622+
if (combined.length <= MAX_TOOL_NAME_LENGTH) {
623+
return combined
624+
}
625+
626+
// We need to truncate. Generate a 6-char hex hash of the full
627+
// (pre-truncation) combined name to preserve uniqueness.
628+
const hashSuffix = separator + shortHash(combined)
629+
630+
// Try to keep the full tool name and truncate the server portion.
631+
// Budget: MAX - toolName - separator - hashSuffix
632+
const serverBudget = MAX_TOOL_NAME_LENGTH - sanitizedTool.length - separator.length - hashSuffix.length
633+
if (serverBudget >= 1) {
634+
return sanitizedServer.slice(0, serverBudget) + separator + sanitizedTool + hashSuffix
635+
}
636+
637+
// Tool name alone is too long (with hash). Drop server prefix entirely.
638+
const toolBudget = MAX_TOOL_NAME_LENGTH - hashSuffix.length
639+
return sanitizedTool.slice(0, toolBudget) + hashSuffix
640+
}
641+
642+
/**
643+
* Produce a short deterministic hex hash (6 chars) from an input string.
644+
* Uses a simple FNV-1a–style hash; no crypto overhead needed.
645+
*/
646+
function shortHash(input: string): string {
647+
let h = 0x811c9dc5 // FNV offset basis
648+
for (let i = 0; i < input.length; i++) {
649+
h ^= input.charCodeAt(i)
650+
h = (h * 0x01000193) | 0 // FNV prime, keep 32-bit
651+
}
652+
return (h >>> 0).toString(16).padStart(8, "0").slice(0, 6)
653+
}
654+
603655
export async function tools() {
604656
const result: Record<string, Tool> = {}
605657
const s = await state()
@@ -636,7 +688,8 @@ export namespace MCP {
636688
for (const mcpTool of toolsResult.tools) {
637689
const sanitizedClientName = clientName.replace(/[^a-zA-Z0-9_-]/g, "_")
638690
const sanitizedToolName = mcpTool.name.replace(/[^a-zA-Z0-9_-]/g, "_")
639-
result[sanitizedClientName + "_" + sanitizedToolName] = await convertMcpTool(mcpTool, client, timeout)
691+
const toolName = buildToolName(sanitizedClientName, sanitizedToolName)
692+
result[toolName] = await convertMcpTool(mcpTool, client, timeout)
640693
}
641694
}
642695
return result

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

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ import type { Provider } from "@/provider/provider"
2828
import { PermissionNext } from "@/permission/next"
2929
import { Global } from "@/global"
3030
import type { LanguageModelV2Usage } from "@ai-sdk/provider"
31-
import { iife } from "@/util/iife"
3231

3332
export namespace Session {
3433
const log = Log.create({ service: "session" })
@@ -815,18 +814,11 @@ export namespace Session {
815814
excludesCachedTokens ? inputTokens : inputTokens - cacheReadInputTokens - cacheWriteInputTokens,
816815
)
817816

818-
const total = iife(() => {
819-
// Anthropic doesn't provide total_tokens, also ai sdk will vastly undercount if we
820-
// don't compute from components
821-
if (
822-
input.model.api.npm === "@ai-sdk/anthropic" ||
823-
input.model.api.npm === "@ai-sdk/amazon-bedrock" ||
824-
input.model.api.npm === "@ai-sdk/google-vertex/anthropic"
825-
) {
826-
return adjustedInputTokens + outputTokens + cacheReadInputTokens + cacheWriteInputTokens
827-
}
828-
return input.usage.totalTokens
829-
})
817+
// Always compute total from adjusted components to avoid semantic
818+
// mismatches across providers. Some providers (OpenRouter, Copilot)
819+
// include cached tokens in totalTokens differently than Anthropic,
820+
// causing inflated counts and premature compaction (#3314).
821+
const total = adjustedInputTokens + outputTokens + reasoningTokens + cacheReadInputTokens + cacheWriteInputTokens
830822

831823
const tokens = {
832824
total,

‎packages/opencode/src/session/llm.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,11 @@ export namespace LLM {
258258
async function resolveTools(input: Pick<StreamInput, "tools" | "agent" | "user">) {
259259
const disabled = PermissionNext.disabled(Object.keys(input.tools), input.agent.permission)
260260
for (const tool of Object.keys(input.tools)) {
261-
if (input.user.tools?.[tool] === false || disabled.has(tool)) {
261+
// Explicitly enabled tools (e.g. MCP tools granted to subagents) bypass
262+
// the agent-level disabled check so they remain available even when the
263+
// agent's default permission is "deny *".
264+
const explicitlyEnabled = input.user.tools?.[tool] === true
265+
if (input.user.tools?.[tool] === false || (disabled.has(tool) && !explicitlyEnabled)) {
262266
delete input.tools[tool]
263267
}
264268
}

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import { Instance } from "../project/instance"
88
import { Patch } from "../patch"
99
import { createTwoFilesPatch, diffLines } from "diff"
1010
import { assertExternalDirectory } from "./external-directory"
11-
import { trimDiff } from "./edit"
11+
import { trimDiff, capDiagnostics } from "./edit"
1212
import { LSP } from "../lsp"
1313
import { Filesystem } from "../util/filesystem"
1414
import DESCRIPTION from "./apply_patch.txt"
@@ -165,8 +165,6 @@ export const ApplyPatchTool = Tool.define("apply_patch", {
165165
relativePath: path.relative(Instance.worktree, change.movePath ?? change.filePath).replaceAll("\\", "/"),
166166
type: change.type,
167167
diff: change.diff,
168-
before: change.oldContent,
169-
after: change.newContent,
170168
additions: change.additions,
171169
deletions: change.deletions,
172170
movePath: change.movePath,
@@ -287,7 +285,7 @@ export const ApplyPatchTool = Tool.define("apply_patch", {
287285
metadata: {
288286
diff: totalDiff,
289287
files,
290-
diagnostics,
288+
diagnostics: capDiagnostics(diagnostics),
291289
},
292290
output,
293291
}

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

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,22 @@ import { Bus } from "../bus"
1515
import { FileTime } from "../file/time"
1616
import { Filesystem } from "../util/filesystem"
1717
import { Instance } from "../project/instance"
18-
import { Snapshot } from "@/snapshot"
1918
import { assertExternalDirectory } from "./external-directory"
2019
import { Graph } from "../graph"
2120
import { GraphParser } from "../graph/parser"
2221
import { Changelog } from "../session/changelog"
2322

2423
const MAX_DIAGNOSTICS_PER_FILE = 20
24+
const MAX_DIAGNOSTICS_IN_METADATA = 10
25+
26+
export function capDiagnostics(diagnostics: Record<string, any[]>): Record<string, any[]> {
27+
const result: Record<string, any[]> = {}
28+
for (const [file, issues] of Object.entries(diagnostics)) {
29+
const errors = issues.filter((d) => d.severity === 1).slice(0, MAX_DIAGNOSTICS_IN_METADATA)
30+
if (errors.length > 0) result[file] = errors
31+
}
32+
return result
33+
}
2534

2635
function normalizeLineEndings(text: string): string {
2736
return text.replaceAll("\r\n", "\n")
@@ -125,10 +134,8 @@ export const EditTool = Tool.define("edit", {
125134
FileTime.read(ctx.sessionID, filePath)
126135
})
127136

128-
const filediff: Snapshot.FileDiff = {
137+
const filediff = {
129138
file: filePath,
130-
before: contentOld,
131-
after: contentNew,
132139
additions: 0,
133140
deletions: 0,
134141
}
@@ -195,7 +202,7 @@ export const EditTool = Tool.define("edit", {
195202

196203
return {
197204
metadata: {
198-
diagnostics,
205+
diagnostics: capDiagnostics(diagnostics),
199206
diff,
200207
filediff,
201208
},

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { iife } from "@/util/iife"
1010
import { defer } from "@/util/defer"
1111
import { Config } from "../config/config"
1212
import { PermissionNext } from "@/permission/next"
13+
import { MCP } from "../mcp"
1314

1415
const parameters = z.object({
1516
description: z.string().describe("A short (3-5 words) description of the task"),
@@ -63,6 +64,9 @@ export const TaskTool = Tool.define("task", async (ctx) => {
6364

6465
const hasTaskPermission = agent.permission.some((rule) => rule.permission === "task")
6566

67+
// Collect MCP tool names so subagents can use them
68+
const mcpToolNames = Object.keys(await MCP.tools())
69+
6670
const session = await iife(async () => {
6771
if (params.task_id) {
6872
const found = await Session.get(params.task_id).catch(() => {})
@@ -97,6 +101,11 @@ export const TaskTool = Tool.define("task", async (ctx) => {
97101
action: "allow" as const,
98102
permission: t,
99103
})) ?? []),
104+
...mcpToolNames.map((t) => ({
105+
pattern: "*" as const,
106+
action: "allow" as const,
107+
permission: t,
108+
})),
100109
],
101110
})
102111
})
@@ -138,6 +147,7 @@ export const TaskTool = Tool.define("task", async (ctx) => {
138147
todoread: false,
139148
...(hasTaskPermission ? {} : { task: false }),
140149
...Object.fromEntries((config.experimental?.primary_tools ?? []).map((t) => [t, false])),
150+
...Object.fromEntries(mcpToolNames.map((t) => [t, true])),
141151
},
142152
parts: promptParts,
143153
})

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { FileWatcher } from "../file/watcher"
1010
import { FileTime } from "../file/time"
1111
import { Filesystem } from "../util/filesystem"
1212
import { Instance } from "../project/instance"
13-
import { trimDiff } from "./edit"
13+
import { trimDiff, capDiagnostics } from "./edit"
1414
import { assertExternalDirectory } from "./external-directory"
1515
import { Changelog } from "../session/changelog"
1616

@@ -87,7 +87,7 @@ export const WriteTool = Tool.define("write", {
8787
return {
8888
title: path.relative(Instance.worktree, filepath),
8989
metadata: {
90-
diagnostics,
90+
diagnostics: capDiagnostics(diagnostics),
9191
filepath,
9292
exists: exists,
9393
},

0 commit comments

Comments
 (0)