Skip to content

Commit d88dd20

Browse files
anandgupta42claude
andcommitted
fix(mcp): enforce source read-only queries and clean up server output
- Without `--allow-write`, every source query from the MCP tools requests database-enforced read-only where the engine supports it (Postgres read-only transaction, SQLite `query_only`, DuckDB read-only open). Engines without database-level read-only are still served, but `warehouse_list`, a stderr notice at start-up and the docs say plainly that stored functions with side effects are not blocked and a read-only database user is recommended. - Spill output goes to a private per-process directory that is removed when the server closes, through the shared truncation service (user output limits and failure wording preserved). - MCP-facing text names only the exposed tools: no `lineage_check` tip from `schema_inspect`, and client-neutral `full_text_columns` guidance. - `--connections` uses the registry's path resolution and rejects the reserved `scratch` name at start-up; docs state the file replaces discovery. `--print-logs`/`--log-level` now apply to `mcp serve`. - Tests: in-process MCP server tests need real drivers, so they run in a dedicated CI step (`ALTIMATE_MCP_E2E=1`); the allow-write read-back and middleware-skip regressions now fail when the behaviour regresses. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 7215ddd commit d88dd20

18 files changed

Lines changed: 577 additions & 207 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,14 @@ jobs:
512512
env:
513513
ALTIMATE_DUCKDB_E2E: "1"
514514

515+
# Same reason as above: the in-process MCP server tests use real SQLite/DuckDB drivers, which the
516+
# whole-package run replaces with module mocks, so they run in their own process.
517+
- name: Run MCP server tests (real drivers, no mocks)
518+
run: bun test --timeout 90000 test/altimate/mcp-server/server.test.ts
519+
working-directory: packages/opencode
520+
env:
521+
ALTIMATE_MCP_E2E: "1"
522+
515523
- name: Run Docker driver E2E (MySQL, SQL Server, Redshift)
516524
run: bun test test/altimate/drivers-docker-e2e.test.ts
517525
working-directory: packages/opencode

‎docs/docs/configure/mcp-servers.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,13 @@ The server exposes exactly `warehouse_list`, `schema_inspect`, `sql_execute`, `s
3131
}
3232
```
3333

34-
Relative database paths resolve beside this file. Omit `--connections` to use normal connection discovery: global and project `.altimate-code/connections.json` files, followed by `ALTIMATE_CODE_CONN_*` environment overrides. Set your client's working directory to the project when using project discovery.
34+
Relative database paths resolve beside this file. With `--connections`, this file is the only source of connections: global and project `connections.json` files and `ALTIMATE_CODE_CONN_*` overrides are ignored. Omit `--connections` to use normal connection discovery: global and project `.altimate-code/connections.json` files, followed by `ALTIMATE_CODE_CONN_*` environment overrides. Set your client's working directory to the project when using project discovery.
3535

36-
Source writes are refused by default. Add `--allow-write` to enable SQL write permissions; existing hard safety blocks still apply. `sql_materialize` always requires a read-only source query and writes only into the server session's temporary `scratch` warehouse. Scratch tables disappear when the server exits. Large results may include a local spill file path that your client can open with any file reader.
36+
<!-- altimate_change start — MCP read-only limits and private output lifecycle -->
37+
38+
Source writes are refused by default. Without `--allow-write`, source queries request database-enforced read-only execution on PostgreSQL, SQLite and DuckDB. For other connection types, read-only is enforced by SQL classification only; stored functions with side effects are not blocked — use a read-only database user. The server prints this caveat on stderr at startup and includes it in `warehouse_list` for each affected connection. Add `--allow-write` to enable SQL write permissions; existing hard safety blocks still apply. `sql_materialize` always requires a read-only source query and writes only into the server session's temporary `scratch` warehouse. Scratch tables disappear when the server exits. Large results may include a local spill file path that your client can open with any file reader. Spill files use a private directory and are deleted when the server exits. Local `tool_output.max_lines` and `tool_output.max_bytes` settings control output limits; remote agent configuration is not loaded.
39+
40+
<!-- altimate_change end -->
3741

