UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

184 lines • 7.28 kB
import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { getAgentDir } from "../../../../config.js"; import { redactResolvedReferenceData } from "../../../config-reference-redaction.js"; import { lockWithLossHandling } from "../../../file-lock.js"; import { isEphemeralIdentity } from "./config-identity-key.js"; import { collectAllPages } from "./expose/pagination.js"; import { listMcpTools } from "./tool-client.js"; import { isModernMcpClient } from "./modern/request.js"; import { hasSupportedModernToolSchemas } from "./modern/tool-schema.js"; const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; const EMPTY_CACHE = { version: 1, servers: {} }; export function getMcpCatalogCachePath(agentDir = getAgentDir()) { return join(agentDir, "cache", "mcp-cache.json"); } export async function readMcpCatalogCache(agentDir) { try { const parsed = JSON.parse(await readFile(getMcpCatalogCachePath(agentDir), "utf8")); return normalizeCacheFile(parsed); } catch { return EMPTY_CACHE; } } export function getValidCachedServer(cache, serverName, configHash, credentialIdentity = "none") { const cached = cache.servers[serverName]; if (cached === undefined) return undefined; if (cached.configHash !== configHash) return undefined; if (cached.credentialIdentity !== credentialIdentity && !(credentialIdentity === "none" && cached.credentialIdentity === undefined)) { return undefined; } return cached; } export function cachedCatalogNeedsRefresh(cached, now = Date.now()) { return now - cached.fetchedAt > CACHE_TTL_MS; } export async function collectServerCatalogForCache(connection, config, configHash, credentialIdentity) { const client = connection.client; const tools = await collectAllPages((cursor) => listMcpTools(client, cursor === undefined ? {} : { cursor }, { timeout: config.requestTimeoutMs, })); const resources = await collectOptionalPages((cursor) => client.listResources(cursor === undefined ? {} : { cursor }, { timeout: config.requestTimeoutMs, })); const prompts = await collectOptionalPages((cursor) => client.listPrompts(cursor === undefined ? {} : { cursor }, { timeout: config.requestTimeoutMs, })); const resourceTemplates = await collectOptionalPages((cursor) => client.listResourceTemplates(cursor === undefined ? {} : { cursor }, { timeout: config.requestTimeoutMs, })); return { configHash, ...(isModernMcpClient(client) ? { modern: true } : {}), credentialIdentity, fetchedAt: Date.now(), instructions: client.getInstructions(), prompts, resources, resourceTemplates, tools: tools.items, }; } export async function writeMcpCachedServer(agentDir, serverName, server, isCurrent) { // Without a valid installation key nothing keyed is persisted (senpi#3858). if (isEphemeralIdentity(server.configHash) || isEphemeralIdentity(server.credentialIdentity)) return; if (isCurrent?.() === false) return; const path = getMcpCatalogCachePath(agentDir); await mkdir(dirname(path), { recursive: true }); const lock = await lockWithLossHandling(dirname(path), { lockfilePath: `${path}.lock`, realpath: false, retries: { retries: 50, factor: 1.2, minTimeout: 20, maxTimeout: 200 }, stale: 30_000, }); try { if (isCurrent?.() === false) return; const cache = await readMcpCatalogCache(agentDir); if (isCurrent?.() === false) return; const persisted = redactResolvedReferenceData(server); const next = { version: 1, servers: { ...cache.servers, [serverName]: persisted }, }; await atomicWriteJson(path, next, isCurrent, lock.assertHeld); } finally { await lock.release(); } } async function collectOptionalPages(listFn) { try { const result = await collectAllPages((cursor) => listFn(cursor)); return result.items; } catch { return []; } } async function atomicWriteJson(path, value, isCurrent, assertHeld) { await mkdir(dirname(path), { recursive: true }); const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`; try { await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8"); if (isCurrent?.() === false) return; assertHeld?.(); await rename(tmp, path); } finally { await rm(tmp, { force: true }); } } function normalizeCacheFile(value) { if (!isRecord(value) || value.version !== 1 || !isRecord(value.servers)) return EMPTY_CACHE; const servers = {}; for (const [name, server] of Object.entries(value.servers)) { const normalized = normalizeCachedServer(server); if (normalized !== undefined) servers[name] = normalized; } return { version: 1, servers }; } function normalizeCachedServer(value) { if (!isRecord(value) || typeof value.configHash !== "string" || typeof value.fetchedAt !== "number") { return undefined; } const tools = normalizeTools(value.tools, value.modern === true); if (tools === undefined) return undefined; const resources = Array.isArray(value.resources) ? value.resources : []; const prompts = Array.isArray(value.prompts) ? value.prompts : []; const resourceTemplates = Array.isArray(value.resourceTemplates) ? value.resourceTemplates : []; const instructions = typeof value.instructions === "string" ? value.instructions : undefined; return { configHash: value.configHash, ...(value.modern === true ? { modern: true } : {}), credentialIdentity: typeof value.credentialIdentity === "string" ? value.credentialIdentity : undefined, fetchedAt: value.fetchedAt, instructions, prompts, resources, resourceTemplates, tools, }; } function normalizeTools(value, modern) { if (!Array.isArray(value)) return undefined; const tools = []; for (const item of value) { if (!isRecord(item) || typeof item.name !== "string") return undefined; if (!isRecord(item.inputSchema) && !(modern && typeof item.inputSchema === "boolean")) return undefined; const tool = { ...(modern ? item : {}), annotations: isRecord(item.annotations) ? item.annotations : undefined, description: typeof item.description === "string" ? item.description : undefined, inputSchema: item.inputSchema, ...(modern && (isRecord(item.outputSchema) || typeof item.outputSchema === "boolean") ? { outputSchema: item.outputSchema } : {}), name: item.name, }; if (!modern || hasSupportedModernToolSchemas(tool)) tools.push(tool); } return tools; } function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } //# sourceMappingURL=catalog-cache.js.map