|
| 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 { ConfigFieldMeta, 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. Can be used within the createSessionConfig |
| 12 | + * hook to manually apply the overrides. Requires `allowRequestOverrides` to be enabled. |
| 13 | + * |
| 14 | + * @param baseConfig - The base user configuration |
| 15 | + * @param request - The request context containing headers and query parameters |
| 16 | + * @returns The configuration with overrides applied |
| 17 | + */ |
| 18 | +export function applyConfigOverrides({ |
| 19 | + baseConfig, |
| 20 | + request, |
| 21 | +}: { |
| 22 | + baseConfig: UserConfig; |
| 23 | + request?: RequestContext; |
| 24 | +}): UserConfig { |
| 25 | + if (!request) { |
| 26 | + return baseConfig; |
| 27 | + } |
| 28 | + |
| 29 | + const result: UserConfig = { ...baseConfig }; |
| 30 | + const overridesFromHeaders = extractConfigOverrides("header", request.headers); |
| 31 | + const overridesFromQuery = extractConfigOverrides("query", request.query); |
| 32 | + |
| 33 | + // Only apply overrides if allowRequestOverrides is enabled |
| 34 | + if ( |
| 35 | + !baseConfig.allowRequestOverrides && |
| 36 | + (Object.keys(overridesFromHeaders).length > 0 || Object.keys(overridesFromQuery).length > 0) |
| 37 | + ) { |
| 38 | + throw new Error("Request overrides are not enabled"); |
| 39 | + } |
| 40 | + |
| 41 | + // Apply header overrides first |
| 42 | + for (const [key, overrideValue] of Object.entries(overridesFromHeaders)) { |
| 43 | + assertValidConfigKey(key); |
| 44 | + const meta = getConfigMeta(key); |
| 45 | + const behavior = meta?.overrideBehavior || "not-allowed"; |
| 46 | + const baseValue = baseConfig[key as keyof UserConfig]; |
| 47 | + const newValue = applyOverride(key, baseValue, overrideValue, behavior); |
| 48 | + (result as Record<keyof UserConfig, unknown>)[key] = newValue; |
| 49 | + } |
| 50 | + |
| 51 | + // Apply query overrides (with precedence), but block secret fields |
| 52 | + for (const [key, overrideValue] of Object.entries(overridesFromQuery)) { |
| 53 | + assertValidConfigKey(key); |
| 54 | + const meta = getConfigMeta(key); |
| 55 | + |
| 56 | + // Prevent overriding secret fields via query params |
| 57 | + if (meta?.isSecret) { |
| 58 | + throw new Error(`Config key ${key} can only be overriden with headers.`); |
| 59 | + } |
| 60 | + |
| 61 | + const behavior = meta?.overrideBehavior || "not-allowed"; |
| 62 | + const baseValue = baseConfig[key as keyof UserConfig]; |
| 63 | + const newValue = applyOverride(key, baseValue, overrideValue, behavior); |
| 64 | + (result as Record<keyof UserConfig, unknown>)[key] = newValue; |
| 65 | + } |
| 66 | + |
| 67 | + return result; |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Extracts config overrides from HTTP headers or query parameters. |
| 72 | + */ |
| 73 | +function extractConfigOverrides( |
| 74 | + mode: "header" | "query", |
| 75 | + source: Record<string, string | string[] | undefined> | undefined |
| 76 | +): Partial<Record<keyof typeof UserConfigSchema.shape, unknown>> { |
| 77 | + if (!source) { |
| 78 | + return {}; |
| 79 | + } |
| 80 | + |
| 81 | + const overrides: Partial<Record<keyof typeof UserConfigSchema.shape, unknown>> = {}; |
| 82 | + |
| 83 | + for (const [name, value] of Object.entries(source)) { |
| 84 | + const configKey = nameToConfigKey(mode, name); |
| 85 | + if (!configKey) { |
| 86 | + continue; |
| 87 | + } |
| 88 | + assertValidConfigKey(configKey); |
| 89 | + |
| 90 | + const parsedValue = parseConfigValue(configKey, value); |
| 91 | + if (parsedValue !== undefined) { |
| 92 | + overrides[configKey] = parsedValue; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return overrides; |
| 97 | +} |
| 98 | + |
| 99 | +function assertValidConfigKey(key: string): asserts key is keyof typeof UserConfigSchema.shape { |
| 100 | + if (!(key in UserConfigSchema.shape)) { |
| 101 | + throw new Error(`Invalid config key: ${key}`); |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +/** |
| 106 | + * Gets the schema metadata for a config key. |
| 107 | + */ |
| 108 | +export function getConfigMeta(key: keyof typeof UserConfigSchema.shape): ConfigFieldMeta | undefined { |
| 109 | + return configRegistry.get(UserConfigSchema.shape[key]); |
| 110 | +} |
| 111 | + |
| 112 | +/** |
| 113 | + * Parses a string value to the appropriate type using the Zod schema. |
| 114 | + */ |
| 115 | +function parseConfigValue(key: keyof typeof UserConfigSchema.shape, value: unknown): unknown { |
| 116 | + const fieldSchema = UserConfigSchema.shape[key]; |
| 117 | + if (!fieldSchema) { |
| 118 | + throw new Error(`Invalid config key: ${key}`); |
| 119 | + } |
| 120 | + |
| 121 | + return fieldSchema.safeParse(value).data; |
| 122 | +} |
| 123 | + |
| 124 | +/** |
| 125 | + * Converts a header/query name to its config key format. |
| 126 | + * Example: "x-mongodb-mcp-read-only" -> "readOnly" |
| 127 | + * Example: "mongodbMcpReadOnly" -> "readOnly" |
| 128 | + */ |
| 129 | +export function nameToConfigKey(mode: "header" | "query", name: string): string | undefined { |
| 130 | + const lowerCaseName = name.toLowerCase(); |
| 131 | + |
| 132 | + if (mode === "header" && lowerCaseName.startsWith(CONFIG_HEADER_PREFIX)) { |
| 133 | + const normalized = lowerCaseName.substring(CONFIG_HEADER_PREFIX.length); |
| 134 | + // Convert kebab-case to camelCase |
| 135 | + return normalized.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase()); |
| 136 | + } |
| 137 | + if (mode === "query" && name.startsWith(CONFIG_QUERY_PREFIX)) { |
| 138 | + const withoutPrefix = name.substring(CONFIG_QUERY_PREFIX.length); |
| 139 | + // Convert first letter to lowercase to get config key |
| 140 | + return withoutPrefix.charAt(0).toLowerCase() + withoutPrefix.slice(1); |
| 141 | + } |
| 142 | + |
| 143 | + return undefined; |
| 144 | +} |
| 145 | + |
| 146 | +function applyOverride( |
| 147 | + key: keyof typeof UserConfigSchema.shape, |
| 148 | + baseValue: unknown, |
| 149 | + overrideValue: unknown, |
| 150 | + behavior: OverrideBehavior |
| 151 | +): unknown { |
| 152 | + if (typeof behavior === "function") { |
| 153 | + // Custom logic function returns the value to use (potentially transformed) |
| 154 | + // or throws an error if the override cannot be applied |
| 155 | + try { |
| 156 | + return behavior(baseValue, overrideValue); |
| 157 | + } catch (error) { |
| 158 | + throw new Error( |
| 159 | + `Cannot apply override for ${key}: ${error instanceof Error ? error.message : String(error)}` |
| 160 | + ); |
| 161 | + } |
| 162 | + } |
| 163 | + switch (behavior) { |
| 164 | + case "override": |
| 165 | + return overrideValue; |
| 166 | + |
| 167 | + case "merge": |
| 168 | + if (Array.isArray(baseValue) && Array.isArray(overrideValue)) { |
| 169 | + return [...(baseValue as unknown[]), ...(overrideValue as unknown[])]; |
| 170 | + } |
| 171 | + throw new Error(`Cannot merge non-array values for ${key}`); |
| 172 | + |
| 173 | + case "not-allowed": |
| 174 | + throw new Error(`Config key ${key} is not allowed to be overridden`); |
| 175 | + default: |
| 176 | + return baseValue; |
| 177 | + } |
| 178 | +} |
0 commit comments