3842
The server writes only MCP protocol messages to stdout and sends logs to stderr. It does not initialize telemetry and honors `ALTIMATE_TELEMETRY_DISABLED`.
3943

Lines changed: 70 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
import { FSUtil } from "@opencode-ai/core/fs-util"
2+
import { NodePath } from "@effect/platform-node"
13
import { Effect, Layer } from "effect"
2-
import { mkdir, writeFile } from "node:fs/promises"
4+
import { mkdtemp, chmod, rm } from "node:fs/promises"
35
import { tmpdir } from "node:os"
46
import path from "node:path"
57
import { randomUUID } from "node:crypto"
68
import { Agent } from "@/agent/agent"
79
import { Tool } from "@/tool/tool"
810
import { Truncate } from "@/tool/truncate"
9-
import * as TruncateCore from "@/tool/truncate-core"
11+
import { outputLimits } from "./output-settings"
1012
import { WarehouseListTool } from "../tools/warehouse-list"
1113
import { SchemaInspectTool } from "../tools/schema-inspect"
1214
import { SqlExecuteTool } from "../tools/sql-execute"
@@ -25,77 +27,67 @@ export const descriptions: Record<string, string> = {
2527
sql_materialize: "Copy a read-only source query into a session-local scratch table for further analysis.",
2628
}
2729

