Skip to content

Commit e65cfa5

Browse files
anandgupta42claude
andcommitted
fix: MCP review findings: config limits, CLI flags, scratch writes, markers, CI
- `outputLimits` uses `ConfigPaths` and `env()` like the agent loader - `--log-level`, `--integrations`, `--pure` apply to `mcp serve` - scratch writes skip `forceReadOnly` - `readOnlyCaveat` tolerates a non-string type - no nested markers in `truncate.ts`; CI runs MCP E2E for exposed tools - stdio tests use an entry wrapper so the guard runs Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 0e0b21e commit e65cfa5

10 files changed

Lines changed: 254 additions & 40 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,14 @@ jobs:
9292
- 'packages/opencode/test/altimate/mcp-server/**'
9393
- 'packages/opencode/src/altimate/tools/schema-inspect.ts'
9494
- 'packages/opencode/src/altimate/tools/schema-values.ts'
95+
# The tools the MCP server exposes; server.test.ts is their only real-driver run.
96+
- 'packages/opencode/src/altimate/tools/warehouse-list.ts'
97+
- 'packages/opencode/src/altimate/tools/warehouse-add.ts'
98+
- 'packages/opencode/src/altimate/tools/sql-execute.ts'
99+
- 'packages/opencode/src/altimate/tools/sql-check.ts'
100+
- 'packages/opencode/src/altimate/tools/sql-materialize.ts'
101+
- 'packages/opencode/src/altimate/tools/answer-commit*.ts'
102+
- 'packages/opencode/src/tool/truncate.ts'
95103
# altimate_change end
96104
- 'packages/drivers/src/**'
97105
- 'packages/opencode/src/altimate/native/connections/**'
Lines changed: 49 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,74 @@
11
import { readFile } from "node:fs/promises"
22
import path from "node:path"
3+
import { Effect } from "effect"
34
import { parse } from "jsonc-parser"
5+
import { Flag, env } from "@opencode-ai/core/flag/flag"
6+
import { FSUtil } from "@opencode-ai/core/fs-util"
47
import { Global } from "@/global"
8+
import { ConfigPaths } from "@/config/paths"
9+
import { git } from "@/util/git"
510
import { MAX_LINES, MAX_BYTES } from "@/tool/truncate-core"
611

