Skip to content

Commit 4a4a175

Browse files
saravmajesticclaude
andcommitted
fix: [AI-6948] address PR review — preserve MCP config fields on disk writes
Resolves the review findings on the `/mcps` enable/disable persistence and datamate transport sync paths. - `mcp/config.ts`: `readMcpEntryFromDisk` now uses `getNodeValue` instead of a manual children walk. `jsonc-parser` only populates `Node.value` for primitives, so the old walk silently dropped `command` arrays and `environment`/`headers` objects — corrupting local stdio (and remote-with- headers) entries on the next write via `persistMcpEnabled`. - `altimate/datamate-transport.ts`: same `getNodeValue` fix for the two sibling walkers; preserve non-transport fields (`enabled`, `timeout`, `oauth`, …) when rebuilding the synced datamate entry; widen the `**/mcp.json` ignore list (`target`, `.next`, `out`, `vendor`, `coverage`, `.venv`, `.turbo`). - `mcp/index.ts`: serialize `persistMcpEnabled` (promise chain) so concurrent enable/disable can't interleave read-modify-write and clobber each other. - `server/server.ts`: `reload-datamate` returns HTTP 500 (not 200) on error so the extension can distinguish failure. - `session/prompt.ts`: `/mcps enable|disable` validates the server name against config and reports clearly when it's unknown (was silent). - `test/mcp/config.test.ts`: add `readMcpEntryFromDisk` round-trip tests, including the persist-enabled flow that previously corrupted local entries. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 parent b5d5df8 commit 4a4a175

6 files changed

Lines changed: 143 additions & 34 deletions

File tree

‎packages/opencode/src/altimate/datamate-transport.ts‎