28-
// These services intentionally have no agent runtime, configuration loading, or provider dependencies.
30+
// No agent runtime or provider initialization; only local output settings are loaded.
2931
const analyst = { name: "analyst", mode: "primary", permission: [], options: {} } as Agent.Info
30-
const truncation: Truncate.Interface = {
31-
cleanup: () => Effect.void,
32-
limits: () => Effect.succeed({ maxLines: TruncateCore.MAX_LINES, maxBytes: TruncateCore.MAX_BYTES }),
33-
write: (text) =>
34-
Effect.promise(async () => {
35-
const directory = path.join(tmpdir(), "altimate-code-mcp-results")
36-
await mkdir(directory, { recursive: true, mode: 0o700 })
37-
const file = path.join(directory, `${randomUUID()}.txt`)
38-
await writeFile(file, text, { mode: 0o600 })
39-
return file
40-
}),
41-
output: (text, options = {}) =>
42-
Effect.gen(function* () {
43-
const maxLines = options.maxLines ?? TruncateCore.MAX_LINES
44-
const maxBytes = options.maxBytes ?? TruncateCore.MAX_BYTES
45-
const lines = text.split("\n")
46-
const bytes = Buffer.byteLength(text)
47-
if (TruncateCore.fits(lines, bytes, maxLines, maxBytes)) return { content: text, truncated: false as const }
48-
const direction = options.direction ?? TruncateCore.DEFAULT_DIRECTION
49-
const preview = TruncateCore.preview(lines, bytes, {
50-
maxLines,
51-
maxBytes,
52-
direction,
53-
headRatio: options.headRatio ?? TruncateCore.DEFAULT_HEAD_RATIO,
54-
})
55-
const file = yield* truncation.write(text)
56-
return {
57-
content: TruncateCore.assemble(
58-
preview,
59-
`Full output saved to: ${file}\nOpen this path with any file reader to inspect the remaining output.`,
60-
direction,
61-
),
62-
truncated: true as const,
63-
outputPath: file,
64-
}
65-
}),
32+
function services(directory: string, limits: Awaited<ReturnType<typeof outputLimits>>) {
33+
return Layer.mergeAll(
34+
Layer.succeed(
35+
Agent.Service,
36+
Agent.Service.of({
37+
get: () => Effect.succeed(analyst),
38+
list: () => Effect.succeed([analyst]),
39+
defaultInfo: () => Effect.succeed(analyst),
40+
defaultAgent: () => Effect.succeed(analyst.name),
41+
generate: () => Effect.die(new Error("MCP data tools never generate agents or call a model")),
42+
}),
43+
),
44+
Truncate.makeLayer({
45+
directory,
46+
limits: () => Effect.succeed(limits),
47+
hint: (file, outcome) =>
48+
`The tool call ${outcome === "error" ? "failed" : "succeeded"} but the output was truncated. Full output saved to: ${file}\nOpen this path with any file reader to inspect the remaining output.`,
49+
}).pipe(Layer.provide(FSUtil.defaultLayer), Layer.provide(NodePath.layer)),
50+
)
6651
}
6752

68-
const services = Layer.mergeAll(
69-
Layer.succeed(
70-
Agent.Service,
71-
Agent.Service.of({
72-
get: () => Effect.succeed(analyst),
73-
list: () => Effect.succeed([analyst]),
74-
defaultInfo: () => Effect.succeed(analyst),
75-
defaultAgent: () => Effect.succeed(analyst.name),
76-
generate: () => Effect.die(new Error("MCP data tools never generate agents or call a model")),
77-
}),
78-
),
79-
Layer.succeed(Truncate.Service, truncation),
80-
)
81-
8253
export async function createAdapter(options: { allowWrite?: boolean } = {}) {
54+
const limits = await outputLimits()
55+
const directory = await mkdtemp(path.join(tmpdir(), "altimate-code-mcp-results-"))
56+
await chmod(directory, 0o700)
8357
const sessionID = `mcp-${randomUUID()}` as SessionID
8458
Precedence.bindLocalSession(sessionID)
8559
const tools = await Effect.runPromise(
86-
Effect.gen(function* () {
87-
const result = new Map<string, Tool.Def>()
88-
for (const source of [WarehouseListTool, SchemaInspectTool, SqlExecuteTool, SqlCheckTool, SqlMaterializeTool]) {
89-
const info = yield* source
90-
result.set(info.id, yield* Tool.init(info, { agent: analyst }))
91-
}
92-
return result
93-
}).pipe(Effect.provide(services)),
94-
)
60+
Effect.scoped(
61+
Effect.gen(function* () {
62+
const result = new Map<string, Tool.Def>()
63+
for (const source of [WarehouseListTool, SchemaInspectTool, SqlExecuteTool, SqlCheckTool, SqlMaterializeTool]) {
64+
const info = yield* source
65+
const tool = yield* Tool.init(info, { agent: analyst })
66+
if (tool.jsonSchema) {
67+
tool.jsonSchema = JSON.parse(
68+
JSON.stringify(tool.jsonSchema).replaceAll(
69+
"use read with char_offset/max_chars to recover clipped text",
70+
"open result_path with any file reader to recover clipped text",
71+
),
72+
)
73+
}
74+
result.set(info.id, tool)
75+
}
76+
return result
77+
}).pipe(Effect.provide(services(directory, limits))),
78+
),
79+
).catch(async (error) => {
80+
Precedence.releaseLocalSession(sessionID)
81+
await rm(directory, { recursive: true, force: true })
82+
throw error
83+
})
9584

85+
const shutdown = new AbortController()
86+
const active = new Set<Promise<Tool.ExecuteResult>>()
9687
return {
9788
tools,
9889
async execute(name: string, args: Record<string, unknown>, signal: AbortSignal) {
90+
signal = AbortSignal.any([signal, shutdown.signal])
9991
signal.throwIfAborted()
10092
const tool = tools.get(name)
10193
if (!tool) throw new Error(`Unknown tool: ${name}`)
@@ -104,7 +96,7 @@ export async function createAdapter(options: { allowWrite?: boolean } = {}) {
10496
messageID: `mcp-${randomUUID()}` as MessageID,
10597
agent: "analyst",
10698
abort: signal,
107-
extra: { mcpClient: true },
99+
extra: { mcpClient: true, forceReadOnly: !options.allowWrite },
108100
messages: [],
109101
metadata: () => Effect.void,
110102
// Fail closed for new permission kinds. sql_execute is the validated source-read permission.
@@ -113,11 +105,23 @@ export async function createAdapter(options: { allowWrite?: boolean } = {}) {
113105
? Effect.void
114106
: Effect.die(new Error(`Permission denied: ${permission}. Restart with --allow-write to enable writes.`)),
115107
}
116-
return Effect.runPromise(tool.execute(args, ctx))
108+
const pending = Effect.runPromise(tool.execute(args, ctx))
109+
active.add(pending)
110+
try {
111+
return await pending
112+
} finally {
113+
active.delete(pending)
114+
}
117115
},
118116
async close() {
119-
await closeScratch(sessionID)
120-
Precedence.releaseLocalSession(sessionID)
117+
shutdown.abort(new Error("MCP server closed"))
118+
await Promise.allSettled([...active])
119+
try {
120+
await closeScratch(sessionID)
121+
} finally {
122+
Precedence.releaseLocalSession(sessionID)
123+
await rm(directory, { recursive: true, force: true })
124+
}
121125
},
122126
}
123127
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { readFile } from "node:fs/promises"
2+
import path from "node:path"
3+
import { parse } from "jsonc-parser"
4+
import { Global } from "@/global"
5+
import { MAX_LINES, MAX_BYTES } from "@/tool/truncate-core"
6+
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.
9+
export async function outputLimits() {
10+
const limits = { maxLines: MAX_LINES, maxBytes: MAX_BYTES }
11+
const apply = (text: string) => {
12+
const output = parse(text)?.tool_output
13+
if (Number.isInteger(output?.max_lines) && output.max_lines > 0) limits.maxLines = output.max_lines
14+
if (Number.isInteger(output?.max_bytes) && output.max_bytes > 0) limits.maxBytes = output.max_bytes
15+
}
16+
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+
})
21+
if (text) apply(text)
22+
}
23+
for (const name of ["config.json", "opencode.json", "opencode.jsonc", "altimate-code.json", "altimate-code.jsonc"]) {
24+
await load(path.join(Global.Path.config, name))
25+
}
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+
}
39+
}
40+
}
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))
44+
}
45+
}
46+
if (process.env.OPENCODE_CONFIG_CONTENT) apply(process.env.OPENCODE_CONFIG_CONTENT)
47+
return limits
48+
}

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

