fix: enhance environment variable handling in replaceEnvVars and expandEnvVars functions (#149)

Co-authored-by: samanhappy@qq.com <my6051199>
This commit is contained in:
samanhappy
2025-05-31 08:41:20 +08:00
committed by GitHub
parent bfc184afc6
commit 394945bbc5
2 changed files with 18 additions and 5 deletions

View File

@@ -44,13 +44,24 @@ export const saveSettings = (settings: McpSettings): boolean => {
export const replaceEnvVars = (env: Record<string, any>): Record<string, any> => {
const res: Record<string, string> = {};
for (const [key, value] of Object.entries(env)) {
res[key] = expandEnvVars(value);
if (typeof value === 'string') {
res[key] = expandEnvVars(value);
} else {
res[key] = String(value);
}
}
return res;
};
export const expandEnvVars = (value: string): string => {
return value.replace(/\$\{([^}]+)\}/g, (_, key) => process.env[key] || '');
if (typeof value !== 'string') {
return String(value);
}
// Replace ${VAR} format
let result = value.replace(/\$\{([^}]+)\}/g, (_, key) => process.env[key] || '');
// Also replace $VAR format (common on Unix-like systems)
result = result.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_, key) => process.env[key] || '');
return result;
};
export default defaultConfig;

View File

@@ -93,9 +93,11 @@ export const initializeClientsFromSettings = (isInit: boolean): ServerInfo[] =>
} else if (conf.url) {
// Default to SSE only when 'conf.type' is not specified and 'conf.url' is available
transport = new SSEClientTransport(new URL(conf.url));
} else if (conf.command && conf.args) {
// If type is stdio or if command and args are provided without type
const env: Record<string, string> = replaceEnvVars(conf.env || {});
} else if (conf.command && conf.args) { // If type is stdio or if command and args are provided without type
const env: Record<string, string> = {
...(process.env as Record<string, string>), // Inherit all environment variables from parent process
...replaceEnvVars(conf.env || {}), // Override with configured env vars
};
env['PATH'] = expandEnvVars(process.env.PATH as string) || '';
// Add UV_DEFAULT_INDEX from settings if available (for Python packages)