Lines changed: 49 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { readFile } from "fs/promises"
22
import path from "path"
3-
import { parseTree, findNodeAtLocation } from "jsonc-parser"
3+
import { parseTree, findNodeAtLocation, getNodeValue } from "jsonc-parser"
44
import { resolveConfigPath, addMcpToConfig, readMcpEntryFromDisk } from "../mcp/config"
55
import { Filesystem } from "../util/filesystem"
66
import { Glob } from "../util/glob"
@@ -49,7 +49,23 @@ async function findAllMcpJsonFiles(projectRootDir: string): Promise<string[]> {
4949
cwd: projectRootDir,
5050
absolute: true,
5151
dot: true,
52-
ignore: ["**/node_modules/**", "**/.git/**", "**/dist/**", "**/build/**", "**/.pnpm/**"],
52+
// Exclude build/dependency/output trees. command + args from a discovered
53+
// mcp.json are passed to StdioClientTransport, so keep the scan to source the
54+
// user actually authors and out of vendored/generated directories.
55+
ignore: [
56+
"**/node_modules/**",
57+
"**/.git/**",
58+
"**/dist/**",
59+
"**/build/**",
60+
"**/.pnpm/**",
61+
"**/target/**",
62+
"**/.next/**",
63+
"**/out/**",
64+
"**/vendor/**",
65+
"**/coverage/**",
66+
"**/.venv/**",
67+
"**/.turbo/**",
68+
],
5369
})
5470
return paths.sort()
5571
} catch {
@@ -170,25 +186,38 @@ export async function syncDatamateUrlFromVscodeMcp(cwd: string): Promise<string[
170186
: undefined
171187

172188
if (existingNode) {
173-
let existingUpdatedAt: string | undefined
174-
let existingEnabled: boolean | undefined
175-
if (existingNode.type === "object" && existingNode.children) {
176-
for (const prop of existingNode.children) {
177-
if (prop.type !== "property" || !prop.children) continue
178-
const k = prop.children[0]!.value as string
179-
if (k === "updatedAt") existingUpdatedAt = prop.children[1]!.value as string
180-
if (k === "enabled") existingEnabled = prop.children[1]!.value as boolean
181-
}
182-
}
189+
// getNodeValue reconstructs the full entry (a manual children walk reading
190+
// `prop.children[1].value` drops array/object fields — jsonc-parser only
191+
// populates `Node.value` for primitives).
192+
const existingEntry =
193+
existingNode.type === "object"
194+
? (getNodeValue(existingNode) as Record<string, unknown>)
195+
: {}
196+
const existingUpdatedAt =
197+
typeof existingEntry["updatedAt"] === "string" ? existingEntry["updatedAt"] : undefined
183198

184199
if (vscodeUpdatedAt === existingUpdatedAt) {
185200
log.info("syncDatamateUrlFromVscodeMcp: datamate entry already up to date", {
186201
updatedAt: vscodeUpdatedAt,
187202
})
188203
} else {
189-
// Build the new config entry in altimate-code.json format.
190-
// IDE config uses "stdio"/"http"/"streamable-http"/"sse";
204+
// Preserve fields the IDE doesn't manage (enabled, timeout, oauth, …) by
205+
// carrying forward everything except the transport-identity fields, which
206+
// we re-derive below. IDE config uses "stdio"/"http"/"streamable-http"/"sse";
191207
// altimate-code.json uses "local"/"remote".
208+
const TRANSPORT_FIELDS = new Set([
209+
"type",
210+
"command",
211+
"args",
212+
"environment",
213+
"url",
214+
"updatedAt",
215+
])
216+
const preserved: Record<string, unknown> = {}
217+
for (const [k, v] of Object.entries(existingEntry)) {
218+
if (!TRANSPORT_FIELDS.has(k)) preserved[k] = v
219+
}
220+
192221
let newEntry: Record<string, unknown>
193222
if ("command" in datamateVscode) {
194223
const env = datamateVscode["env"] as Record<string, string> | undefined
@@ -198,6 +227,7 @@ export async function syncDatamateUrlFromVscodeMcp(cwd: string): Promise<string[
198227
? (datamateVscode["command"] as string)
199228
: DATAMATE_KEY
200229
newEntry = {
230+
...preserved,
201231
type: "local",
202232
command: [cmd, ...((datamateVscode["args"] as string[]) ?? [])],
203233
...(Object.keys(restEnv).length > 0 ? { environment: restEnv } : {}),
@@ -206,12 +236,12 @@ export async function syncDatamateUrlFromVscodeMcp(cwd: string): Promise<string[
206236
} else {
207237
// http / streamable-http / sse → remote
208238
newEntry = {
239+
...preserved,
209240
type: "remote",
210241
url: datamateVscode["url"] as string,
211242
updatedAt: vscodeUpdatedAt,
212243
}
213244
}
214-
if (typeof existingEnabled === "boolean") newEntry["enabled"] = existingEnabled
215245

216246
await addMcpToConfig(
217247
DATAMATE_KEY,
@@ -262,13 +292,10 @@ export async function syncDatamateUrlFromVscodeMcp(cwd: string): Promise<string[
262292
const match = httpEntries.find((e) => e.key === remote.name)
263293
if (match && match.url !== remote.url) {
264294
const entryNode = findNodeAtLocation(tree, ["mcp", remote.name])
265-
if (!entryNode || entryNode.type !== "object" || !entryNode.children) continue
266-
const entry: Record<string, unknown> = {}
267-
for (const prop of entryNode.children) {
268-
if (prop.type === "property" && prop.children) {
269-
entry[prop.children[0]!.value as string] = prop.children[1]!.value
270-
}
271-
}
295+
if (!entryNode || entryNode.type !== "object") continue
296+
// getNodeValue preserves headers/oauth/timeout; a children walk reading
297+
// `prop.children[1].value` would strip them (object/array nodes).
298+
const entry = getNodeValue(entryNode) as Record<string, unknown>
272299
entry["url"] = match.url
273300
entry["updatedAt"] = new Date().toISOString()
274301
await addMcpToConfig(

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

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import path from "path"
2-
import { modify, applyEdits, parseTree, findNodeAtLocation } from "jsonc-parser"
2+
import { modify, applyEdits, parseTree, findNodeAtLocation, getNodeValue } from "jsonc-parser"
33
import { Filesystem } from "../util/filesystem"
44
import type { Config } from "../config/config"
55

@@ -118,14 +118,11 @@ export async function readMcpEntryFromDisk(
118118
if (!tree) return undefined
119119

120120
const node = findNodeAtLocation(tree, ["mcp", name])
121-
if (!node || node.type !== "object" || !node.children) return undefined
121+
if (!node || node.type !== "object") return undefined
122122

123-
const entry: Record<string, unknown> = {}
124-
for (const prop of node.children) {
125-
if (prop.type === "property" && prop.children) {
126-
entry[prop.children[0]!.value as string] = prop.children[1]!.value
127-
}
128-
}
129-
130-
return entry as Config.Mcp
123+
// getNodeValue reconstructs the full value tree. A manual children walk reading
124+
// `prop.children[1].value` would silently drop array/object fields (command,
125+
// environment, headers, oauth) — jsonc-parser only populates `Node.value` for
126+
// primitives — corrupting the entry on the next disk write.
127+
return getNodeValue(node) as Config.Mcp
131128
}

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,16 @@ export namespace MCP {
699699
}
700700

701701
// altimate_change start — persist enabled/disabled to disk so it survives session restarts
702-
async function persistMcpEnabled(name: string, enabled: boolean): Promise<void> {
702+
// Serialize all writes: persistMcpEnabled is read-modify-write on a shared config
703+
// file, so concurrent callers (e.g. rapid /mcps enable then disable) could otherwise
704+
// interleave and clobber each other's changes.
705+
let persistChain: Promise<void> = Promise.resolve()
706+
function persistMcpEnabled(name: string, enabled: boolean): Promise<void> {
707+
const run = persistChain.then(() => persistMcpEnabledUnlocked(name, enabled))
708+
persistChain = run.catch(() => {})
709+
return run
710+
}
711+
async function persistMcpEnabledUnlocked(name: string, enabled: boolean): Promise<void> {
703712
try {
704713
const paths = await findAllConfigPaths(Instance.directory, Global.Path.config)
705714
let found = false

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ export namespace Server {
619619
} catch (err) {
620620
const error = err instanceof Error ? err.message : String(err)
621621
log.error("reload-datamate: failed", { error })
622-
return c.json({ ok: false, error })
622+
return c.json({ ok: false, error }, 500)
623623
}
624624
})
625625
// altimate_change end

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2653,6 +2653,19 @@ NOTE: At any point in time through this workflow you should feel free to ask the
26532653
})
26542654

26552655
const model = await lastModel(input.sessionID)
2656+
// MCP.connect/disconnect on an unknown name logs and returns silently, so
2657+
// validate against config first and give the user a clear signal on a typo.
2658+
const cfg = await Config.get()
2659+
if (!cfg.mcp?.[name]) {
2660+
const known = Object.keys(cfg.mcp ?? {})
2661+
const suffix = known.length ? ` Known servers: ${known.join(", ")}.` : ""
2662+
return respond(
2663+
userMsg.info.id,
2664+
`MCP server **${name}** not found in config.${suffix}`,
2665+
model,
2666+
)
2667+
}
2668+
26562669
let responseText: string
26572670

26582671
if (isEnable) {

‎packages/opencode/test/mcp/config.test.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
removeMcpFromConfig,
99
listMcpInConfig,
1010
findAllConfigPaths,
11+
readMcpEntryFromDisk,
1112
} from "../../src/mcp/config"
1213

1314
describe("MCP config: resolveConfigPath", () => {
@@ -99,6 +100,68 @@ describe("MCP config: addMcpToConfig + removeMcpFromConfig round-trip", () => {
99100
})
100101
})
101102

103+
describe("MCP config: readMcpEntryFromDisk round-trip", () => {
104+
test("preserves command array and environment object for local entries", async () => {
105+
await using tmp = await tmpdir()
106+
const configPath = path.join(tmp.path, "opencode.json")
107+
const local = {
108+
type: "local",
109+
command: ["node", "/path/to/datamate", "start-stdio"],
110+
environment: { DATAMATE_KEY: "abc" },
111+
enabled: false,
112+
}
113+
await addMcpToConfig("datamate", local as any, configPath)
114+
const entry = await readMcpEntryFromDisk("datamate", configPath)
115+
expect(entry).toEqual(local as any)
116+
})
117+
118+
test("preserves headers object for remote entries", async () => {
119+
await using tmp = await tmpdir()
120+
const configPath = path.join(tmp.path, "opencode.json")
121+
const remote = {
122+
type: "remote",
123+
url: "https://example.com/mcp",
124+
headers: { Authorization: "Bearer xyz" },
125+
enabled: true,
126+
}
127+
await addMcpToConfig("knowledge", remote as any, configPath)
128+
const entry = await readMcpEntryFromDisk("knowledge", configPath)
129+
expect(entry).toEqual(remote as any)
130+
})
131+
132+
test("persist-enabled flow does not corrupt local command/environment", async () => {
133+
// Mirrors persistMcpEnabled: read entry from disk, then write back {...entry, enabled}.
134+
// A node-walker that drops array/object fields would strip command + environment here.
135+
await using tmp = await tmpdir()
136+
const configPath = path.join(tmp.path, "opencode.json")
137+
await addMcpToConfig(
138+
"datamate",
139+
{ type: "local", command: ["node", "/p"], environment: { K: "v" }, enabled: false } as any,
140+
configPath,
141+
)
142+
143+
const entry = await readMcpEntryFromDisk("datamate", configPath)
144+
expect(entry).toBeDefined()
145+
await addMcpToConfig("datamate", { ...(entry as any), enabled: true }, configPath)
146+
147+
const after = await readMcpEntryFromDisk("datamate", configPath)
148+
expect(after).toEqual({
149+
type: "local",
150+
command: ["node", "/p"],
151+
environment: { K: "v" },
152+
enabled: true,
153+
} as any)
154+
})
155+
156+
test("returns undefined for missing file or unknown name", async () => {
157+
await using tmp = await tmpdir()
158+
const configPath = path.join(tmp.path, "opencode.json")
159+
expect(await readMcpEntryFromDisk("x", path.join(tmp.path, "missing.json"))).toBeUndefined()
160+
await writeFile(configPath, JSON.stringify({ mcp: { a: { type: "local", command: ["x"] } } }))
161+
expect(await readMcpEntryFromDisk("nope", configPath)).toBeUndefined()
162+
})
163+
})
164+
102165
describe("MCP config: listMcpInConfig", () => {
103166
test("returns empty array for missing file", async () => {
104167
await using tmp = await tmpdir()

0 commit comments

Comments
 (0)