main.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. llm := NewLLM(cfg.OpenAIKey, cfg.OpenAIModel, float32(cfg.OpenAITemperature), cfg.OpenAIBaseURL, cfg.OpenAIMaxTokens)
  29. if err := llm.TestConnection(context.Background()); err != nil {
  30. log.Fatalf("Failed to connect to OpenAI API: %v", err)
  31. }
  32. log.Printf("✓ Successfully connected to OpenAI API")
  33. // Login to ARP server
  34. log.Printf("Connecting to ARP server at %s...", cfg.ARPURL)
  35. token, err := login(cfg.ARPURL, cfg.ARPUsername, cfg.ARPPassword)
  36. if err != nil {
  37. log.Fatalf("Failed to login: %v", err)
  38. }
  39. log.Printf("Successfully authenticated with ARP server")
  40. // Connect to MCP server
  41. log.Printf("Connecting to MCP server...")
  42. mcpClient := NewMCPClient(cfg.ARPURL, token)
  43. if err := mcpClient.Connect(); err != nil {
  44. log.Fatalf("Failed to connect to MCP: %v", err)
  45. }
  46. defer mcpClient.Close()
  47. // Initialize MCP
  48. initResult, err := mcpClient.Initialize()
  49. if err != nil {
  50. log.Fatalf("Failed to initialize MCP: %v", err)
  51. }
  52. log.Printf("Connected to MCP server: %s v%s", initResult.ServerInfo.Name, initResult.ServerInfo.Version)
  53. // Create and initialize agent
  54. agent := NewAgent(llm, mcpClient, cfg)
  55. if err := agent.Initialize(); err != nil {
  56. log.Fatalf("Failed to initialize agent: %v", err)
  57. }
  58. log.Printf("Agent initialized successfully.")
  59. // Setup event queues
  60. agent.SetupQueues(cfg.MaxQueueSize)
  61. log.Printf("Event queues initialized with capacity: %d", cfg.MaxQueueSize)
  62. // List and subscribe to resources
  63. log.Printf("Subscribing to ARP resources...")
  64. resources, err := mcpClient.ListResources()
  65. if err != nil {
  66. log.Fatalf("Failed to list resources: %v", err)
  67. }
  68. log.Printf("Available resources: %v", resourceURIs(resources))
  69. for _, resource := range resources {
  70. log.Printf(" Subscribed to: %s", resource.URI)
  71. if err := mcpClient.SubscribeResource(resource.URI); err != nil {
  72. log.Printf("Warning: Failed to subscribe to %s: %v", resource.URI, err)
  73. }
  74. }
  75. // Handle graceful shutdown
  76. ctx, cancel := context.WithCancel(context.Background())
  77. sigChan := make(chan os.Signal, 1)
  78. signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
  79. go func() {
  80. <-sigChan
  81. log.Println("Received shutdown signal, stopping...")
  82. cancel()
  83. }()
  84. // Start the agent queue processor
  85. agent.Start(ctx)
  86. defer agent.Stop()
  87. // Listen for events
  88. log.Println()
  89. log.Println("Listening for events. Press Ctrl+C to stop.")
  90. for {
  91. select {
  92. case <-ctx.Done():
  93. return
  94. case event, ok := <-mcpClient.Notifications():
  95. if !ok {
  96. log.Println("Notification channel closed")
  97. return
  98. }
  99. handleNotification(agent, event)
  100. }
  101. }
  102. }
  103. // login authenticates with the ARP server and returns a JWT token
  104. func login(baseURL, username, password string) (string, error) {
  105. // Ensure URL has the /query endpoint
  106. loginURL := strings.TrimSuffix(baseURL, "/")
  107. if !strings.HasSuffix(loginURL, "/query") {
  108. loginURL = loginURL + "/query"
  109. }
  110. query := `
  111. mutation Login($email: String!, $password: String!) {
  112. login(email: $email, password: $password) {
  113. token
  114. user {
  115. id
  116. email
  117. }
  118. }
  119. }`
  120. reqBody := map[string]interface{}{
  121. "query": query,
  122. "variables": map[string]interface{}{
  123. "email": username,
  124. "password": password,
  125. },
  126. }
  127. bodyBytes, err := json.Marshal(reqBody)
  128. if err != nil {
  129. return "", fmt.Errorf("failed to marshal request: %w", err)
  130. }
  131. req, err := http.NewRequest("POST", loginURL, bytes.NewReader(bodyBytes))
  132. if err != nil {
  133. return "", fmt.Errorf("failed to create request: %w", err)
  134. }
  135. req.Header.Set("Content-Type", "application/json")
  136. client := &http.Client{Timeout: 30 * time.Second}
  137. resp, err := client.Do(req)
  138. if err != nil {
  139. return "", fmt.Errorf("request failed: %w", err)
  140. }
  141. defer resp.Body.Close()
  142. var result struct {
  143. Data struct {
  144. Login struct {
  145. Token string `json:"token"`
  146. User struct {
  147. ID string `json:"id"`
  148. Email string `json:"email"`
  149. } `json:"user"`
  150. } `json:"login"`
  151. } `json:"data"`
  152. Errors []struct {
  153. Message string `json:"message"`
  154. } `json:"errors"`
  155. }
  156. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  157. return "", fmt.Errorf("failed to parse response: %w", err)
  158. }
  159. if len(result.Errors) > 0 {
  160. return "", fmt.Errorf("login failed: %s", result.Errors[0].Message)
  161. }
  162. if result.Data.Login.Token == "" {
  163. return "", fmt.Errorf("no token received")
  164. }
  165. return result.Data.Login.Token, nil
  166. }
  167. // resourceURIs extracts URIs from resources for logging
  168. func resourceURIs(resources []Resource) []string {
  169. uris := make([]string, len(resources))
  170. for i, r := range resources {
  171. uris[i] = r.URI
  172. }
  173. return uris
  174. }
  175. // handleNotification processes an MCP notification and queues it for processing
  176. func handleNotification(agent *Agent, event json.RawMessage) {
  177. // Parse the notification
  178. var notification JSONRPCNotification
  179. if err := json.Unmarshal(event, &notification); err != nil {
  180. log.Printf("Failed to parse notification: %v", err)
  181. return
  182. }
  183. // Handle resource update notifications
  184. if notification.Method == "notifications/resources/updated" {
  185. params, ok := notification.Params.(map[string]interface{})
  186. if !ok {
  187. log.Printf("Invalid notification params")
  188. return
  189. }
  190. uri, _ := params["uri"].(string)
  191. contents, ok := params["contents"].(map[string]interface{})
  192. if !ok {
  193. log.Printf("Invalid notification contents")
  194. return
  195. }
  196. text, _ := contents["text"].(string)
  197. log.Printf("Received event from %s", uri)
  198. // Queue the event for processing (non-blocking)
  199. agent.QueueEvent(uri, json.RawMessage(text))
  200. }
  201. }