Skip to content

Commit 853bfa0

Browse files
hkaltaiclaude
andcommitted
fix: address review findings in the tool CLI, MCP server and workspace tools
- `daemon`: requests wait for an in-progress file release, `stop` replies before shutting down, and the daemon key includes `ALTIMATE_DISABLE_SCHEMA_VALUES`, `ALTIMATE_INTEGRATIONS` and `ALTIMATE_DISABLE_WORKSPACE`. - `permissions`: the blocked-statement check runs before the read-permission shortcut. - `claude-md`: a symlinked `CLAUDE.md` is left untouched. - `workspace-tools`: workspace-authored names and descriptions render as one inert line, skills are read through `WorkspaceClient.readSkill`, and the workspace is labelled with `workspaceLabel`. - MCP workspace adapter: an adapter is closed only after the operations using it finish; `serverInstructions` releases file connections it opened. - `outputLimits` reads organisation-managed config and preferences. - `schema-list`: MySQL and Redshift (whose drivers ignore binds) get an escaped schema literal; schema names are sorted before the limit. - `registry.releaseFileConnections` keeps remote and in-memory URI stores. - `sql_execute` batches: `truncated` reports row-limited or clipped items, references resolve against the default warehouse, duplicate labels are rejected, backslashes are escaped for BigQuery, Snowflake, Databricks and ClickHouse, and an unmaterialized spill returns no table. - `answer_commit`: integers keep every digit; coverage and number checks stand down when the run budget is ending (one shared `budgetEnding`). - `warehouse_add` resolves relative store paths against the project root; `warehouse_list` skips only workspace-routed connections in discovery. - `analyst-effort` honours SAP `modelParams` and the configured `model.variants`. - Workspace client: `readSkill` opens with `O_NOFOLLOW`; context lists only skills with a regular `SKILL.md`. `releaseLocalSession` clears every per-session map; skill withdrawal runs in `finally` on purge. - MongoDB `listTables` checks that an empty database exists. - Docs and `--allow-write` help match the actual policies. - Tests for each behaviour change; new suites restore their spies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b139685 commit 853bfa0

46 files changed

Lines changed: 795 additions & 130 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ Source writes are refused by default. Without `--allow-write`, source queries re
4141

4242
<!-- altimate_change end -->
4343

44-
The server writes only MCP protocol messages to stdout and sends logs to stderr. It does not initialize telemetry and honors `ALTIMATE_TELEMETRY_DISABLED`.
44+
The server writes only MCP protocol messages to stdout and sends logs to stderr. It honors `ALTIMATE_TELEMETRY_DISABLED`.
4545

4646
## Local MCP Servers
4747

‎docs/docs/usage/tool.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ description: "Call Altimate Code data tools from any shell, agent or CI job with
55

66
# Tool CLI (Headless)
77

8-
Expose the data tools -- warehouse, SQL, schema, lineage, impact, PII, data-diff, FinOps and dbt -- as plain commands. No model or API key is involved, so Claude Code, Codex and CI jobs can call them directly.
8+
Expose the data tools -- warehouse, SQL, schema, lineage, impact, PII, data-diff, FinOps and dbt -- as plain commands. The local data tools use no model or API key, so Claude Code, Codex and CI jobs can call them directly. Linked workspace tools authenticate to Altimate and `workspace_execute` may use backend models.
99

1010
## List tools
1111

@@ -14,15 +14,15 @@ altimate-code tool list # id and description
1414
altimate-code tool list --json # id, description and JSON input schema
1515
```
1616

17-
`tool` and `mcp serve` share one implementation, so compact schemas, `sql_execute` with `tables`, `query_from` chaining, spilled result files, read-only enforcement and `answer_commit` (with its `request` argument) behave the same in both. `tool` exposes the full tool list. In a project linked to a workspace it also exposes `workspace_context`, `workspace_skill` and `workspace_execute`; the link is read from the project's saved state, with no network request. Pass `--workspace-tools` to add them to an unlinked project, or `--no-workspace-tools` to leave them out of a linked one.
17+
`tool` and `mcp serve` share one implementation, so compact schemas, `sql_execute` with `tables`, `query_from` chaining, spilled result files, read-only enforcement and `answer_commit` (with its `request` argument) are consistent in both. Their permission policies differ: the CLI requires `--allow-write` for local configuration writes such as `warehouse_add`, while `mcp serve` allows `warehouse_add` by default. `tool` exposes the full tool list. In a project linked to a workspace it also exposes `workspace_context`, `workspace_skill` and `workspace_execute`; the link is read from the project's saved state, with no network request. Pass `--workspace-tools` to add them to an unlinked project, or `--no-workspace-tools` to leave them out of a linked one.
1818

1919
## Startup context
2020

2121
```bash
2222
altimate-code tool context [--connections <file>] [--json]
2323
```
2424

25-
Prints the analyst method and the connections known at startup (the same text `mcp serve` sends as its instructions), so a shell agent gets it in one call.
25+
Prints the analyst method and the connections known at startup (the same base instructions `mcp serve` sends, plus the linked workspace's name, skills and tools when workspace tools are enabled), so a shell agent gets it in one call.
2626

2727
## Run a tool
2828

@@ -64,7 +64,7 @@ altimate-code tool daemon status
6464
altimate-code tool daemon stop
6565
```
6666

