|
package main |
|
|
|
import ( |
|
"bytes" |
|
"errors" |
|
"fmt" |
|
"os" |
|
"path/filepath" |
|
"strconv" |
|
"strings" |
|
|
|
toml "github.com/pelletier/go-toml" |
|
) |
|
|
|
const ( |
|
defaultStartupTimeout = int64(20000) |
|
configFileName = "config.toml" |
|
) |
|
|
|
var proxyEnvVarNames = []string{ |
|
"http_proxy", |
|
"https_proxy", |
|
"all_proxy", |
|
"no_proxy", |
|
"HTTP_PROXY", |
|
"HTTPS_PROXY", |
|
"ALL_PROXY", |
|
"NO_PROXY", |
|
} |
|
|
|
// main 是命令行入口,负责输出顶层错误并返回非零退出码 |
|
func main() { |
|
if err := run(); err != nil { |
|
fmt.Fprintf(os.Stderr, "setter: %v\n", err) |
|
os.Exit(1) |
|
} |
|
} |
|
|
|
// run 执行读取超时值、定位配置文件、更新配置并写回文件的完整流程 |
|
func run() error { |
|
timeout, err := startupTimeout() |
|
if err != nil { |
|
return err |
|
} |
|
|
|
codexHome, err := codexHome() |
|
if err != nil { |
|
return err |
|
} |
|
|
|
configPath := filepath.Join(codexHome, configFileName) |
|
data, mode, err := readConfig(configPath) |
|
if err != nil { |
|
return err |
|
} |
|
|
|
// 先在内存中计算变更,只有存在实际改动时才写回原文件 |
|
updated, serverCount, changedCount, err := updateStartupTimeout(data, timeout) |
|
if err != nil { |
|
return fmt.Errorf("parse config file %s: %w", configPath, err) |
|
} |
|
// 没有 MCP 服务配置时保持文件不变,避免制造空写入 |
|
if serverCount == 0 { |
|
fmt.Printf("no MCP server sections found in %s\n", configPath) |
|
return nil |
|
} |
|
// 目标配置已经满足要求(不需要进行任何修改)时保持文件原样,避免 TOML 格式被重排 |
|
if changedCount == 0 { |
|
fmt.Printf("%s already has startup_timeout_sec = %d and proxy env_vars in %d MCP server section(s)\n", configPath, timeout, serverCount) |
|
return nil |
|
} |
|
|
|
if err := os.WriteFile(configPath, updated, mode); err != nil { |
|
return fmt.Errorf("write config file %s: %w", configPath, err) |
|
} |
|
|
|
fmt.Printf("updated startup_timeout_sec/env_vars in %d/%d MCP server section(s): %s\n", changedCount, serverCount, configPath) |
|
return nil |
|
} |
|
|
|
// readConfig 读取配置文件内容并返回可用于写回的原始权限 |
|
func readConfig(path string) ([]byte, os.FileMode, error) { |
|
info, err := os.Stat(path) |
|
if err != nil { |
|
if errors.Is(err, os.ErrNotExist) { |
|
return nil, 0, fmt.Errorf("config file not found: %s", path) |
|
} |
|
return nil, 0, fmt.Errorf("stat config file %s: %w", path, err) |
|
} |
|
|
|
data, err := os.ReadFile(path) |
|
if err != nil { |
|
return nil, 0, fmt.Errorf("read config file %s: %w", path, err) |
|
} |
|
|
|
return data, info.Mode().Perm(), nil |
|
} |
|
|
|
// codexHome 返回 Codex 配置目录,优先使用 CODEX_HOME 环境变量 |
|
func codexHome() (string, error) { |
|
if value := strings.TrimSpace(os.Getenv("CODEX_HOME")); value != "" { |
|
return expandHome(value) |
|
} |
|
|
|
home, err := os.UserHomeDir() |
|
if err != nil { |
|
return "", fmt.Errorf("find user home directory: %w", err) |
|
} |
|
return filepath.Join(home, ".codex"), nil |
|
} |
|
|
|
// expandHome 将以波浪线开头的路径展开为当前用户主目录路径 |
|
func expandHome(path string) (string, error) { |
|
if path == "~" || strings.HasPrefix(path, "~/") { |
|
home, err := os.UserHomeDir() |
|
if err != nil { |
|
return "", fmt.Errorf("expand CODEX_HOME: %w", err) |
|
} |
|
if path == "~" { |
|
return home, nil |
|
} |
|
return filepath.Join(home, path[2:]), nil |
|
} |
|
return path, nil |
|
} |
|
|
|
// startupTimeout 返回要写入 MCP 服务配置的启动超时时间 |
|
func startupTimeout() (int64, error) { |
|
value := strings.TrimSpace(os.Getenv("CODEX_MCP_STARTUP_TIMEOUT")) |
|
if value == "" { |
|
return defaultStartupTimeout, nil |
|
} |
|
|
|
// 环境变量必须是正整数,避免写入无效或不可用的超时值 |
|
timeout, err := strconv.ParseInt(value, 10, 64) |
|
if err != nil || timeout <= 0 { |
|
return 0, fmt.Errorf("CODEX_MCP_STARTUP_TIMEOUT must be a positive integer number of seconds, got %q", value) |
|
} |
|
return timeout, nil |
|
} |
|
|
|
// updateStartupTimeout 更新 MCP 启动超时配置以及代理环境变量配置,并返回更新后的 TOML 内容、服务数量、变更数量和可能的错误 |
|
func updateStartupTimeout(data []byte, timeout int64) ([]byte, int, int, error) { |
|
return updateMCPServers(data, timeout, proxyEnvVars()) |
|
} |
|
|
|
// updateMCPServers 更新 mcp_servers 表中的启动超时和代理环境变量配置 |
|
func updateMCPServers(data []byte, timeout int64, proxyEnvVars []string) ([]byte, int, int, error) { |
|
tree, err := toml.LoadBytes(data) |
|
if err != nil { |
|
return nil, 0, 0, err |
|
} |
|
|
|
serverCount, changedCount := updateMCPServersInTable(tree, timeout, proxyEnvVars) |
|
// 没有变更时返回原始字节,保留用户原来的格式和注释 |
|
if serverCount == 0 || changedCount == 0 { |
|
return data, serverCount, changedCount, nil |
|
} |
|
|
|
var buf bytes.Buffer |
|
if _, err := tree.WriteTo(&buf); err != nil { |
|
return nil, 0, 0, err |
|
} |
|
return stripLineIndent(buf.Bytes()), serverCount, changedCount, nil |
|
} |
|
|
|
// updateMCPServersInTable 更新 mcp_servers 表下的每个服务小节 |
|
func updateMCPServersInTable(root *toml.Tree, timeout int64, proxyEnvVars []string) (int, int) { |
|
table, ok := root.Get("mcp_servers").(*toml.Tree) |
|
if !ok { |
|
return 0, 0 |
|
} |
|
|
|
total := 0 |
|
changed := 0 |
|
for _, name := range table.Keys() { |
|
server, ok := table.GetPath([]string{name}).(*toml.Tree) |
|
if !ok { |
|
continue |
|
} |
|
|
|
total++ |
|
// 单个小节只要超时值或代理环境变量发生变化,就计入变更数量 |
|
sectionChanged := false |
|
if server.Get("startup_timeout_sec") != timeout { |
|
sectionChanged = true |
|
} |
|
server.Set("startup_timeout_sec", timeout) |
|
if addProxyEnvVars(server, proxyEnvVars) { |
|
sectionChanged = true |
|
} |
|
if sectionChanged { |
|
changed++ |
|
} |
|
} |
|
|
|
return total, changed |
|
} |
|
|
|
// proxyEnvVars 收集当前进程中已设置且非空的代理环境变量名 |
|
func proxyEnvVars() []string { |
|
var vars []string |
|
for _, name := range proxyEnvVarNames { |
|
if value, ok := os.LookupEnv(name); ok && strings.TrimSpace(value) != "" { |
|
vars = append(vars, name) |
|
} |
|
} |
|
return vars |
|
} |
|
|
|
// addProxyEnvVars 将代理环境变量名追加到服务小节的 env_vars 配置中,并返回是否发生了实际变更 |
|
func addProxyEnvVars(server *toml.Tree, proxyEnvVars []string) bool { |
|
if len(proxyEnvVars) == 0 { |
|
return false |
|
} |
|
|
|
value := server.Get("env_vars") |
|
items, seen, ok := existingEnvVars(value) |
|
if !ok { |
|
return false |
|
} |
|
|
|
// 只追加缺失项,避免重复写入已有的环境变量名 |
|
changed := false |
|
for _, name := range proxyEnvVars { |
|
if seen[name] { |
|
continue |
|
} |
|
items = append(items, name) |
|
seen[name] = true |
|
changed = true |
|
} |
|
if changed { |
|
server.Set("env_vars", items) |
|
} |
|
return changed |
|
} |
|
|
|
// existingEnvVars 解析现有 env_vars 值并返回原始条目和已出现的变量名集合 |
|
func existingEnvVars(value interface{}) ([]interface{}, map[string]bool, bool) { |
|
items := []interface{}{} |
|
seen := map[string]bool{} |
|
if value == nil { |
|
return items, seen, true |
|
} |
|
|
|
switch envVars := value.(type) { |
|
case []interface{}: |
|
items = append(items, envVars...) |
|
case []*toml.Tree: |
|
for _, item := range envVars { |
|
items = append(items, item) |
|
} |
|
case []string: |
|
for _, item := range envVars { |
|
items = append(items, item) |
|
} |
|
default: |
|
return nil, nil, false |
|
} |
|
|
|
// 支持字符串数组和带 name 字段的表项,其他条目原样保留 |
|
for _, item := range items { |
|
if name, ok := envVarName(item); ok { |
|
seen[name] = true |
|
} |
|
} |
|
return items, seen, true |
|
} |
|
|
|
// envVarName 从 env_vars 条目中提取环境变量名 |
|
func envVarName(item interface{}) (string, bool) { |
|
switch value := item.(type) { |
|
case string: |
|
return value, true |
|
case map[string]interface{}: |
|
name, ok := value["name"].(string) |
|
return name, ok |
|
case *toml.Tree: |
|
name, ok := value.Get("name").(string) |
|
return name, ok |
|
default: |
|
return "", false |
|
} |
|
} |
|
|
|
// stripLineIndent 移除 go-toml 写出内容中每一行开头的缩进 |
|
func stripLineIndent(data []byte) []byte { |
|
lines := bytes.SplitAfter(data, []byte("\n")) |
|
for i, line := range lines { |
|
// 保留行尾换行,只清理行首空格和制表符 |
|
lines[i] = bytes.TrimLeft(line, " \t") |
|
} |
|
return bytes.Join(lines, nil) |
|
} |