|
| 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 | +} |
0 commit comments