1
0

main.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. // Initialize MCP
  47. initResult, err := mcpClient.Initialize()
  48. if err != nil {
  49. mcpClient.Close()
  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 MCP manager to aggregate ARP + external servers
  54. mcpManager := NewMCPManager(mcpClient)
  55. // Load external MCP servers from config file if specified
  56. if cfg.MCPConfigPath != "" {
  57. log.Printf("Loading MCP server configuration from %s", cfg.MCPConfigPath)
  58. mcpConfig, err := LoadMCPConfig(cfg.MCPConfigPath)
  59. if err != nil {
  60. mcpManager.Close()
  61. log.Fatalf("Failed to load MCP config: %v", err)
  62. }
  63. for name, serverConfig := range mcpConfig.MCPServers {
  64. if err := mcpManager.AddExternalServer(name, serverConfig); err != nil {
  65. log.Printf("Warning: Failed to add external MCP server '%s': %v", name, err)
  66. }
  67. }
  68. }
  69. // Initialize the manager (discovers ARP tools)
  70. if err := mcpManager.Initialize(); err != nil {
  71. mcpManager.Close()
  72. log.Fatalf("Failed to initialize MCP manager: %v", err)
  73. }
  74. log.Printf("MCP manager initialized with %d tools from %d servers", mcpManager.GetToolCount(), len(mcpManager.GetServerNames()))
  75. // Create and initialize agent
  76. agent := NewAgent(llm, mcpManager, cfg)
  77. if err := agent.Initialize(); err != nil {
  78. mcpManager.Close()
  79. log.Fatalf("Failed to initialize agent: %v", err)
  80. }
  81. log.Printf("Agent initialized successfully.")
  82. // Setup event queues
  83. agent.SetupQueues(cfg.MaxQueueSize)
  84. log.Printf("Event queues initialized with capacity: %d", cfg.MaxQueueSize)
  85. // List and subscribe to resources
  86. log.Printf("Subscribing to ARP resources...")
  87. resources, err := mcpManager.ListResources()
  88. if err != nil {
  89. mcpManager.Close()
  90. log.Fatalf("Failed to list resources: %v", err)
  91. }
  92. log.Printf("Available resources: %v", resourceURIs(resources))
  93. for _, resource := range resources {
  94. log.Printf(" Subscribed to: %s", resource.URI)
  95. if err := mcpManager.SubscribeResource(resource.URI); err != nil {
  96. log.Printf("Warning: Failed to subscribe to %s: %v", resource.URI, err)
  97. }
  98. }
  99. // Handle graceful shutdown
  100. ctx, cancel := context.WithCancel(context.Background())
  101. sigChan := make(chan os.Signal, 1)
  102. signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
  103. go func() {
  104. <-sigChan
  105. log.Println("Received shutdown signal, stopping...")
  106. cancel()
  107. }()
  108. // Start the agent queue processor
  109. agent.Start(ctx)
  110. defer agent.Stop()
  111. // Listen for events
  112. log.Println()
  113. log.Println("Listening for events. Press Ctrl+C to stop.")
  114. for {
  115. select {
  116. case <-ctx.Done():
  117. mcpManager.Close()
  118. return
  119. case event, ok := <-mcpManager.Notifications():
  120. if !ok {
  121. log.Println("Notification channel closed")
  122. mcpManager.Close()
  123. return
  124. }
  125. handleNotification(agent, event)
  126. }
  127. }
  128. }
  129. // login authenticates with the ARP server and returns a JWT token
  130. func login(baseURL, username, password string) (string, error) {
  131. // Ensure URL has the /query endpoint
  132. loginURL := strings.TrimSuffix(baseURL, "/")
  133. if !strings.HasSuffix(loginURL, "/query") {
  134. loginURL = loginURL + "/query"
  135. }
  136. query := `
  137. mutation Login($email: String!, $password: String!) {
  138. login(email: $email, password: $password) {
  139. token
  140. user {
  141. id
  142. email
  143. }
  144. }
  145. }`
  146. reqBody := map[string]interface{}{
  147. "query": query,
  148. "variables": map[string]interface{}{
  149. "email": username,
  150. "password": password,
  151. },
  152. }
  153. bodyBytes, err := json.Marshal(reqBody)
  154. if err != nil {
  155. return "", fmt.Errorf("failed to marshal request: %w", err)
  156. }
  157. req, err := http.NewRequest("POST", loginURL, bytes.NewReader(bodyBytes))
  158. if err != nil {
  159. return "", fmt.Errorf("failed to create request: %w", err)
  160. }
  161. req.Header.Set("Content-Type", "application/json")
  162. client := &http.Client{Timeout: 30 * time.Second}
  163. resp, err := client.Do(req)
  164. if err != nil {
  165. return "", fmt.Errorf("request failed: %w", err)
  166. }
  167. defer resp.Body.Close()
  168. var result struct {
  169. Data struct {
  170. Login struct {
  171. Token string `json:"token"`
  172. User struct {
  173. ID string `json:"id"`
  174. Email string `json:"email"`
  175. } `json:"user"`
  176. } `json:"login"`
  177. } `json:"data"`
  178. Errors []struct {
  179. Message string `json:"message"`
  180. } `json:"errors"`
  181. }
  182. if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
  183. return "", fmt.Errorf("failed to parse response: %w", err)
  184. }
  185. if len(result.Errors) > 0 {
  186. return "", fmt.Errorf("login failed: %s", result.Errors[0].Message)
  187. }
  188. if result.Data.Login.Token == "" {
  189. return "", fmt.Errorf("no token received")
  190. }
  191. return result.Data.Login.Token, nil
  192. }
  193. // resourceURIs extracts URIs from resources for logging
  194. func resourceURIs(resources []Resource) []string {
  195. uris := make([]string, len(resources))
  196. for i, r := range resources {
  197. uris[i] = r.URI
  198. }
  199. return uris
  200. }
  201. // handleNotification processes an MCP notification and queues it for processing
  202. func handleNotification(agent *Agent, event json.RawMessage) {
  203. // Parse the notification
  204. var notification JSONRPCNotification
  205. if err := json.Unmarshal(event, &notification); err != nil {
  206. log.Printf("Failed to parse notification: %v", err)
  207. return
  208. }
  209. // Handle resource update notifications
  210. if notification.Method == "notifications/resources/updated" {
  211. params, ok := notification.Params.(map[string]interface{})
  212. if !ok {
  213. log.Printf("Invalid notification params")
  214. return
  215. }
  216. uri, _ := params["uri"].(string)
  217. contents, ok := params["contents"].(map[string]interface{})
  218. if !ok {
  219. log.Printf("Invalid notification contents")
  220. return
  221. }
  222. text, _ := contents["text"].(string)
  223. log.Printf("Received event from %s", uri)
  224. // Queue the event for processing (non-blocking)
  225. agent.QueueEvent(uri, json.RawMessage(text))
  226. }
  227. }