1
0

main.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. // Close existing connection
  146. mcpManager.Close()
  147. // Re-authenticate
  148. newToken, err := login(cfg.ARPURL, cfg.ARPUsername, cfg.ARPPassword)
  149. if err != nil {
  150. return fmt.Errorf("failed to re-authenticate: %w", err)
  151. }
  152. *token = newToken
  153. // Create new MCP client
  154. mcpClient := NewMCPClient(cfg.ARPURL, newToken)
  155. if err := mcpClient.Connect(); err != nil {
  156. return fmt.Errorf("failed to reconnect to MCP: %w", err)
  157. }
  158. // Initialize MCP
  159. if _, err := mcpClient.Initialize(); err != nil {
  160. mcpClient.Close()
  161. return fmt.Errorf("failed to initialize MCP on reconnect: %w", err)
  162. }
  163. // Note: We can't easily replace the mcpManager's internal client
  164. // This is a limitation - in a production system we'd need to refactor
  165. // the MCPManager to support reconnection
  166. log.Println("MCP reconnection requires agent restart - please restart the agent")
  167. return fmt.Errorf("MCP reconnection requires agent restart")
  168. }
  169. // login authenticates with the ARP server and returns a JWT token
  170. func login(baseURL, username, password string) (string, error) {
  171. // Ensure URL has the /query endpoint
  172. loginURL := strings.TrimSuffix(baseURL, "/")
  173. if !strings.HasSuffix(loginURL, "/query") {
  174. loginURL = loginURL + "/query"
  175. }
  176. query := `
  177. mutation Login($email: String!, $password: String!) {
  178. login(email: $email, password: $password) {
  179. token
  180. user {
  181. id
  182. email
  183. }
  184. }
  185. }`
  186. reqBody := map[string]interface{}{
  187. "query": query,
  188. "variables": map[string]interface{}{
  189. "email": username,
  190. "password": password,
  191. },
  192. }
  193. bodyBytes, err := json.Marshal(reqBody)
  194. if err != nil {
  195. return "", fmt.Errorf("failed to marshal request: %w", err)
  196. }
  197. req, err := http.NewRequest("POST", loginURL, bytes.NewReader(bodyBytes))
  198. if err != nil {
  199. return "", fmt.Errorf("failed to create request: %w", err)
  200. }
  201. req.Header.Set("Content-Type", "application/json")
  202. client := &http.Client{Timeout: 30 * time.Second}
  203. resp, err := client.Do(req)
  204. if err != nil {
  205. return "", fmt.Errorf("request failed: %w", err)
  206. }
  207. defer resp.Body.Close()
  208. var result struct {
  209. Data struct {
  210. Login struct {
  211. Token string `json:"token"`
  212. User struct {
  213. ID string `json:"id"`
  214. Email string `json:"email"`
  215. } `json:"user"`
  216. } `json:"login"`
  217. } `json:"data"`
  218. Errors []struct {
  219. Message string `json:"message"`
  220. } `json:"errors"`
  221. }
  222. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  223. return "", fmt.Errorf("failed to parse response: %w", err)
  224. }
  225. if len(result.Errors) > 0 {
  226. return "", fmt.Errorf("login failed: %s", result.Errors[0].Message)
  227. }
  228. if result.Data.Login.Token == "" {
  229. return "", fmt.Errorf("no token received")
  230. }
  231. return result.Data.Login.Token, nil
  232. }
  233. // resourceURIs extracts URIs from resources for logging
  234. func resourceURIs(resources []Resource) []string {
  235. uris := make([]string, len(resources))
  236. for i, r := range resources {
  237. uris[i] = r.URI
  238. }
  239. return uris
  240. }
  241. // handleNotification processes an MCP notification and queues it for processing
  242. func handleNotification(agent *Agent, event json.RawMessage) {
  243. // Parse the notification
  244. var notification JSONRPCNotification
  245. if err := json.Unmarshal(event, &notification); err != nil {
  246. log.Printf("Failed to parse notification: %v", err)
  247. return
  248. }
  249. // Handle resource update notifications
  250. if notification.Method == "notifications/resources/updated" {
  251. params, ok := notification.Params.(map[string]interface{})
  252. if !ok {
  253. log.Printf("Invalid notification params")
  254. return
  255. }
  256. uri, _ := params["uri"].(string)
  257. contents, ok := params["contents"].(map[string]interface{})
  258. if !ok {
  259. log.Printf("Invalid notification contents")
  260. return
  261. }
  262. text, _ := contents["text"].(string)
  263. log.Printf("Received event from %s", uri)
  264. // Queue the event for processing (non-blocking)
  265. agent.QueueEvent(uri, json.RawMessage(text))
  266. }
  267. }