Skip to content

Commit 4c8490f

Browse files
anandgupta42claude
andcommitted
feat(mcp): list connections and small local catalogs in the server instructions
Starting a data question cost a `warehouse_list` round trip. The initialize instructions now end with the connection list known at startup: name, type and, for small local catalogs, table names (reusing the warehouse_list discovery budget; at most 1,200 bytes; a connection that does not fit is listed by name only; remote catalogs by name only). `warehouse_list` stays for refreshes, columns and sample rows. Local connectors now open at server start. Tests: `server.test.ts` (ALTIMATE_MCP_E2E=1): list present, 60-table catalog falls back to the name, cap. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 07b3c80 commit 4c8490f

3 files changed

Lines changed: 81 additions & 5 deletions

File tree

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

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,37 @@ import {
99
} from "@modelcontextprotocol/sdk/types.js"
1010
import * as Registry from "../native/connections/registry"
1111
import { createAdapter, descriptions } from "./adapter"
12+
import { catalogSummary } from "../tools/warehouse-discovery"
1213
import { readOnlyCaveat } from "../native/connections/read-only"
1314
import path from "node:path"
1415
import { pathToFileURL } from "node:url"
1516
import { InstallationVersion } from "@opencode-ai/core/installation/version"
1617

1718
export const SERVER_INSTRUCTIONS = [
1819
"Analyst method for data questions:",
19-
"1. Start with warehouse_list (local tables, columns, a sample row); if none fit, warehouse_add one.",
20+
"1. Connections are listed below; warehouse_list refreshes them with columns and a sample row. If none fit, warehouse_add one.",
2021
"2. Check stored value formats before filtering or joining: sql_execute `tables` returns value profiles in the same call as your queries.",
2122
"3. Compute in the database; chain dependent steps (any connection) in one sql_execute `queries` call.",
2223
"4. Cross-connection joins: sql_materialize the smaller filtered side into `scratch` and join there.",
2324
"5. Finish with answer_commit (`asked` = the requested items, one field each); reply with exactly its FINAL ANSWER text.",
2425
].join("\n")
2526

