Skip to content

Commit 7215ddd

Browse files
anandgupta42claude
andcommitted
feat(mcp): serve native data tools over stdio without an LLM
Add `altimate-code mcp serve`, a stdio MCP server that lets any MCP client (e.g. Claude Code) call altimate-code's data tools directly while the client's own model does the reasoning. The server never calls a model. - Exposes `warehouse_list`, `schema_inspect`, `sql_execute`, `sql_check` and `sql_materialize`, reusing the existing implementations with short tool descriptions. - Read-only by default: the `sql_execute_write` permission is denied unless `--allow-write` is passed; reads are auto-allowed. - Binds a local session at start-up so results do not carry the workspace-routing notice; forwards MCP cancellation to tool calls; `sql_materialize` keeps a session-local scratch warehouse. - Spill hints tell MCP clients to open the spill path with any file reader instead of naming the agent-only `read` tool. - `--connections <file>` or normal connection discovery; stdout carries only MCP protocol messages; no telemetry start-up. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 268cbd3 commit 7215ddd

10 files changed

Lines changed: 582 additions & 1 deletion

File tree

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,37 @@ description: "Configure Model Context Protocol (MCP) servers in Altimate Code to
66

77
altimate supports the Model Context Protocol (MCP) for connecting to external tool servers.
88

9+
## Use Altimate Code tools from another MCP client
10+
11+
Run `altimate-code mcp serve` to expose data tools over stdio. Your MCP client's model handles reasoning; this server runs tools directly without calling a model.
12+
13+
Add this entry to your MCP client's configuration (for example, Claude Code's `.mcp.json`):
14+
15+
```json
16+
{
17+
"mcpServers": {
18+
"altimate-code": {
19+
"command": "altimate-code",
20+
"args": ["mcp", "serve", "--connections", "/absolute/path/to/connections.json"]
21+
}
22+
}
23+
}
24+
```
25+
26+
The server exposes exactly `warehouse_list`, `schema_inspect`, `sql_execute`, `sql_check`, and `sql_materialize`. A connections file is a JSON object keyed by connection name:
27+
28+
```json
29+
{
30+
"local": { "type": "sqlite", "path": "./analytics.sqlite" }
31+
}
32+
```
33+
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.
35+
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.
37+
38+
The server writes only MCP protocol messages to stdout and sends logs to stderr. It does not initialize telemetry and honors `ALTIMATE_TELEMETRY_DISABLED`.
39+
940
## Local MCP Servers
1041

