import { z } from 'zod';
export const DEFAULT_GHL_BASE_URL = 'https://services.leadconnectorhq.com';
export const configSchema = z.object({
ghlApiKey: z
.string({ required_error: 'ghlApiKey is required' })
.trim()
.min(1, 'ghlApiKey is required'),
ghlLocationId: z
.string({ required_error: 'ghlLocationId is required' })
.trim()
.min(1, 'ghlLocationId is required'),
ghlBaseUrl: z
.string()
.trim()
.url({ message: 'ghlBaseUrl must be a valid URL' })
.optional(),
});
export type SmitheryConfig = z.infer<typeof configSchema>;
function coalesceString(value: unknown | undefined | null): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
return undefined;
}
export function resolveConfig(
env: NodeJS.ProcessEnv = process.env,
overrides: Partial<SmitheryConfig> = {}
): SmitheryConfig {
let smitheryOverrides: Partial<SmitheryConfig> = {};
const smitheryConfigRaw = coalesceString(env.SMITHERY_CONFIG) ?? coalesceString(env.MCP_CONFIG);
if (smitheryConfigRaw) {
try {
const parsed = JSON.parse(smitheryConfigRaw) as Record<string, unknown>;
smitheryOverrides = {
ghlApiKey: coalesceString(parsed.ghlApiKey) ?? undefined,
ghlLocationId: coalesceString(parsed.ghlLocationId) ?? undefined,
ghlBaseUrl: coalesceString(parsed.ghlBaseUrl) ?? undefined,
};
} catch (error) {
throw new Error(`Failed to parse Smithery configuration: ${error}`);
}
}
const merged: SmitheryConfig = configSchema.parse({
ghlApiKey:
coalesceString(overrides.ghlApiKey) ??
coalesceString(smitheryOverrides.ghlApiKey) ??
coalesceString(env.ghlApiKey) ??
coalesceString(env.GHL_API_KEY),
ghlLocationId:
coalesceString(overrides.ghlLocationId) ??
coalesceString(smitheryOverrides.ghlLocationId) ??
coalesceString(env.ghlLocationId) ??
coalesceString(env.GHL_LOCATION_ID),
ghlBaseUrl:
coalesceString(overrides.ghlBaseUrl) ??
coalesceString(smitheryOverrides.ghlBaseUrl) ??
coalesceString(env.ghlBaseUrl) ??
coalesceString(env.GHL_BASE_URL),
});
return {
...merged,
ghlBaseUrl: merged.ghlBaseUrl ?? DEFAULT_GHL_BASE_URL,
};
}