|
| 1 | +import type { UserConfig } from "./userConfig.js"; |
| 2 | +import { UserConfigSchema, configRegistry } from "./userConfig.js"; |
| 3 | +import type { RequestContext } from "../../transports/base.js"; |
| 4 | +import type { OverrideBehavior } from "./configUtils.js"; |
| 5 | + |
| 6 | +export const CONFIG_HEADER_PREFIX = "x-mongodb-mcp-"; |
| 7 | +export const CONFIG_QUERY_PREFIX = "mongodbMcp"; |
| 8 | + |
| 9 | +/** |
| 10 | + * Applies config overrides from request context (headers and query parameters). |
| 11 | + * Query parameters take precedence over headers. |
| 12 | + * |
| 13 | + * @param baseConfig - The base user configuration |
| 14 | + * @param request - The request context containing headers and query parameters |
| 15 | + * @returns The configuration with overrides applied |
| 16 | + */ |
| 17 | +export function applyConfigOverrides({ |
| 18 | + baseConfig, |
| 19 | + request, |
| 20 | +}: { |
| 21 | + baseConfig: UserConfig; |
| 22 | + request?: RequestContext; |
| 23 | +}): UserConfig { |
| 24 | + if (!request) { |
| 25 | + return baseConfig; |
| 26 | + } |
| 27 | + |
| 28 | + const result: UserConfig = { ...baseConfig }; |
| 29 | + const overridesFromHeaders = extractConfigOverrides("header", request.headers); |
| 30 | + const overridesFromQuery = extractConfigOverrides("query", request.query); |
| 31 | + |
| 32 | + // Merge overrides, with query params taking precedence |
| 33 | + const allOverrides = { ...overridesFromHeaders, ...overridesFromQuery }; |
| 34 | + |
| 35 | + // Apply each override according to its behavior |
| 36 | + for (const [key, overrideValue] of Object.entries(allOverrides)) { |
| 37 | + assertValidConfigKey(key); |
| 38 | + const behavior = getConfigMeta(key)?.overrideBehavior || "not-allowed"; |
| 39 | + const baseValue = baseConfig[key as keyof UserConfig]; |
| 40 | + const newValue = applyOverride(key, baseValue, overrideValue, behavior); |
| 41 | + (result as any)[key] = newValue; |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | +} |
| 46 | + |
| 47 | +/** |
| 48 | + * Extracts config overrides from HTTP headers or query parameters. |
| 49 | + */ |
| 50 | +function extractConfigOverrides( |
| 51 | + mode: "header" | "query", |
| 52 | + source: Record<string, string | string[] | undefined> | undefined |
| 53 | +): Partial<Record<keyof typeof UserConfigSchema.shape, unknown>> { |
| 54 | + if (!source) { |
| 55 | + return {}; |
| 56 | + } |
| 57 | + |
| 58 | + const overrides: Partial<Record<keyof typeof UserConfigSchema.shape, unknown>> = {}; |
| 59 | + |
| 60 | + for (const [name, value] of Object.entries(source)) { |
| 61 | + const configKey = nameToConfigKey(mode, name); |
| 62 | + if (!configKey) { |
| 63 | + continue; |
| 64 | + } |
| 65 | + assertValidConfigKey(configKey); |
| 66 | + |
| 67 | + const behavior = getConfigMeta(configKey)?.overrideBehavior || "not-allowed"; |
| 68 | + if (behavior === "not-allowed") { |
| 69 | + throw new Error(`Config key ${configKey} is not allowed to be overridden`); |
| 70 | + } |
| 71 | + |
| 72 | + const parsedValue = parseConfigValue(configKey, value); |
| 73 | + if (parsedValue !== undefined) { |
| 74 | + overrides[configKey] = parsedValue; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return overrides; |
| 79 | +} |
| 80 | + |
| 81 | +function assertValidConfigKey(key: string): asserts key is keyof typeof UserConfigSchema.shape { |
| 82 | + if (!(key in UserConfigSchema.shape)) { |
| 83 | + throw new Error(`Invalid config key: ${key}`); |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +/** |
| 88 | + * Gets the schema metadata for a config key. |
| 89 | + */ |
| 90 | +export function getConfigMeta(key: keyof typeof UserConfigSchema.shape) { |
| 91 | + return configRegistry.get(UserConfigSchema.shape[key]); |
| 92 | +} |
| 93 | + |
| 94 | +/** |
| 95 | + * Parses a string value to the appropriate type using the Zod schema. |
| 96 | + */ |
| 97 | +function parseConfigValue(key: keyof typeof UserConfigSchema.shape, value: unknown): unknown { |
| 98 | + const fieldSchema = UserConfigSchema.shape[key as keyof typeof UserConfigSchema.shape]; |
| 99 | + if (!fieldSchema) { |
| 100 | + throw new Error(`Invalid config key: ${key}`); |
| 101 | + } |
| 102 | + |
| 103 | + return fieldSchema.safeParse(value).data; |
| 104 | +} |
| 105 | + |
| 106 | +/** |
| 107 | + * Converts a header/query name to its config key format. |
| 108 | + * Example: "x-mongodb-mcp-read-only" -> "readOnly" |
| 109 | + * Example: "mongodbMcpReadOnly" -> "readOnly" |
| 110 | + */ |
| 111 | +export function nameToConfigKey(mode: "header" | "query", name: string): string | undefined { |
| 112 | + const lowerCaseName = name.toLowerCase(); |
| 113 | + |
| 114 | + if (mode === "header" && lowerCaseName.startsWith(CONFIG_HEADER_PREFIX)) { |
| 115 | + const normalized = lowerCaseName.substring(CONFIG_HEADER_PREFIX.length); |
| 116 | + // Convert kebab-case to camelCase |
| 117 | + return normalized.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()); |
| 118 | + } |
| 119 | + if (mode === "query" && name.startsWith(CONFIG_QUERY_PREFIX)) { |
| 120 | + const withoutPrefix = name.substring(CONFIG_QUERY_PREFIX.length); |
| 121 | + // Convert first letter to lowercase to get config key |
| 122 | + return withoutPrefix.charAt(0).toLowerCase() + withoutPrefix.slice(1); |
| 123 | + } |
| 124 | + |
| 125 | + return undefined; |
| 126 | +} |
| 127 | + |
| 128 | +function applyOverride( |
| 129 | + key: keyof typeof UserConfigSchema.shape, |
| 130 | + baseValue: unknown, |
| 131 | + overrideValue: unknown, |
| 132 | + behavior: OverrideBehavior |
| 133 | +): unknown { |
| 134 | + if (typeof behavior === "function") { |
| 135 | + const shouldApply = behavior(baseValue, overrideValue); |
| 136 | + if (!shouldApply) { |
| 137 | + throw new Error( |
| 138 | + `Config override validation failed for ${key}: cannot override from ${JSON.stringify(baseValue)} to ${JSON.stringify(overrideValue)}` |
| 139 | + ); |
| 140 | + } |
| 141 | + return overrideValue; |
| 142 | + } |
| 143 | + switch (behavior) { |
| 144 | + case "override": |
| 145 | + return overrideValue; |
| 146 | + |
| 147 | + case "merge": |
| 148 | + if (Array.isArray(baseValue) && Array.isArray(overrideValue)) { |
| 149 | + return [...baseValue, ...overrideValue]; |
| 150 | + } |
| 151 | + throw new Error("Cannot merge non-array values, did you mean to use the 'override' behavior?"); |
| 152 | + |
| 153 | + case "not-allowed": |
| 154 | + default: |
| 155 | + return baseValue; |
| 156 | + } |
| 157 | +} |
0 commit comments