27+
/**
28+
* The analyst method plus the connection list known at startup (names, types, table names of small local catalogs;
29+
* bounded by catalogSummary), so a client can start querying without a warehouse_list round trip. A failing or empty
30+
* listing leaves the method alone.
31+
*/
32+
async function serverInstructions(): Promise<string> {
33+
try {
34+
const warehouses = Registry.list().warehouses
35+
if (!warehouses.length) return SERVER_INSTRUCTIONS
36+
const summary = await catalogSummary(warehouses, { signal: AbortSignal.timeout(5_000), sessionID: "mcp-startup" })
37+
return summary ? `${SERVER_INSTRUCTIONS}\n\nConnections:\n${summary}` : SERVER_INSTRUCTIONS
38+
} catch {
39+
return SERVER_INSTRUCTIONS
40+
}
41+
}
42+
2643
/** Spilled results: a resource_link next to the text, which keeps the preview, row count and path. */
2744
function resultLinks(metadata: Record<string, unknown>) {
2845
// A batched sql_execute call reports one saved file per spilled query.
@@ -68,7 +85,7 @@ export async function createServer(options: ServeOptions = {}) {
6885
const adapter = await createAdapter(options)
6986
const server = new Server({ name: "altimate-code", version: InstallationVersion }, {
7087
capabilities: { tools: {}, prompts: {} },
71-
instructions: SERVER_INSTRUCTIONS,
88+
instructions: await serverInstructions(),
7289
})
7390
server.setRequestHandler(ListToolsRequestSchema, async () => ({
7491
tools: [...adapter.tools].map(([name, tool]) => ({

‎packages/opencode/src/altimate/tools/warehouse-discovery.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,48 @@ export async function discoverCatalog(warehouses: { name: string; type: string }
168168
return lines.join("\n")
169169
}
170170

171+
const SUMMARY_BYTES = 1_200
172+
const SUMMARY_DEADLINE_MS = 2_000
173+
174+
/**
175+
* A compact connection list for the MCP server instructions: one line per connection with its type and, for small
176+
* local catalogs, its table names. Bounded like discoverCatalog (local engines only, table budget, deadline) and by
177+
* SUMMARY_BYTES; a connection whose tables do not fit is listed by name only. No columns, samples or row counts.
178+
*/
179+
export async function catalogSummary(warehouses: { name: string; type: string }[], context: DiscoveryContext): Promise<string> {
180+
const deadline = Date.now() + SUMMARY_DEADLINE_MS
181+
const timeLeft = () => deadline - Date.now()
182+
const budget = { tables: TABLE_BUDGET, columns: 0, samples: 0 }
183+
const lines: string[] = []
184+
let bytes = 0
185+
const shown = warehouses.filter((warehouse) => !isScratch(warehouse.name)).slice(0, MAX_CONNECTIONS)
186+
for (const [index, warehouse] of shown.entries()) {
187+
const head = `- ${warehouse.name} (${warehouse.type})`
188+
// Keep room for a name-only line for every connection still to come.
189+
const reserve = shown.slice(index + 1).reduce((total, next) => total + next.name.length + next.type.length + 8, 0)
190+
let line = head
191+
const config = Registry.getConfig(warehouse.name)
192+
if (isLocalConnection(config) && timeLeft() > 0) {
193+
context.signal.throwIfAborted()
194+
const type = Registry.canonicalType(config?.type) ?? ""
195+
const tables = await listTables(warehouse.name, type, budget, context, timeLeft).catch(() => {
196+
context.signal.throwIfAborted()
197+
return undefined
198+
})
199+
if (tables?.length) {
200+
const names = tables.map((table) => (table.schema && table.schema !== "main" ? `${table.schema}.${table.name}` : table.name))
201+
const full = `${head}: ${names.join(", ")}`
202+
if (bytes + Buffer.byteLength(full, "utf8") + 1 + reserve <= SUMMARY_BYTES) line = full
203+
}
204+
}
205+
if (bytes + Buffer.byteLength(line, "utf8") + 1 > SUMMARY_BYTES) break
206+
lines.push(line)
207+
bytes += Buffer.byteLength(line, "utf8") + 1
208+
}
209+
if (lines.length < warehouses.filter((warehouse) => !isScratch(warehouse.name)).length) lines.push("- (more: warehouse_list)")
210+
return lines.join("\n")
211+
}
212+
171213
/** The connection's tables in name order, or undefined when the catalog exceeds the remaining table budget. */
172214
async function listTables(
173215
warehouse: string,

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

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,10 @@ function text(result: Awaited<ReturnType<Client["callTool"]>>) {
6565
mcpTest("initialize result carries short analyst-method instructions", async () => {
6666
const { client } = await fixture()
6767
const instructions = client.getInstructions()
68-
expect(instructions).toBe(SERVER_INSTRUCTIONS)
69-
expect(instructions!.split(/\s+/).length).toBeLessThanOrEqual(120)
68+
expect(instructions!.startsWith(SERVER_INSTRUCTIONS)).toBe(true)
69+
// The connection list known at startup follows the method, so no warehouse_list call is needed to start.
70+
expect(instructions).toContain("Connections:\n- source (sqlite): items")
71+
expect(SERVER_INSTRUCTIONS.split(/\s+/).length).toBeLessThanOrEqual(120)
7072
for (const tool of ["warehouse_list", "warehouse_add", "sql_execute", "sql_materialize", "answer_commit"]) {
7173
expect(instructions).toContain(tool)
7274
}
@@ -89,7 +91,7 @@ mcpTest("the default toolset is five tools; sql_execute `tables` describes table
8991
0,
9092
)
9193
expect(declared).toBeLessThan(5_200)
92-
expect(client.getInstructions()!.length).toBeLessThanOrEqual(600)
94+
expect(SERVER_INSTRUCTIONS.length).toBeLessThanOrEqual(620)
9395
const sqlExecute = listed.tools.find((t) => t.name === "sql_execute")!
9496
expect(Object.keys(sqlExecute.inputSchema.properties ?? {})).toContain("tables")
9597
const fused = await call("sql_execute", {
@@ -473,6 +475,9 @@ mcpTest("shared truncation honors configured limits and preserves failure wordin
473475
for (const allowWrite of [false, true]) {
474476
mcpTest(`DuckDB hidden function writes reach the database read-only guard (allow-write=${allowWrite})`, async () => {
475477
const { call } = await fixture(allowWrite)
478+
// The server opened the fixture's SQLite connector to list its tables at startup; start from a clean registry.
479+
await Registry.closeAll()
480+
Registry.reset()
476481
Registry.setConfigs({ source: { type: "duckdb", path: ":memory:" } })
477482
const connector = await Registry.get("source")
478483
await connector.execute("CREATE SEQUENCE source_sequence")
@@ -1265,3 +1270,15 @@ mcpTest("a failing batch step fails its dependents and the remaining steps still
12651270
expect(block(body, "ok")).toContain("42")
12661271
})
12671272
// altimate_change end
1273+
1274+
// altimate_change start — startup connection list in the instructions stays bounded
1275+
mcpTest("a large catalog is listed by connection name only and the instructions stay within the cap", async () => {
1276+
const { client } = await fixture(false, {}, undefined, (db) => {
1277+
for (let i = 0; i < 60; i++) db.run(`CREATE TABLE wide_table_with_a_long_name_${i} (id INTEGER)`)
1278+
})
1279+
const instructions = client.getInstructions()!
1280+
expect(instructions).toContain("Connections:\n- source (sqlite)")
1281+
expect(instructions).not.toContain("wide_table_with_a_long_name_0")
1282+
expect(instructions.length - SERVER_INSTRUCTIONS.length).toBeLessThanOrEqual(1_250)
1283+
})
1284+
// altimate_change end

0 commit comments

Comments
 (0)