1142
Run an MCP server as a local subprocess:
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { Effect, Layer } from "effect"
2+
import { mkdir, writeFile } from "node:fs/promises"
3+
import { tmpdir } from "node:os"
4+
import path from "node:path"
5+
import { randomUUID } from "node:crypto"
6+
import { Agent } from "@/agent/agent"
7+
import { Tool } from "@/tool/tool"
8+
import { Truncate } from "@/tool/truncate"
9+
import * as TruncateCore from "@/tool/truncate-core"
10+
import { WarehouseListTool } from "../tools/warehouse-list"
11+
import { SchemaInspectTool } from "../tools/schema-inspect"
12+
import { SqlExecuteTool } from "../tools/sql-execute"
13+
import { SqlCheckTool } from "../tools/sql-check"
14+
import { SqlMaterializeTool } from "../tools/sql-materialize"
15+
import * as Precedence from "../workspace/precedence"
16+
import { closeScratch } from "../native/connections/scratch"
17+
import type { SessionID, MessageID } from "@/session/schema"
18+
19+
export const descriptions: Record<string, string> = {
20+
warehouse_list: "List configured warehouse connections and their database types.",
21+
schema_inspect: "Inspect tables and columns in a connected warehouse, with optional sample values.",
22+
sql_execute:
23+
"Execute SQL against a connected warehouse and return rows. Source writes require the server's --allow-write option.",
24+
sql_check: "Run a read-only SQL data quality check against a connected warehouse.",
25+
sql_materialize: "Copy a read-only source query into a session-local scratch table for further analysis.",
26+
}
27+
28+
// These services intentionally have no agent runtime, configuration loading, or provider dependencies.
29+
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+
}),
66+
}
67+
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+
82+
export async function createAdapter(options: { allowWrite?: boolean } = {}) {
83+
const sessionID = `mcp-${randomUUID()}` as SessionID
84+
Precedence.bindLocalSession(sessionID)
85+
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+
)
95+
96+
return {
97+
tools,
98+
async execute(name: string, args: Record<string, unknown>, signal: AbortSignal) {
99+
signal.throwIfAborted()
100+
const tool = tools.get(name)
101+
if (!tool) throw new Error(`Unknown tool: ${name}`)
102+
const ctx: Tool.Context = {
103+
sessionID,
104+
messageID: `mcp-${randomUUID()}` as MessageID,
105+
agent: "analyst",
106+
abort: signal,
107+
extra: { mcpClient: true },
108+
messages: [],
109+
metadata: () => Effect.void,
110+
// Fail closed for new permission kinds. sql_execute is the validated source-read permission.
111+
ask: ({ permission }) =>
112+
permission === "sql_execute" || permission === "schema_inspect" || options.allowWrite
113+
? Effect.void
114+
: Effect.die(new Error(`Permission denied: ${permission}. Restart with --allow-write to enable writes.`)),
115+
}
116+
return Effect.runPromise(tool.execute(args, ctx))
117+
},
118+
async close() {
119+
await closeScratch(sessionID)
120+
Precedence.releaseLocalSession(sessionID)
121+
},
122+
}
123+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
2+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
3+
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"
7+
import * as Registry from "../native/connections/registry"
8+
import { createAdapter, descriptions } from "./adapter"
9+
import { InstallationVersion } from "@opencode-ai/core/installation/version"
10+
11+
export interface ServeOptions {
12+
connections?: string
13+
allowWrite?: boolean
14+
}
15+
16+
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
37+
}
38+
Registry.setConfigs(resolved)
39+
}
40+
const adapter = await createAdapter(options)
41+
const server = new Server({ name: "altimate-code", version: InstallationVersion }, { capabilities: { tools: {} } })
42+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
43+
tools: [...adapter.tools].map(([name, tool]) => ({
44+
name,
45+
description: descriptions[name],
46+
inputSchema: tool.jsonSchema as McpTool["inputSchema"],
47+
})),
48+
}))
49+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
50+
try {
51+
const result = await adapter.execute(request.params.name, request.params.arguments ?? {}, extra.signal)
52+
const isError = result.status === "error" || (result.metadata.success !== true && Boolean(result.metadata.error))
53+
return { content: [{ type: "text" as const, text: result.output }], isError }
54+
} catch (error) {
55+
return {
56+
content: [{ type: "text" as const, text: error instanceof Error ? error.message : String(error) }],
57+
isError: true,
58+
}
59+
}
60+
})
61+
server.onclose = async () => {
62+
await adapter.close().catch(console.error)
63+
}
64+
return server
65+
}
66+
67+
export async function serveStdio(options: ServeOptions = {}): Promise<void> {
68+
// Protocol writes use the transport's stdout directly; application logging must use stderr.
69+
console.log = console.error.bind(console)
70+
console.info = console.error.bind(console)
71+
console.debug = console.error.bind(console)
72+
const server = await createServer(options)
73+
server.onerror = (error) => console.error(error)
74+
const closed = Promise.withResolvers<void>()
75+
const onclose = server.onclose
76+
server.onclose = async () => {
77+
try {
78+
await onclose?.()
79+
await Registry.closeAll()
80+
closed.resolve()
81+
} catch (error) {
82+
closed.reject(error)
83+
}
84+
}
85+
const close = () => {
86+
void server.close().catch(closed.reject)
87+
}
88+
process.stdin.once("end", close)
89+
process.once("SIGINT", close)
90+
process.once("SIGTERM", close)
91+
try {
92+
await server.connect(new StdioServerTransport())
93+
await closed.promise
94+
} finally {
95+
process.stdin.off("end", close)
96+
process.off("SIGINT", close)
97+
process.off("SIGTERM", close)
98+
}
99+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ export const SqlExecuteTool = Tool.define(
360360
const suggestion = ctx.agent === "analyst" ? null : PostConnectSuggestions.getProgressiveSuggestion("sql_execute")
361361
const lint = await lintSqlResult(sql, args.warehouse, ctx.sessionID)
362362
const formatted = await formatSqlResult(result, {
363+
mcpClient: ctx.extra?.mcpClient === true,
363364
limit,
364365
fullTextColumns: args.full_text_columns,
365366
// The statement text lets the formatter add the empty/near-empty

‎packages/opencode/src/altimate/tools/sql-result-format.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export const SQL_MAX_PREVIEW_BYTES = 16 * 1024
66
export const SQL_MAX_SPILL_BYTES = 32 * 1024 * 1024
77

88
interface FormatOptions {
9+
mcpClient?: boolean
910
limit: number
1011
maxBytes?: number
1112
maxLines?: number
@@ -520,7 +521,10 @@ export async function formatSqlResult(result: SqlExecuteResult, options: FormatO
520521
const chunks: string[] = []
521522
serializeRows(result, (chunk) => chunks.push(chunk))
522523
metadata.result_path = await options.write(chunks.join(""))
523-
spill = `All ${result.rows.length} returned rows saved to ${metadata.result_path}. JSONL text: columns/values per row; $bigint, $date (ISO), $bytes (base64) tags; strings unchanged. Use read with char_offset/max_chars to recover any clipped text.`
524+
const reader = options.mcpClient
525+
? "Open this path with any file reader to recover clipped text."
526+
: "Use read with char_offset/max_chars to recover any clipped text."
527+
spill = `All ${result.rows.length} returned rows saved to ${metadata.result_path}. JSONL text: columns/values per row; $bigint, $date (ISO), $bytes (base64) tags; strings unchanged. ${reader}`
524528
} catch {
525529
spill = `Spill failed (write/serialization error or ${SQL_MAX_SPILL_BYTES / 1024 / 1024} MiB size limit); returned rows were not saved.`
526530
}

‎packages/opencode/src/altimate/workspace/precedence.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,16 @@ const EMPTY = (reason: Precedence["disabledReason"], workspaceName = "", workspa
190190
/** Per-session precedence, refreshed once per turn by the tool resolver and read
191191
* (never recomputed) by tool bodies mid-turn. */
192192
const bySession = new Map<string, Precedence>()
193+
194+
/** A standalone native-tool server deliberately uses local drivers, without attaching an engine. */
195+
export function bindLocalSession(sessionID: string): void {
196+
remember(sessionID, EMPTY("escape-hatch"))
197+
}
198+
199+
export function releaseLocalSession(sessionID: string): void {
200+
bySession.delete(sessionID)
201+
incarnations.delete(sessionID)
202+
}
193203
/** One token per session incarnation: set when a session is first remembered or
194204
* recreated after eviction, dropped with it. A delivery records against the
195205
* incarnation it was published for, so ordinary refreshes (which replace the

‎packages/opencode/src/cli/cmd/mcp.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ export const McpCommand = cmd({
108108
yargs
109109
.command(McpAddCommand)
110110
.command(McpListCommand)
111+
// altimate_change start — expose native data tools over stdio without an agent
112+
.command(McpServeCommand)
113+
// altimate_change end
111114
// altimate_change start — upstream_fix (#790): `status` is the name people reach for when a
112115
// server will not connect, and it was the one name that did not exist. It shares the list
113116
// handler rather than duplicating a view that already probes live and already prints the
@@ -124,6 +127,20 @@ export const McpCommand = cmd({
124127
async handler() {},
125128
})
126129

130+
// altimate_change start — standalone native-tool MCP server
131+
export const McpServeCommand = cmd({
132+
command: "serve",
133+
describe: "serve data tools over MCP stdio (no model required)",
134+
builder: (yargs) => yargs
135+
.option("connections", { type: "string", describe: "Connections JSON file" })
136+
.option("allow-write", { type: "boolean", default: false, describe: "Allow SQL write permissions" }),
137+
async handler(args) {
138+
const { serveStdio } = await import("../../altimate/mcp-server/server")
139+
await serveStdio({ connections: args.connections, allowWrite: args.allowWrite })
140+
},
141+
})
142+
// altimate_change end
143+
127144
// altimate_change start — upstream_fix (#878/#701): config-level diagnostics, shared by every
128145
// exit of `mcp list` / `mcp status` so a config with nothing listable still reports them.
129146
function reportConfigDiagnostics() {

‎packages/opencode/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ let cli = yargs(args)
135135
})
136136
// altimate_change end
137137
.middleware(async (opts) => {
138+
// altimate_change start — MCP stdio needs no banner, telemetry startup or agent initialization
139+
if (opts._[0] === "mcp" && opts._[1] === "serve") return
140+
// altimate_change end
138141
if (opts.printLogs) process.env.OPENCODE_PRINT_LOGS = "1"
139142
if (opts.logLevel) process.env.OPENCODE_LOG_LEVEL = opts.logLevel
140143
if (opts.pure) {

0 commit comments

Comments
 (0)