UNPKG

@code-yeongyu/senpi

Version:

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

180 lines • 7.92 kB
import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { CONFIG_DIR_NAME, getAgentDir } from "../../../../config.js"; import { McpConfigValidationError } from "./config-error.js"; import { hashConfig } from "./config-identity.js"; import { interpolateValue } from "./config-interpolation.js"; import { normalizeServer } from "./config-normalize.js"; import { rememberMcpReferenceOrigins } from "./config-references.js"; import { defaultSettings, getServerEndpointValidationError, validateConfig, } from "./config-schema.js"; import { inheritMcpSharingScope } from "./sharing-policy.js"; export { McpConfigValidationError } from "./config-error.js"; export { mergeExtensionMcpServers, resolveExtensionMcpServer } from "./config-extension.js"; export { hashConfig } from "./config-identity.js"; export { interpolateValue } from "./config-interpolation.js"; export { normalizeServer } from "./config-normalize.js"; const trustedEnv = process.env; export function loadMcpConfig(options) { const agentDir = options.agentDir ?? getAgentDir(); const env = options.env ?? trustedEnv; const globalPath = join(agentDir, "mcp.json"); const projectPath = join(options.cwd, CONFIG_DIR_NAME, "mcp.json"); const claudePath = join(options.cwd, ".mcp.json"); const globalConfig = readTrustedConfig(globalPath, env); const projectRead = readConfigJson(projectPath, options.projectTrusted); const projectRaw = projectRead.raw; const preliminary = mergeConfigs(globalConfig, options.projectTrusted ? validateRaw(projectRaw, projectPath) : undefined); const shouldImportClaude = preliminary.settings?.importConfigs?.includes("claude") === true; const claudeRead = shouldImportClaude ? readConfigJson(claudePath, options.projectTrusted) : { raw: undefined }; const claudeRaw = claudeRead.raw; const sources = [ { config: globalConfig, path: globalPath, source: "global", trusted: true }, { config: options.projectTrusted && shouldImportClaude ? readTrustedConfig(claudePath, env, claudeRaw) : undefined, path: claudePath, source: "claude", trusted: options.projectTrusted, }, { config: options.projectTrusted ? readTrustedConfig(projectPath, env, projectRaw) : undefined, path: projectPath, source: "project", trusted: options.projectTrusted, }, ]; const merged = mergeConfigs(...sources.map((item) => item.config)); const result = { diagnostics: [], servers: {}, settings: normalizeSettings(merged.settings) }; for (const diagnostic of [projectRead.diagnostic, claudeRead.diagnostic]) { if (diagnostic) result.diagnostics.push(diagnostic); } for (const item of sources) { if (item.trusted && item.config?.mcpServers) { addTrustedServers(result, item.config.mcpServers, { source: item.source, sourcePath: item.path, agentDir }); continue; } if (!item.trusted) { addUntrustedServers(result, readServerNames(item.source === "claude" ? claudeRaw : projectRaw), item.source, item.path); } } return result; } export function visitSpawnableMcpServers(config, visit) { for (const [name, server] of Object.entries(config.servers)) { if (server.state === "enabled") { visit(name, server); } } } function readTrustedConfig(path, env, raw = readConfigJson(path, true).raw) { const config = resolveTrustedConfig(raw, path, env); rememberMcpReferenceOrigins(config?.mcpServers, path); return config; } /** * Throws the `McpConfigValidationError` loading `raw` as the trusted file at `path` would throw, without loading it: * a candidate is checked with the loader's own steps before anything writes it (senpi#6485). */ export function assertLoadableMcpConfig(raw, path, env = trustedEnv) { resolveTrustedConfig(raw, path, env); } function resolveTrustedConfig(raw, path, env) { const config = interpolateConfig(validateRaw(raw, path), env); const endpointError = config ? getServerEndpointValidationError(config) : undefined; if (endpointError) throw new McpConfigValidationError(`Invalid MCP config at ${endpointError}`); return config; } function readConfigJson(path, trusted) { if (!existsSync(path)) return { raw: undefined }; try { const raw = JSON.parse(readFileSync(path, "utf-8")); return { raw }; } catch (error) { const reason = error instanceof Error ? error.message : String(error); if (trusted) throw new McpConfigValidationError(`Invalid MCP config at ${path}: ${reason}`); return { raw: undefined, diagnostic: `Blocked untrusted MCP config at ${path}: invalid JSON (${reason})` }; } } function validateRaw(raw, _path) { if (raw === undefined) return undefined; if (validateConfig.Check(raw)) { const config = raw; const endpointError = getServerEndpointValidationError(config); if (endpointError) throw new McpConfigValidationError(`Invalid MCP config at ${endpointError}`); return config; } const error = Array.from(validateConfig.Errors(raw))[0]; throw new McpConfigValidationError(`Invalid MCP config at ${formatErrorPath(error)}: ${formatErrorMessage(error)}`); } function formatErrorPath(error) { const trimmed = error.instancePath.replace(/^\//, ""); return trimmed.length === 0 ? "$" : trimmed.split("/").map(decodePathPart).join("."); } function decodePathPart(part) { return part.replace(/~1/g, "/").replace(/~0/g, "~"); } function formatErrorMessage(error) { return error.message === "must be array" ? "Expected array" : error.message; } function mergeConfigs(...configs) { const merged = {}; for (const config of configs) { if (!config) continue; merged.settings = { ...(merged.settings ?? {}), ...(config.settings ?? {}) }; merged.mcpServers = { ...(merged.mcpServers ?? {}), ...(config.mcpServers ?? {}) }; } return merged; } function normalizeSettings(settings) { return { ...defaultSettings, ...settings }; } function addTrustedServers(result, servers, origin) { for (const [name, server] of Object.entries(servers)) { const config = normalizeServer(server); inheritMcpSharingScope(server, config); result.servers[name] = { config, configHash: hashConfig(config, origin.agentDir), name, source: origin.source, sourcePath: origin.sourcePath, state: config.enabled ? "enabled" : "disabled", transport: config.type, }; } } function addUntrustedServers(result, names, source, sourcePath) { for (const name of names) { const existing = result.servers[name]; if (existing && existing.state !== "untrusted") { result.diagnostics.push(`Blocked untrusted ${source} MCP server '${name}' from shadowing trusted ${existing.source} server.`); continue; } result.servers[name] = { name, source, sourcePath, state: "untrusted" }; } } function readServerNames(raw) { if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return []; const servers = raw.mcpServers; if (typeof servers !== "object" || servers === null || Array.isArray(servers)) return []; return Object.keys(servers); } function interpolateConfig(config, env) { const resolved = interpolateValue(config, "mcp", env); for (const [name, raw] of Object.entries(config?.mcpServers ?? {})) { const server = resolved?.mcpServers?.[name]; if (server !== undefined) inheritMcpSharingScope(raw, server); } return resolved; } //# sourceMappingURL=config.js.map