mcp_config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. )
  8. // MCPServerConfig represents the configuration for a single MCP server
  9. type MCPServerConfig struct {
  10. Command string `json:"command"`
  11. Args []string `json:"args"`
  12. Env map[string]string `json:"env,omitempty"`
  13. }
  14. // MCPConfig represents the root configuration for MCP servers
  15. type MCPConfig struct {
  16. MCPServers map[string]MCPServerConfig `json:"mcpServers"`
  17. }
  18. // LoadMCPConfig loads the MCP configuration from a JSON file
  19. func LoadMCPConfig(path string) (*MCPConfig, error) {
  20. // If no path provided, return empty config
  21. if path == "" {
  22. return &MCPConfig{MCPServers: make(map[string]MCPServerConfig)}, nil
  23. }
  24. // Check if file exists
  25. if _, err := os.Stat(path); os.IsNotExist(err) {
  26. // File doesn't exist, return empty config
  27. return &MCPConfig{MCPServers: make(map[string]MCPServerConfig)}, nil
  28. }
  29. data, err := os.ReadFile(path)
  30. if err != nil {
  31. return nil, fmt.Errorf("failed to read MCP config file: %w", err)
  32. }
  33. var config MCPConfig
  34. if err := json.Unmarshal(data, &config); err != nil {
  35. return nil, fmt.Errorf("failed to parse MCP config file: %w", err)
  36. }
  37. if config.MCPServers == nil {
  38. config.MCPServers = make(map[string]MCPServerConfig)
  39. }
  40. return &config, nil
  41. }
  42. // DefaultMCPConfigPath returns the default path for mcp.json
  43. // It looks in the same directory as the .env file
  44. func DefaultMCPConfigPath() string {
  45. // Check for mcp.json in current directory first
  46. if _, err := os.Stat("mcp.json"); err == nil {
  47. return "mcp.json"
  48. }
  49. // Check for mcp.json in the same directory as the executable
  50. execPath, err := os.Executable()
  51. if err == nil {
  52. execDir := filepath.Dir(execPath)
  53. mcpPath := filepath.Join(execDir, "mcp.json")
  54. if _, err := os.Stat(mcpPath); err == nil {
  55. return mcpPath
  56. }
  57. }
  58. // Default to mcp.json in current directory
  59. return "mcp.json"
  60. }