Lines changed: 19 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
22
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
33
import { CallToolRequestSchema, ListToolsRequestSchema, type Tool as McpTool } from "@modelcontextprotocol/sdk/types.js"
4-
import { readFile } from "node:fs/promises"
5-
import path from "node:path"
6-
import { isLocalFilePath, type ConnectionConfig } from "@altimateai/drivers"
74
import * as Registry from "../native/connections/registry"
85
import { createAdapter, descriptions } from "./adapter"
6+
import { readOnlyCaveat } from "../native/connections/read-only"
97
import { InstallationVersion } from "@opencode-ai/core/installation/version"
108

119
export interface ServeOptions {
@@ -14,28 +12,12 @@ export interface ServeOptions {
1412
}
1513

1614
export async function createServer(options: ServeOptions = {}) {
17-
if (options.connections) {
18-
const file = path.resolve(options.connections)
19-
const configs: unknown = JSON.parse(await readFile(file, "utf8"))
20-
if (!configs || typeof configs !== "object" || Array.isArray(configs))
21-
throw new Error("Connections file must contain an object keyed by connection name")
22-
const resolved: Record<string, ConnectionConfig> = {}
23-
for (const [name, value] of Object.entries(configs)) {
24-
if (!value || typeof value !== "object" || typeof value.type !== "string")
25-
throw new Error(`Invalid connection: ${name}`)
26-
const config = { ...value } as ConnectionConfig
27-
if (
28-
["duckdb", "sqlite"].includes(config.type.toLowerCase()) &&
29-
typeof config.path === "string" &&
30-
isLocalFilePath(config.path) &&
31-
!path.isAbsolute(config.path) &&
32-
!path.win32.isAbsolute(config.path)
33-
) {
34-
config.path = path.resolve(path.dirname(file), config.path)
35-
}
36-
resolved[name] = config
15+
if (options.connections) await Registry.loadFile(options.connections)
16+
if (!options.allowWrite) {
17+
for (const connection of Registry.list().warehouses) {
18+
const caveat = readOnlyCaveat(connection)
19+
if (caveat) console.error(caveat)
3720
}
38-
Registry.setConfigs(resolved)
3921
}
4022
const adapter = await createAdapter(options)
4123
const server = new Server({ name: "altimate-code", version: InstallationVersion }, { capabilities: { tools: {} } })
@@ -58,8 +40,18 @@ export async function createServer(options: ServeOptions = {}) {
5840
}
5941
}
6042
})
43+
let cleanup: Promise<void> | undefined
44+
const dispose = () => (cleanup ??= adapter.close())
6145
server.onclose = async () => {
62-
await adapter.close().catch(console.error)
46+
await dispose().catch(console.error)
47+
}
48+
const close = server.close.bind(server)
49+
server.close = async () => {
50+
try {
51+
await close()
52+
} finally {
53+
await dispose()
54+
}
6355
}
6456
return server
6557
}
@@ -95,5 +87,7 @@ export async function serveStdio(options: ServeOptions = {}): Promise<void> {
9587
process.stdin.off("end", close)
9688
process.off("SIGINT", close)
9789
process.off("SIGTERM", close)
90+
await server.close()
91+
await Registry.closeAll()
9892
}
9993
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/** Drivers that enforce ExecuteOptions.readOnly at the database boundary. */
2+
const ENFORCED = new Set(["postgres", "postgresql", "sqlite", "duckdb"])
3+
4+
export function readOnlyCaveat(connection: { name: string; type: string }): string | undefined {
5+
if (ENFORCED.has(connection.type.toLowerCase())) return undefined
6+
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`
7+
}

‎packages/opencode/src/altimate/native/connections/register.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -525,7 +525,7 @@ register("sql.execute", async (params: SqlExecuteParams, context): Promise<SqlEx
525525
// dbt knows how to connect using profiles.yml — no separate connection config needed.
526526
// altimate_change start — dbt cannot enforce the connector's read-only option.
527527
// Protected requests must reach the native driver's transaction handling.
528-
if (!params.warehouse && !params.read_only) {
528+
if (!params.warehouse && !params.read_only && !context?.forceReadOnly) {
529529
const dbtResult = await tryExecuteViaDbt(
530530
params.sql,
531531
params.limit,
@@ -559,7 +559,7 @@ register("sql.execute", async (params: SqlExecuteParams, context): Promise<SqlEx
559559
Registry.getConfig(fallbackName),
560560
{
561561
queryTimeoutMs: params.query_timeout_ms,
562-
...(fallbackType === "postgres" && params.read_only ? { readOnly: true } : {}),
562+
...(context?.forceReadOnly || (fallbackType === "postgres" && params.read_only) ? { readOnly: true } : {}),
563563
},
564564
context,
565565
async (options) => {

‎packages/opencode/src/altimate/native/connections/registry.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,27 @@ export function load(): void {
219219
loaded = true
220220
}
221221

222+
/** Load only an explicit connections file, resolving stores relative to that file. */
223+
export async function loadFile(file: string): Promise<void> {
224+
await closeAll()
225+
const absolute = path.resolve(file)
226+
const parsed: unknown = JSON.parse(await fs.promises.readFile(absolute, "utf8"))
227+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
228+
throw new Error("Connections file must contain an object keyed by connection name")
229+
}
230+
for (const [name, value] of Object.entries(parsed)) {
231+
if (!value || typeof value !== "object" || typeof value.type !== "string") {
232+
throw new Error(`Invalid connection: ${name}`)
233+
}
234+
}
235+
configs = new Map(
236+
Object.entries(resolveStorePaths(parsed as Record<string, ConnectionConfig>, path.dirname(absolute))),
237+
)
238+
if (configs.has(SCRATCH_NAME)) Log.Default.warn(SCRATCH_NAME_CONFLICT)
239+
loaded = true
240+
censusSent = false
241+
}
242+
222243
/** Ensure configs are loaded. */
223244
function ensureLoaded(): void {
224245
if (!loaded) load()

‎packages/opencode/src/altimate/native/query-execution.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { RunBudget } from "../run-budget"
66
export interface QueryContext {
77
signal?: AbortSignal
88
sessionID?: string
9+
/** MCP source reads request database protection even when SQL classifies as a read. */
10+
forceReadOnly?: boolean
911
}
1012

1113
/** Share the session cutoff across probes, extraction and scratch writes. */

0 commit comments

Comments
 (0)