7-
// Read only output settings: loading the full agent config can install dependencies
8-
// or fetch remote configuration, neither of which belongs in this standalone server.
12+
/** The project's git worktree root, as the agent's Instance resolves it (`Project.fromDirectory`). */
13+
async function projectWorktree(directory: string): Promise<string> {
14+
const dotgit = await Effect.runPromise(
15+
Effect.gen(function* () {
16+
return yield* (yield* FSUtil.Service).up({ targets: [".git"], start: directory })
17+
}).pipe(
18+
Effect.provide(FSUtil.defaultLayer),
19+
Effect.orElseSucceed(() => [] as string[]),
20+
),
21+
)
22+
if (!dotgit[0]) return "/"
23+
const sandbox = path.dirname(dotgit[0])
24+
const result = await git(["rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: sandbox })
25+
const common = result.exitCode === 0 ? result.text().replace(/[\r\n]+$/, "") : ""
26+
if (!common) return sandbox
27+
const resolved = path.resolve(sandbox, common)
28+
return resolved === sandbox ? sandbox : path.dirname(resolved)
29+
}
30+
31+
/**
32+
* Read only output settings: loading the full agent config can install dependencies or fetch remote
33+
* configuration, neither of which belongs in this standalone server. The files, their order and the
34+
* `ALTIMATE_CLI_*` / `OPENCODE_*` variables are the agent loader's (`config/config.ts`), through the
35+
* same `ConfigPaths` and `Flag` helpers, so one config resolves to the same limits in both.
36+
*/
937
export async function outputLimits() {
38+
const directory = process.cwd()
1039
const limits = { maxLines: MAX_LINES, maxBytes: MAX_BYTES }
1140
const apply = (text: string) => {
1241
const output = parse(text)?.tool_output
1342
if (Number.isInteger(output?.max_lines) && output.max_lines > 0) limits.maxLines = output.max_lines
1443
if (Number.isInteger(output?.max_bytes) && output.max_bytes > 0) limits.maxBytes = output.max_bytes
1544
}
45+
// A missing or unreadable file contributes nothing; output limits never stop the server from starting.
1646
const load = async (file: string) => {
17-
const text = await readFile(file, "utf8").catch((error) => {
18-
if (error.code === "ENOENT") return undefined
19-
throw error
20-
})
47+
const text = await readFile(file, "utf8").catch(() => undefined)
2148
if (text) apply(text)
2249
}
50+
const worktree = await projectWorktree(directory)
51+
const discover = <A>(effect: Effect.Effect<A, unknown, FSUtil.Service>, fallback: A) =>
52+
Effect.runPromise(effect.pipe(Effect.provide(FSUtil.defaultLayer), Effect.orElseSucceed(() => fallback)))
53+
2354
for (const name of ["config.json", "opencode.json", "opencode.jsonc", "altimate-code.json", "altimate-code.jsonc"]) {
2455
await load(path.join(Global.Path.config, name))
2556
}
26-
if (process.env.OPENCODE_CONFIG) await load(process.env.OPENCODE_CONFIG)
27-
if (process.env.OPENCODE_DISABLE_PROJECT_CONFIG !== "1" && process.env.OPENCODE_DISABLE_PROJECT_CONFIG !== "true") {
28-
const ancestors = []
29-
for (let directory = process.cwd(); ; directory = path.dirname(directory)) {
30-
ancestors.unshift(directory)
31-
if (directory === path.dirname(directory)) break
32-
}
33-
for (const directory of ancestors) {
34-
for (const base of [directory, path.join(directory, ".opencode"), path.join(directory, ".altimate-code")]) {
35-
for (const name of ["opencode.jsonc", "opencode.json", "altimate-code.jsonc", "altimate-code.json"]) {
36-
await load(path.join(base, name))
37-
}
38-
}
57+
const custom = env("OPENCODE_CONFIG")
58+
if (custom) await load(custom)
59+
if (!Flag.OPENCODE_DISABLE_PROJECT_CONFIG) {
60+
for (const file of await discover(ConfigPaths.files("opencode", directory, worktree), [] as string[])) {
61+
await load(file)
3962
}
4063
}
41-
if (process.env.OPENCODE_CONFIG_DIR) {
42-
for (const name of ["opencode.jsonc", "opencode.json", "altimate-code.jsonc", "altimate-code.json"]) {
43-
await load(path.join(process.env.OPENCODE_CONFIG_DIR, name))
64+
const configDir = Flag.OPENCODE_CONFIG_DIR
65+
for (const dir of await discover(ConfigPaths.directories(directory, worktree), [] as string[])) {
66+
if (!dir.endsWith(".altimate-code") && !dir.endsWith(".opencode") && dir !== configDir) continue
67+
for (const name of ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"]) {
68+
await load(path.join(dir, name))
4469
}
4570
}
46-
if (process.env.OPENCODE_CONFIG_CONTENT) apply(process.env.OPENCODE_CONFIG_CONTENT)
71+
const content = env("OPENCODE_CONFIG_CONTENT")
72+
if (content) apply(content)
4773
return limits
4874
}
Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
/** Drivers that enforce ExecuteOptions.readOnly at the database boundary. */
22
const ENFORCED = new Set(["postgres", "postgresql", "sqlite", "duckdb"])
33

4-
export function readOnlyCaveat(connection: { name: string; type: string }): string | undefined {
5-
if (ENFORCED.has(connection.type.toLowerCase())) return undefined
4+
/**
5+
* The caveat for a connection whose driver does not enforce read-only. A malformed connection without a string
6+
* type has no driver to caveat (it cannot connect), so it gets none rather than crashing the caller.
7+
*/
8+
export function readOnlyCaveat(connection: { name: string; type?: unknown }): string | undefined {
9+
if (typeof connection.type !== "string" || ENFORCED.has(connection.type.toLowerCase())) return undefined
610
return `${connection.name} (${connection.type}): read-only is enforced by SQL classification only; stored functions with side effects are not blocked — use a read-only database user`
711
}

‎packages/opencode/src/altimate/tools/sql-execute.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,15 @@ export const SqlExecuteTool = Tool.define(
320320
limit: Math.max(limit, budget?.minRows ?? 0),
321321
query_timeout_ms: args.query_timeout_ms,
322322
...(readOnly ? { read_only: true } : {}),
323-
}, { signal: ctx.abort, sessionID: ctx.sessionID, ...(ctx.extra?.forceReadOnly === true ? { forceReadOnly: true } : {}) })
323+
}, {
324+
signal: ctx.abort,
325+
sessionID: ctx.sessionID,
326+
// forceReadOnly protects source connections; the session's own scratch tables take the
327+
// same table writes here that need no write permission above.
328+
...(ctx.extra?.forceReadOnly === true && !(queryType === "write" && isScratch(args.warehouse) && isScratchSafeWrite(sql))
329+
? { forceReadOnly: true }
330+
: {}),
331+
})
324332

325333
// altimate_change start — a failure must not be rendered as "(0 rows)".
326334
// sql.execute never throws: it catches every connection and query error

‎packages/opencode/src/index.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -137,16 +137,19 @@ let cli = yargs(args)
137137
.middleware(async (opts) => {
138138
if (opts.printLogs) process.env.OPENCODE_PRINT_LOGS = "1"
139139
if (opts.logLevel) process.env.OPENCODE_LOG_LEVEL = opts.logLevel
140-
// altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization
141-
if (opts._[0] === "mcp" && opts._[1] === "serve") return
140+
// altimate_change start — the altimate log shim read its level when it was imported, before this ran
141+
if (opts.logLevel) AltimateLog.setLevel(opts.logLevel as AltimateLog.Level)
142+
// altimate_change end
143+
// altimate_change start - workspace precedence escape hatch. Process-wide, not
144+
// per session: an env var inherited by child processes, and under `serve` (and
145+
// `mcp serve`) it covers every session that process hosts.
146+
if (opts.integrations) process.env.ALTIMATE_INTEGRATIONS = String(opts.integrations)
142147
// altimate_change end
143148
if (opts.pure) {
144149
process.env.OPENCODE_PURE = "1"
145150
}
146-
// altimate_change start - workspace precedence escape hatch. Process-wide, not
147-
// per session: an env var inherited by child processes, and under `serve` it
148-
// covers every session that process hosts.
149-
if (opts.integrations) process.env.ALTIMATE_INTEGRATIONS = String(opts.integrations)
151+
// altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization
152+
if (opts._[0] === "mcp" && opts._[1] === "serve") return
150153
// altimate_change end
151154

152155
Heap.start()

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

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export interface Interface {
5454

5555
export class Service extends Context.Service<Service, Interface>()("@opencode/Truncate") {}
5656

57-
// altimate_change start — let standalone MCP sessions share output handling with private storage and neutral hints.
57+
// altimate_change start — standalone MCP sessions share output handling with private storage and neutral hints (inner notes are plain comments: markers do not nest); carries upstream_fix: age files by mtime, not decoded ID timestamps.
5858
export function makeLayer(
5959
options: {
6060
directory?: string
@@ -69,7 +69,7 @@ export function makeLayer(
6969
const fs = yield* FSUtil.Service
7070

7171
const cleanup = Effect.fn("Truncate.cleanup")(function* () {
72-
// altimate_change start — upstream_fix: age files by mtime, not decoded ID timestamps.
72+
// Age files by mtime, not decoded ID timestamps (upstream fix).
7373
// Identifier packs `timestamp * 4096` into 48 bits, which wraps every
7474
// 2^36 ms (~795 days) — the 26th wrap landed 2026-08-14T11:19:55Z, after
7575
// which every new ID decoded as "ancient" and cleanup deleted files the
@@ -89,7 +89,6 @@ export function makeLayer(
8989
if (mtimeMs >= cutoffMs) continue
9090
yield* fs.remove(file).pipe(Effect.catch(() => Effect.void))
9191
}
92-
// altimate_change end
9392
})
9493

9594
const write = Effect.fn("Truncate.write")(function* (text: string) {
@@ -110,7 +109,7 @@ export function makeLayer(
110109
}
111110
})
112111

113-
// altimate_change start — default direction "middle" (head+tail,
112+
// Default direction "middle" (head+tail,
114113
// tail-weighted elision) via the shared truncate-core.ts algorithm.
115114
const output = Effect.fn("Truncate.output")(function* (
116115
text: string,
@@ -146,7 +145,6 @@ export function makeLayer(
146145
outputPath: file,
147146
} as const
148147
})
149-
// altimate_change end
150148

151149
yield* cleanup().pipe(
152150
Effect.catchCause((cause) => Effect.logError("truncation cleanup failed", { cause: Cause.pretty(cause) })),
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// altimate_change start — MCP output limits resolve like the agent's config loader
2+
import { afterEach, beforeEach, expect, test } from "bun:test"
3+
import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"
4+
import os from "node:os"
5+
import path from "node:path"
6+
import { outputLimits } from "../../../src/altimate/mcp-server/output-settings"
7+
import { MAX_BYTES, MAX_LINES } from "../../../src/tool/truncate-core"
8+
9+
const VARS = [
10+
"OPENCODE_CONFIG",
11+
"OPENCODE_CONFIG_CONTENT",
12+
"OPENCODE_CONFIG_DIR",
13+
"OPENCODE_DISABLE_PROJECT_CONFIG",
14+
"ALTIMATE_CLI_CONFIG",
15+
"ALTIMATE_CLI_CONFIG_CONTENT",
16+
"ALTIMATE_CLI_CONFIG_DIR",
17+
"ALTIMATE_CLI_DISABLE_PROJECT_CONFIG",
18+
]
19+
let saved: Record<string, string | undefined>
20+
let root: string
21+
let repo: string
22+
let cwd: string
23+
24+
const output = (tool_output: Record<string, number>) => JSON.stringify({ tool_output })
25+
26+
beforeEach(async () => {
27+
cwd = process.cwd()
28+
saved = Object.fromEntries(VARS.map((name) => [name, process.env[name]]))
29+
for (const name of VARS) delete process.env[name]
30+
root = await realpath(await mkdtemp(path.join(os.tmpdir(), "mcp-output-settings-")))
31+
repo = path.join(root, "repo")
32+
await mkdir(path.join(repo, "sub"), { recursive: true })
33+
const init = Bun.spawnSync(["git", "init", "-q", repo])
34+
expect(init.exitCode).toBe(0)
35+
process.chdir(path.join(repo, "sub"))
36+
})
37+
38+
afterEach(async () => {
39+
process.chdir(cwd)
40+
for (const [name, value] of Object.entries(saved)) {
41+
if (value === undefined) delete process.env[name]
42+
else process.env[name] = value
43+
}
44+
await rm(root, { recursive: true, force: true })
45+
})
46+
47+
test("reads inline config through the documented ALTIMATE_CLI_CONFIG_CONTENT name", async () => {
48+
process.env.ALTIMATE_CLI_CONFIG_CONTENT = output({ max_lines: 3, max_bytes: 300 })
49+
expect(await outputLimits()).toEqual({ maxLines: 3, maxBytes: 300 })
50+
})
51+
52+
test("reads ALTIMATE_CLI_CONFIG and ALTIMATE_CLI_CONFIG_DIR", async () => {
53+
const custom = path.join(root, "custom.json")
54+
await writeFile(custom, output({ max_lines: 4 }))
55+
const dir = path.join(root, "config-dir")
56+
await mkdir(dir)
57+
await writeFile(path.join(dir, "opencode.json"), output({ max_bytes: 400 }))
58+
process.env.ALTIMATE_CLI_CONFIG = custom
59+
process.env.ALTIMATE_CLI_CONFIG_DIR = dir
60+
expect(await outputLimits()).toEqual({ maxLines: 4, maxBytes: 400 })
61+
})
62+
63+
test("stops at the git worktree and ignores altimate-code.* at the project root, as the agent does", async () => {
64+
await writeFile(path.join(root, "opencode.json"), output({ max_bytes: 999 }))
65+
await writeFile(path.join(repo, "altimate-code.json"), output({ max_lines: 9 }))
66+
await writeFile(path.join(repo, "opencode.json"), output({ max_lines: 5 }))
67+
expect(await outputLimits()).toEqual({ maxLines: 5, maxBytes: MAX_BYTES })
68+
})
69+
70+
test("opencode.jsonc overrides opencode.json in the same directory; .opencode/ applies after", async () => {
71+
await writeFile(path.join(repo, "opencode.json"), output({ max_lines: 5, max_bytes: 500 }))
72+
await writeFile(path.join(repo, "opencode.jsonc"), output({ max_lines: 6, max_bytes: 600 }))
73+
await mkdir(path.join(repo, ".opencode"))
74+
await writeFile(path.join(repo, ".opencode", "opencode.json"), output({ max_bytes: 700 }))
75+
expect(await outputLimits()).toEqual({ maxLines: 6, maxBytes: 700 })
76+
})
77+
78+
test("ALTIMATE_CLI_DISABLE_PROJECT_CONFIG skips project files", async () => {
79+
await writeFile(path.join(repo, "opencode.json"), output({ max_lines: 5 }))
80+
process.env.ALTIMATE_CLI_DISABLE_PROJECT_CONFIG = "1"
81+
expect(await outputLimits()).toEqual({ maxLines: MAX_LINES, maxBytes: MAX_BYTES })
82+
})
83+
84+
test("an unreadable config path does not stop startup", async () => {
85+
await mkdir(path.join(repo, "sub", "opencode.json"))
86+
await writeFile(path.join(repo, "opencode.jsonc"), output({ max_lines: 8 }))
87+
expect(await outputLimits()).toEqual({ maxLines: 8, maxBytes: MAX_BYTES })
88+
})
89+
// altimate_change end

‎packages/opencode/test/altimate/mcp-server/server.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,22 @@ mcpTest("materializes read-only sources into scratch, refuses source mutations",
212212
expect(denied.isError).toBe(true)
213213
})
214214

215+
mcpTest("scratch table writes run without --allow-write; source writes stay refused", async () => {
216+
const { call } = await fixture()
217+
for (const query of ["CREATE TABLE notes (n INTEGER)", "INSERT INTO notes VALUES (41)", "UPDATE notes SET n = n + 1"]) {
218+
const result = await call("sql_execute", { warehouse: "scratch", query })
219+
expect(result.isError, `${query}: ${text(result)}`).toBe(false)
220+
}
221+
expect(text(await call("sql_execute", { warehouse: "scratch", query: "SELECT n FROM notes" }))).toContain("42")
222+
expect((await call("sql_execute", { warehouse: "source", query: "INSERT INTO items VALUES (3, 'fig')" })).isError).toBe(true)
223+
})
224+
225+
mcpTest("a discovered connection without a string type does not stop startup", async () => {
226+
Registry.setConfigs({ broken: {} as never })
227+
const server = await createServer({})
228+
await server.close()
229+
})
230+
215231
mcpTest("MCP cancellation reaches the active tool abort signal", async () => {
216232
const { client } = await fixture()
217233
const started = Promise.withResolvers<AbortSignal>()

0 commit comments

Comments
 (0)