main.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "log"
  8. "net/http"
  9. "os"
  10. "os/signal"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/joho/godotenv"
  15. )
  16. func main() {
  17. // Load .env file if it exists
  18. if err := godotenv.Load(); err != nil {
  19. log.Println("No .env file found, using environment variables")
  20. }
  21. // Load configuration
  22. cfg, err := LoadConfig()
  23. if err != nil {
  24. log.Fatalf("Failed to load configuration: %v", err)
  25. }
  26. // Test OpenAI connectivity
  27. log.Printf("Testing connectivity to OpenAI API...")
  28. retryDelay := time.Duration(cfg.LLMRetryDelay) * time.Second
  29. llm := NewLLMWithRetry(cfg.OpenAIKey, cfg.OpenAIModel, float32(cfg.OpenAITemperature), cfg.OpenAIBaseURL, cfg.OpenAIMaxTokens, cfg.LLMMaxRetries, retryDelay)
  30. if err := llm.TestConnection(context.Background()); err != nil {
  31. log.Fatalf("Failed to connect to OpenAI API: %v", err)
  32. }
  33. log.Printf("✓ Successfully connected to OpenAI API (max retries: %d, retry delay: %v)", cfg.LLMMaxRetries, retryDelay)
  34. // Login to ARP server
  35. log.Printf("Connecting to ARP server at %s...", cfg.ARPURL)
  36. token, err := login(cfg.ARPURL, cfg.ARPUsername, cfg.ARPPassword)
  37. if err != nil {
  38. log.Fatalf("Failed to login: %v", err)
  39. }
  40. log.Printf("Successfully authenticated with ARP server")
  41. // Connect to MCP server
  42. log.Printf("Connecting to MCP server...")
  43. mcpClient := NewMCPClient(cfg.ARPURL, token)
  44. if err := mcpClient.Connect(); err != nil {
  45. log.Fatalf("Failed to connect to MCP: %v", err)
  46. }
  47. // Initialize MCP
  48. initResult, err := mcpClient.Initialize()
  49. if err != nil {
  50. mcpClient.Close()
  51. log.Fatalf("Failed to initialize MCP: %v", err)
  52. }
  53. log.Printf("Connected to MCP server: %s v%s", initResult.ServerInfo.Name, initResult.ServerInfo.Version)
  54. // Create MCP manager to aggregate ARP + external servers
  55. mcpManager := NewMCPManager(mcpClient)
  56. // Load external MCP servers from config file if specified
  57. if cfg.MCPConfigPath != "" {
  58. log.Printf("Loading MCP server configuration from %s", cfg.MCPConfigPath)
  59. mcpConfig, err := LoadMCPConfig(cfg.MCPConfigPath)
  60. if err != nil {
  61. mcpManager.Close()
  62. log.Fatalf("Failed to load MCP config: %v", err)
  63. }
  64. for name, serverConfig := range mcpConfig.MCPServers {
  65. if err := mcpManager.AddExternalServer(name, serverConfig); err != nil {
  66. log.Printf("Warning: Failed to add external MCP server '%s': %v", name, err)
  67. }
  68. }
  69. }
  70. // Initialize the manager (discovers ARP tools)
  71. if err := mcpManager.Initialize(); err != nil {
  72. mcpManager.Close()
  73. log.Fatalf("Failed to initialize MCP manager: %v", err)
  74. }
  75. log.Printf("MCP manager initialized with %d tools from %d servers", mcpManager.GetToolCount(), len(mcpManager.GetServerNames()))
  76. // Create and initialize agent
  77. agent := NewAgent(llm, mcpManager, cfg)
  78. if err := agent.Initialize(); err != nil {
  79. mcpManager.Close()
  80. log.Fatalf("Failed to initialize agent: %v", err)
  81. }
  82. log.Printf("Agent initialized successfully.")
  83. // Setup event queues
  84. agent.SetupQueues(cfg.MaxQueueSize)
  85. log.Printf("Event queues initialized with capacity: %d", cfg.MaxQueueSize)
  86. // List and subscribe to resources
  87. log.Printf("Subscribing to ARP resources...")
  88. resources, err := mcpManager.ListResources()
  89. if err != nil {
  90. mcpManager.Close()
  91. log.Fatalf("Failed to list resources: %v", err)
  92. }
  93. log.Printf("Available resources: %v", resourceURIs(resources))
  94. for _, resource := range resources {
  95. log.Printf(" Subscribed to: %s", resource.URI)
  96. if err := mcpManager.SubscribeResource(resource.URI); err != nil {
  97. log.Printf("Warning: Failed to subscribe to %s: %v", resource.URI, err)
  98. }
  99. }
  100. // Handle graceful shutdown
  101. ctx, cancel := context.WithCancel(context.Background())
  102. sigChan := make(chan os.Signal, 1)
  103. signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
  104. go func() {
  105. <-sigChan
  106. log.Println("Received shutdown signal, stopping...")
  107. cancel()
  108. }()
  109. // Start the agent queue processor
  110. agent.Start(ctx)
  111. defer agent.Stop()
  112. // Listen for events with reconnection support
  113. log.Println()
  114. log.Println("Listening for events. Press Ctrl+C to stop.")
  115. reconnectDelay := time.Duration(cfg.MCPReconnectDelay) * time.Second
  116. for {
  117. select {
  118. case <-ctx.Done():
  119. mcpManager.Close()
  120. return
  121. case event, ok := <-mcpManager.Notifications():
  122. if !ok {
  123. // Notification channel closed - attempt to reconnect
  124. log.Printf("Notification channel closed, attempting to reconnect in %v...", reconnectDelay)
  125. select {
  126. case <-ctx.Done():
  127. mcpManager.Close()
  128. return
  129. case <-time.After(reconnectDelay):
  130. // Try to reconnect
  131. if err := reconnectMCP(cfg, mcpManager, &token); err != nil {
  132. log.Printf("Reconnection failed: %v. Retrying in %v...", err, reconnectDelay)
  133. continue
  134. }
  135. log.Println("Successfully reconnected to MCP server")
  136. }
  137. continue
  138. }
  139. handleNotification(agent, event)
  140. }
  141. }
  142. }
  143. // reconnectMCP attempts to reconnect to the MCP server
  144. func reconnectMCP(cfg *Config, mcpManager *MCPManager, token *string) error {
  145. // Re-authenticate
  146. newToken, err := login(cfg.ARPURL, cfg.ARPUsername, cfg.ARPPassword)
  147. if err != nil {
  148. return fmt.Errorf("failed to re-authenticate: %w", err)
  149. }
  150. *token = newToken
  151. // Create new MCP client
  152. mcpClient := NewMCPClient(cfg.ARPURL, newToken)
  153. if err := mcpClient.Connect(); err != nil {
  154. return fmt.Errorf("failed to reconnect to MCP: %w", err)
  155. }
  156. // Initialize MCP
  157. if _, err := mcpClient.Initialize(); err != nil {
  158. mcpClient.Close()
  159. return fmt.Errorf("failed to initialize MCP on reconnect: %w", err)
  160. }
  161. // Use the manager's Reconnect method to replace the client and re-subscribe
  162. if err := mcpManager.Reconnect(mcpClient); err != nil {
  163. return fmt.Errorf("failed to reconnect MCP manager: %w", err)
  164. }
  165. log.Println("Successfully reconnected to MCP server")
  166. return nil
  167. }
  168. // login authenticates with the ARP server and returns a JWT token
  169. func login(baseURL, username, password string) (string, error) {
  170. // Ensure URL has the /query endpoint
  171. loginURL := strings.TrimSuffix(baseURL, "/")
  172. if !strings.HasSuffix(loginURL, "/query") {
  173. loginURL = loginURL + "/query"
  174. }
  175. query := `
  176. mutation Login($email: String!, $password: String!) {
  177. login(email: $email, password: $password) {
  178. token
  179. user {
  180. id
  181. email
  182. }
  183. }
  184. }`
  185. reqBody := map[string]interface{}{
  186. "query": query,
  187. "variables": map[string]interface{}{
  188. "email": username,
  189. "password": password,
  190. },
  191. }
  192. bodyBytes, err := json.Marshal(reqBody)
  193. if err != nil {
  194. return "", fmt.Errorf("failed to marshal request: %w", err)
  195. }
  196. req, err := http.NewRequest("POST", loginURL, bytes.NewReader(bodyBytes))
  197. if err != nil {
  198. return "", fmt.Errorf("failed to create request: %w", err)
  199. }
  200. req.Header.Set("Content-Type", "application/json")
  201. client := &http.Client{Timeout: 30 * time.Second}
  202. resp, err := client.Do(req)
  203. if err != nil {
  204. return "", fmt.Errorf("request failed: %w", err)
  205. }
  206. defer resp.Body.Close()
  207. var result struct {
  208. Data struct {
  209. Login struct {
  210. Token string `json:"token"`
  211. User struct {
  212. ID string `json:"id"`
  213. Email string `json:"email"`
  214. } `json:"user"`
  215. } `json:"login"`
  216. } `json:"data"`
  217. Errors []struct {
  218. Message string `json:"message"`
  219. } `json:"errors"`
  220. }
  221. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  222. return "", fmt.Errorf("failed to parse response: %w", err)
  223. }
  224. if len(result.Errors) > 0 {
  225. return "", fmt.Errorf("login failed: %s", result.Errors[0].Message)
  226. }
  227. if result.Data.Login.Token == "" {
  228. return "", fmt.Errorf("no token received")
  229. }
  230. return result.Data.Login.Token, nil
  231. }
  232. // resourceURIs extracts URIs from resources for logging
  233. func resourceURIs(resources []Resource) []string {
  234. uris := make([]string, len(resources))
  235. for i, r := range resources {
  236. uris[i] = r.URI
  237. }
  238. return uris
  239. }
  240. // handleNotification processes an MCP notification and queues it for processing
  241. func handleNotification(agent *Agent, event json.RawMessage) {
  242. // Parse the notification
  243. var notification JSONRPCNotification
  244. if err := json.Unmarshal(event, &notification); err != nil {
  245. log.Printf("Failed to parse notification: %v", err)
  246. return
  247. }
  248. // Handle resource update notifications
  249. if notification.Method == "notifications/resources/updated" {
  250. params, ok := notification.Params.(map[string]interface{})
  251. if !ok {
  252. log.Printf("Invalid notification params")
  253. return
  254. }
  255. uri, _ := params["uri"].(string)
  256. contents, ok := params["contents"].(map[string]interface{})
  257. if !ok {
  258. log.Printf("Invalid notification contents")
  259. return
  260. }
  261. text, _ := contents["text"].(string)
  262. log.Printf("Received event from %s", uri)
  263. // Queue the event for processing (non-blocking)
  264. agent.QueueEvent(uri, json.RawMessage(text))
  265. }
  266. }