67-
`status` and `stop` locate the running daemon the same way `run` does: by project directory, CLI version, the `--connections` file (if any), whether workspace tools are on, and the caller's `ALTIMATE_CODE_CONN_*` environment variables. Run them with the same flags and `ALTIMATE_CODE_CONN_*` variables as the call that started the daemon, or they will report no daemon running for this project even though one is.
67+
`status` and `stop` locate the running daemon the same way `run` does: by project directory, CLI version, the `--connections` file (if any), whether workspace tools are on, and the caller's `ALTIMATE_CODE_CONN_*`, `ALTIMATE_DISABLE_SCHEMA_VALUES`, `ALTIMATE_INTEGRATIONS` and `ALTIMATE_DISABLE_WORKSPACE` environment variables. Run them with the same flags and variables as the call that started the daemon, or they will report no daemon running for this project even though one is.
6868

6969
| Setting | Description |
7070
|---|---|

‎packages/drivers/src/mongodb.ts‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,24 @@ export async function connect(config: ConnectionConfig): Promise<Connector> {
307307
databaseNames = undefined
308308
}
309309

310+
/** An empty collection list is only valid for a database the user can see. */
311+
async function assertDatabaseExists(name: string, maxTimeMS: number | undefined): Promise<void> {
312+
const pendingNames: Promise<string[]> = databaseNames ?? client.db().admin()
313+
.listDatabases({ nameOnly: true, authorizedDatabases: true, ...withMaxTime(maxTimeMS) })
314+
.then((result: { databases: Array<{ name: string }> }) => result.databases.map((db) => db.name).sort())
315+
.catch((error: unknown) => {
316+
databaseNames = undefined
317+
throw error
318+
})
319+
databaseNames = pendingNames
320+
const names = await pendingNames
321+
if (!names.includes(name)) {
322+
throw new Error(
323+
`MongoDB database "${name}" does not exist or is not accessible. Available databases: ${names.join(", ") || "(none)"}`,
324+
)
325+
}
326+
}
327+
310328
async function readCollections(db: any, maxTimeMS: number | undefined): Promise<Array<{ name: string; type: string }>> {
311329
const name = db.databaseName as string
312330
const pending: Promise<Array<{ name: string; type: string }>> = collectionCache.get(name)
@@ -320,22 +338,7 @@ export async function connect(config: ConnectionConfig): Promise<Connector> {
320338
throw error
321339
}
322340
// Visible collections prove the database exists without requiring database-listing privileges.
323-
if (collections.length === 0) {
324-
const pendingNames: Promise<string[]> = databaseNames ?? client.db().admin()
325-
.listDatabases({ nameOnly: true, authorizedDatabases: true, ...withMaxTime(maxTimeMS) })
326-
.then((result: { databases: Array<{ name: string }> }) => result.databases.map((db) => db.name).sort())
327-
.catch((error: unknown) => {
328-
databaseNames = undefined
329-
throw error
330-
})
331-
databaseNames = pendingNames
332-
const names = await pendingNames
333-
if (!names.includes(name)) {
334-
throw new Error(
335-
`MongoDB database "${name}" does not exist or is not accessible. Available databases: ${names.join(", ") || "(none)"}`,
336-
)
337-
}
338-
}
341+
if (collections.length === 0) await assertDatabaseExists(name, maxTimeMS)
339342
return collections
340343
}
341344

