配置MCP Server时,env中填写的${xxx}值可以从环境变量中读取 (#135)

This commit is contained in:
Oven
2025-05-30 23:02:34 +08:00
committed by GitHub
parent 63c55875b5
commit 1acacfab88
2 changed files with 10 additions and 2 deletions

View File

@@ -41,6 +41,14 @@ 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);
}
return res;
};
export const expandEnvVars = (value: string): string => {
return value.replace(/\$\{([^}]+)\}/g, (_, key) => process.env[key] || '');
};

View File

@@ -5,7 +5,7 @@ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { ServerInfo, ServerConfig } from '../types/index.js';
import { loadSettings, saveSettings, expandEnvVars } from '../config/index.js';
import { loadSettings, saveSettings, expandEnvVars, replaceEnvVars } from '../config/index.js';
import config from '../config/index.js';
import { getGroup } from './sseService.js';
import { getServersInGroup } from './groupService.js';
@@ -95,7 +95,7 @@ export const initializeClientsFromSettings = (isInit: boolean): ServerInfo[] =>
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> = conf.env || {};
const env: Record<string, string> = replaceEnvVars(conf.env || {});
env['PATH'] = expandEnvVars(process.env.PATH as string) || '';
// Add UV_DEFAULT_INDEX from settings if available (for Python packages)