@@ -618,6 +621,7 @@ export async function connect(config: ConnectionConfig): Promise<Connector> {
618621
const matches = await readCursor(db.listCollections(parsed.filter ?? {}, {
619622
nameOnly: true, authorizedCollections: true, batchSize: Math.min(effectiveLimit + 1, 501), ...withMaxTime(maxTimeMS),
620623
}), effectiveLimit + 1)
624+
if (matches.length === 0) await assertDatabaseExists(db.databaseName as string, maxTimeMS)
621625
const rows = matches.slice(0, effectiveLimit)
622626
.map((collection) => [collection.name, collection.type])
623627
return { columns: ["name", "type"], rows, row_count: rows.length, truncated: matches.length > effectiveLimit }

‎packages/drivers/test/mongodb-unit.test.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,14 @@ describe("MongoDB read namespace validation", () => {
145145
expect(finds).toEqual([])
146146
})
147147

148+
test("listCollections on a missing database reports the available databases", async () => {
149+
const { connector } = await fakeMongo()
150+
await expect(connector.execute(JSON.stringify({ listCollections: 1, database: "missing" }))).rejects.toThrow(
151+
'MongoDB database "missing" does not exist or is not accessible. Available databases: archive, test',
152+
)
153+
expect(await connector.execute(JSON.stringify({ listCollections: 1, database: "archive" }))).toMatchObject({ rows: [], truncated: false })
154+
})
155+
148156
test("wrong collection lists available collections before opening a cursor", async () => {
149157
const { connector, query, finds } = await fakeMongo()
150158
await expect(connector.execute(query("find", { collection: "missing" }))).rejects.toThrow(
@@ -181,9 +189,7 @@ describe("MongoDB read namespace validation", () => {
181189
expect(await connector.execute(JSON.stringify({ command: "listCollections", database: "archive" }))).toEqual({
182190
columns: ["name", "type"], rows: [], row_count: 0, truncated: false,
183191
})
184-
// altimate_change start — an empty bounded cursor needs no unbounded metadata validation
185-
expect(databaseLists).toEqual([])
186-
// altimate_change end
192+
expect(databaseLists).toEqual([{ nameOnly: true, authorizedDatabases: true, maxTimeMS: 120_000 }])
187193
})
188194

189195
test("metadata failures cannot become an empty read", async () => {

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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { Agent } from "@/agent/agent"
99
import { Tool } from "@/tool/tool"
1010
import { Truncate } from "@/tool/truncate"
1111
import { outputLimits } from "./output-settings"
12-
import { renderAnswer } from "../tools/answer-commit"
12+
import { MAX_BASIS_CHARACTERS, renderAnswer } from "../tools/answer-commit"
1313
import { AnswerCommitConjunction } from "../tools/answer-commit-conjunction"
1414
import { MAX_SCANNED_CHARACTERS } from "../tools/answer-commit-checks"
1515
import * as Precedence from "../workspace/precedence"
@@ -183,7 +183,6 @@ export function compactSchema<T>(name: string, schema: T): T {
183183
}
184184

185185
// The native tool caps `basis` at 400 characters; over the MCP boundary the text is trimmed instead of rejected.
186-
const BASIS_LIMIT = 400
187186
const MCP_ONLY_TOOLS = new Set(["answer_commit"])
188187

189188
/**
@@ -203,7 +202,6 @@ const DEFAULT_EXTRA_TOOLS = [
203202
"sql_translate",
204203
]
205204
export const DEFAULT_TOOLS: ReadonlySet<string> = new Set([...LEAN_TOOLS, ...DEFAULT_EXTRA_TOOLS])
206-
export const ALL_TOOLS: readonly string[] = Object.keys(EXPOSED)
207205
const MAX_FUSED_TABLES = 8
208206

209207
/** Adds `tables` to the advertised sql_execute schema: tables described in the same call, before its queries. */
@@ -305,7 +303,7 @@ function recordRequest(messages: TurnMessage[], request: unknown) {
305303
}
306304

307305
function relaxBasis<T>(schema: T): T {
308-
const copy = JSON.parse(JSON.stringify(schema).replaceAll(`at most ${BASIS_LIMIT} characters`, "kept brief")) as {
306+
const copy = JSON.parse(JSON.stringify(schema).replaceAll(`at most ${MAX_BASIS_CHARACTERS} characters`, "kept brief")) as {
309307
properties?: { basis?: { maxLength?: number } }
310308
}
311309
delete copy.properties?.basis?.maxLength
@@ -477,8 +475,8 @@ export async function createAdapter(options: AdapterOptions = {}) {
477475
// Fail closed for new permission kinds. sql_execute is the validated source-read permission.
478476
ask: askFor(allowWrite, retry),
479477
}
480-
if (MCP_ONLY_TOOLS.has(name) && typeof args.basis === "string" && args.basis.length > BASIS_LIMIT)
481-
args = { ...args, basis: args.basis.slice(0, BASIS_LIMIT) }
478+
if (MCP_ONLY_TOOLS.has(name) && typeof args.basis === "string" && args.basis.length > MAX_BASIS_CHARACTERS)
479+
args = { ...args, basis: args.basis.slice(0, MAX_BASIS_CHARACTERS) }
482480
let request: unknown
483481
if (name === "answer_commit") {
484482
const { request: text, ...rest } = args

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { FSUtil } from "@opencode-ai/core/fs-util"
77
import { Global } from "@/global"
88
import { ConfigPaths } from "@/config/paths"
99
import { ConfigVariable } from "@/config/variable"
10+
import { ConfigManaged } from "@/config/managed"
1011
import { git } from "@/util/git"
1112
import { MAX_LINES, MAX_BYTES } from "@/tool/truncate-core"
1213

@@ -76,5 +77,11 @@ export async function outputLimits() {
7677
}
7778
const content = env("OPENCODE_CONFIG_CONTENT")
7879
if (content) await apply(content, { source: "OPENCODE_CONFIG_CONTENT" })
80+
// Organisation-managed config merges last in the agent loader, so it caps everything above.
81+
for (const name of ["altimate-code.json", "altimate-code.jsonc", "opencode.json", "opencode.jsonc"]) {
82+
await load(path.join(ConfigManaged.managedConfigDir(), name))
83+
}
84+
const preferences = await ConfigManaged.readManagedPreferences().catch(() => undefined)
85+
if (preferences) await apply(preferences.text, { source: preferences.source })
7986
return limits
8087
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ export async function serverInstructions(): Promise<string> {
3737
return summary ? `${SERVER_INSTRUCTIONS}\n\nConnections:\n${summary}` : SERVER_INSTRUCTIONS
3838
} catch {
3939
return SERVER_INSTRUCTIONS
40+
} finally {
41+
// The catalog listing opens local SQLite/DuckDB files; release them so other processes can open them while idle.
42+
await Registry.releaseFileConnections().catch(() => {})
4043
}
4144
}
4245

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

Lines changed: 44 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -199,16 +199,23 @@ export async function createWorkspaceAdapter(directory: string) {
199199
type Context = Awaited<ReturnType<typeof WorkspaceClient.context>>
200200
let cached: { value: Context; until: number } | undefined
201201
let load: { token: string; promise: Promise<Context> } | undefined
202-
let active: { token: string; adapter: Awaited<ReturnType<typeof createPinnedWorkspaceAdapter>> } | undefined
202+
type Pinned = Awaited<ReturnType<typeof createPinnedWorkspaceAdapter>>
203+
type Active = { token: string; adapter: Pinned; running: Set<Promise<void>> }
204+
let active: Active | undefined
203205
let queue = Promise.resolve()
204206
let closed = false
205207
const text = (value: unknown) => ({ content: [{ type: "text" as const, text: JSON.stringify(value) }] })
208+
// An adapter is closed only after the operations that hold it have finished.
209+
const retire = async (entry: Active) => {
210+
await Promise.all(entry.running)
211+
await entry.adapter.close()
212+
}
206213
const connection = (token: string, refresh = false) => {
207214
const job = queue.then(async () => {
208215
if (closed) throw new Error("Workspace server closed.")
209216
await WorkspaceClient.assertIdentity(directory, token)
210-
if (!refresh && active?.token === token) return active.adapter
211-
await active?.adapter.close()
217+
if (!refresh && active?.token === token) return active
218+
if (active) await retire(active)
212219
active = undefined
213220
const adapter = await createPinnedWorkspaceAdapter(directory)
214221
try {
@@ -218,15 +225,29 @@ export async function createWorkspaceAdapter(directory: string) {
218225
await adapter.close()
219226
throw error
220227
}
221-
active = { token, adapter }
222-
return adapter
228+
active = { token, adapter, running: new Set() }
229+
return active
223230
})
224231
queue = job.then(
225232
() => {},
226233
() => {},
227234
)
228235
return job
229236
}
237+
const withAdapter = async <A>(token: string, refresh: boolean, use: (adapter: Pinned) => Promise<A>) => {
238+
const entry = await connection(token, refresh)
239+
const run = Promise.resolve().then(() => use(entry.adapter))
240+
const settled = run.then(
241+
() => {},
242+
() => {},
243+
)
244+
entry.running.add(settled)
245+
try {
246+
return await run
247+
} finally {
248+
entry.running.delete(settled)
249+
}
250+
}
230251
return {
231252
tools,
232253
async execute(name: string, args: Record<string, unknown>, signal: AbortSignal) {
@@ -261,15 +282,16 @@ export async function createWorkspaceAdapter(directory: string) {
261282
await WorkspaceClient.assertIdentity(directory, token)
262283
signal.throwIfAborted()
263284
if (args.include_tools !== true) return text({ status: "ready", ...value })
264-
const adapter = await connection(token, args.refresh === true)
265-
const operations = adapter.tools
266-
.filter((tool) => tool.name !== "workspace_context" && tool.name !== "workspace_skill")
267-
.map(({ name, description, inputSchema }) => ({
268-
name: name.slice("workspace_".length),
269-
description,
270-
inputSchema,
271-
}))
272-
const engine = await adapter.engineStatus()
285+
const { operations, engine } = await withAdapter(token, args.refresh === true, async (adapter) => ({
286+
operations: adapter.tools
287+
.filter((tool) => tool.name !== "workspace_context" && tool.name !== "workspace_skill")
288+
.map(({ name, description, inputSchema }) => ({
289+
name: name.slice("workspace_".length),
290+
description,
291+
inputSchema,
292+
})),
293+
engine: await adapter.engineStatus(),
294+
}))
273295
signal.throwIfAborted()
274296
await WorkspaceClient.assertIdentity(directory, token)
275297
return text({ status: "ready", ...value, operations, ...engine })
@@ -287,21 +309,22 @@ export async function createWorkspaceAdapter(directory: string) {
287309
throw new Error("Workspace operation is not exposed by the read-only integration.")
288310
if (!args.arguments || typeof args.arguments !== "object" || Array.isArray(args.arguments))
289311
throw new Error("Operation arguments must be an object.")
290-
const adapter = await connection(args.workspace_token)
291312
const operation = `workspace_${args.operation}`
292-
if (!adapter.tools.some((tool) => tool.name === operation))
293-
throw new Error(
294-
"Workspace operation is unavailable. Read workspace_context with include_tools=true for the current catalog.",
295-
)
296-
const answer = await adapter.execute(operation, args.arguments as Record<string, unknown>, signal)
313+
const answer = await withAdapter(args.workspace_token, false, async (adapter) => {
314+
if (!adapter.tools.some((tool) => tool.name === operation))
315+
throw new Error(
316+
"Workspace operation is unavailable. Read workspace_context with include_tools=true for the current catalog.",
317+
)
318+
return adapter.execute(operation, args.arguments as Record<string, unknown>, signal)
319+
})
297320
await WorkspaceClient.assertIdentity(directory, args.workspace_token)
298321
return answer
299322
},
300323
async close() {
301324
closed = true
302325
cached = undefined
303326
await queue
304-
await active?.adapter.close()
327+
if (active) await retire(active)
305328
active = undefined
306329
},
307330
}

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { Instance } from "@/project/instance"
2222
import { Log } from "@/altimate/util/log"
2323
import type { ConnectionConfig, Connector } from "@altimateai/drivers"
2424
import { isLocalFilePath, normalizeConfig } from "@altimateai/drivers"
25+
import { absoluteFileUriPath } from "@altimateai/drivers/file-store"
2526
import { forgetCredentials, notRemovedWarning, resolveConfig, saveConnection } from "./credential-store"
2627
// altimate_change start — the shared home, which honours the test-isolation override
2728
import { Global } from "@/global"
@@ -1046,7 +1047,8 @@ export async function releaseFileConnections(): Promise<void> {
10461047
const config = s.configs.get(name)
10471048
const type = canonicalType(config?.type)
10481049
// An in-memory database holds no file lock, and closing it would discard its contents.
1049-
const file = typeof config?.path === "string" && config.path !== "" && config.path !== ":memory:"
1050+
const store = typeof config?.path === "string" ? config.path : ""
1051+
const file = isLocalFilePath(store) || absoluteFileUriPath(store) !== undefined
10501052
if ((type === "duckdb" || type === "sqlite") && file) tasks.push(detachCached(s, name))
10511053
}
10521054
await Promise.all(tasks.map((task) => task()))

0 commit comments

Comments
 (0)