-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathclient.go
More file actions
1144 lines (979 loc) · 30.6 KB
/
Copy pathclient.go
File metadata and controls
1144 lines (979 loc) · 30.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
import (
"bufio"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"go.uber.org/zap"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/socket"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/tray"
)
// HealthStatus represents the unified health status of an upstream MCP server.
// This matches the contracts.HealthStatus struct from the core.
// Spec 013: Health is the single source of truth for server status.
type HealthStatus struct {
Level string `json:"level"` // "healthy", "degraded", "unhealthy"
AdminState string `json:"admin_state"` // "enabled", "disabled", "quarantined"
Summary string `json:"summary"` // e.g., "Connected (5 tools)"
Detail string `json:"detail,omitempty"` // Optional longer explanation
Action string `json:"action,omitempty"` // "login", "restart", "enable", "approve", "set_secret", "configure", "view_logs", ""
}
// Server represents a server from the API
type Server struct {
Name string `json:"name"`
Connected bool `json:"connected"`
Connecting bool `json:"connecting"`
Enabled bool `json:"enabled"`
Quarantined bool `json:"quarantined"`
Protocol string `json:"protocol"`
URL string `json:"url"`
Command string `json:"command"`
ToolCount int `json:"tool_count"`
LastError string `json:"last_error"`
Status string `json:"status"`
ShouldRetry bool `json:"should_retry"`
RetryCount int `json:"retry_count"`
LastRetry string `json:"last_retry_time"`
Health *HealthStatus `json:"health,omitempty"` // Spec 013: Health is source of truth
}
// Tool represents a tool from the API
type Tool struct {
Name string `json:"name"`
Description string `json:"description"`
Server string `json:"server"`
InputSchema map[string]interface{} `json:"input_schema,omitempty"`
}
// SearchResult represents a search result from the API
type SearchResult struct {
Name string `json:"name"`
Description string `json:"description"`
Server string `json:"server"`
Score float64 `json:"score"`
InputSchema map[string]interface{} `json:"input_schema,omitempty"`
}
// Response represents the standard API response format
type Response struct {
Success bool `json:"success"`
Data map[string]interface{} `json:"data,omitempty"`
Error string `json:"error,omitempty"`
}
// StatusUpdate represents a status update from SSE
type StatusUpdate struct {
Running bool `json:"running"`
ListenAddr string `json:"listen_addr"`
UpstreamStats map[string]interface{} `json:"upstream_stats"`
Status map[string]interface{} `json:"status"`
Timestamp int64 `json:"timestamp"`
}
// DockerStatus represents Docker recovery status from the API
type DockerStatus struct {
DockerAvailable bool `json:"docker_available"`
RecoveryMode bool `json:"recovery_mode"`
FailureCount int `json:"failure_count"`
AttemptsSinceUp int `json:"attempts_since_up"`
LastAttempt string `json:"last_attempt"`
LastError string `json:"last_error"`
LastSuccessfulAt string `json:"last_successful_at"`
}
// Client provides access to the mcpproxy API
type Client struct {
baseURL string
apiKey string
httpClient *http.Client
logger *zap.SugaredLogger
statusCh chan StatusUpdate
sseCancel context.CancelFunc
connectionStateCh chan tray.ConnectionState
// State tracking to reduce logging noise
lastServerState string // Hash of server states to detect changes
}
// NewClient creates a new API client with automatic socket/pipe support
func NewClient(endpoint string, logger *zap.SugaredLogger) *Client {
// Create TLS config that trusts the local CA
tlsConfig := createTLSConfig(logger)
// Create custom transport
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
// Check if we should use a custom dialer (Unix socket or Windows pipe)
dialer, baseURL, err := socket.CreateDialer(endpoint)
if err != nil {
if logger != nil {
logger.Warn("Failed to create custom dialer, falling back to TCP",
"endpoint", endpoint,
"error", err)
}
baseURL = endpoint
dialer = nil
}
// Apply custom dialer if available
if dialer != nil {
transport.DialContext = dialer
if logger != nil {
logger.Infow("Using socket/pipe connection",
"endpoint", endpoint,
"base_url", baseURL)
}
} else {
if logger != nil {
logger.Infow("Using TCP connection", "endpoint", endpoint)
}
}
return &Client{
baseURL: strings.TrimSuffix(baseURL, "/"),
httpClient: &http.Client{
Timeout: 0,
Transport: transport,
},
logger: logger,
statusCh: make(chan StatusUpdate, 10),
connectionStateCh: make(chan tray.ConnectionState, 8),
}
}
// CreateHTTPClient creates an HTTP client with socket/pipe awareness and optional timeout.
// This is used by both the API client and health monitor to ensure consistent behavior.
func CreateHTTPClient(endpoint string, timeout time.Duration, logger *zap.SugaredLogger) *http.Client {
// Create TLS config that trusts the local CA
tlsConfig := createTLSConfig(logger)
// Create custom transport
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
// Check if we should use a custom dialer (Unix socket or Windows pipe)
dialer, _, err := socket.CreateDialer(endpoint)
if err != nil {
if logger != nil {
logger.Debug("Using standard TCP dialer",
"endpoint", endpoint,
"error", err)
}
}
// Apply custom dialer if available
if dialer != nil {
transport.DialContext = dialer
if logger != nil {
logger.Debug("Using socket/pipe dialer for HTTP client",
"endpoint", endpoint)
}
}
return &http.Client{
Timeout: timeout,
Transport: transport,
}
}
func (c *Client) buildURL(path string) (string, error) {
base := strings.TrimSuffix(c.baseURL, "/")
baseURL, err := url.Parse(base)
if err != nil {
return "", fmt.Errorf("invalid base URL %q: %w", c.baseURL, err)
}
rel, err := url.Parse(path)
if err != nil {
return "", fmt.Errorf("invalid path %q: %w", path, err)
}
return baseURL.ResolveReference(rel).String(), nil
}
// SetAPIKey sets the API key for authentication
func (c *Client) SetAPIKey(apiKey string) {
c.apiKey = apiKey
}
// StartSSE starts the Server-Sent Events connection for real-time updates with enhanced retry logic
func (c *Client) StartSSE(ctx context.Context) error {
c.logger.Info("Starting enhanced SSE connection for real-time updates over socket/pipe transport")
sseCtx, cancel := context.WithCancel(ctx)
c.sseCancel = cancel
go func() {
defer close(c.statusCh)
defer close(c.connectionStateCh)
attemptCount := 0
maxRetries := 10
baseDelay := 2 * time.Second
maxDelay := 30 * time.Second
for {
if sseCtx.Err() != nil {
c.publishConnectionState(tray.ConnectionStateDisconnected)
return
}
attemptCount++
// Calculate exponential backoff delay
minVal := attemptCount - 1
if minVal > 4 {
minVal = 4
}
if minVal < 0 {
minVal = 0
}
backoffFactor := 1 << minVal
delay := time.Duration(int64(baseDelay) * int64(backoffFactor))
if delay > maxDelay {
delay = maxDelay
}
if attemptCount > 1 {
if c.logger != nil {
c.logger.Infow("SSE reconnection attempt",
"attempt", attemptCount,
"max_retries", maxRetries,
"delay", delay,
"base_url", c.baseURL)
}
// Wait before reconnecting (except first attempt)
select {
case <-sseCtx.Done():
c.publishConnectionState(tray.ConnectionStateDisconnected)
return
case <-time.After(delay):
}
}
// Check if we've exceeded max retries
if attemptCount > maxRetries {
if c.logger != nil {
c.logger.Errorw("SSE connection failed after max retries",
"attempts", attemptCount,
"max_retries", maxRetries,
"base_url", c.baseURL)
}
c.publishConnectionState(tray.ConnectionStateDisconnected)
return
}
c.publishConnectionState(tray.ConnectionStateConnecting)
if err := c.connectSSE(sseCtx); err != nil {
if c.logger != nil {
c.logger.Errorw("SSE connection error",
"error", err,
"attempt", attemptCount,
"max_retries", maxRetries,
"base_url", c.baseURL)
}
// Check if it's a context cancellation
if sseCtx.Err() != nil {
c.publishConnectionState(tray.ConnectionStateDisconnected)
return
}
c.publishConnectionState(tray.ConnectionStateReconnecting)
continue
}
// Successful connection - reset attempt count
if attemptCount > 1 && c.logger != nil {
c.logger.Infow("SSE connection established successfully",
"after_attempts", attemptCount,
"base_url", c.baseURL)
}
attemptCount = 0
}
}()
return nil
}
// StopSSE stops the SSE connection
func (c *Client) StopSSE() {
if c.sseCancel != nil {
c.sseCancel()
}
}
// StatusChannel returns the channel for status updates
func (c *Client) StatusChannel() <-chan StatusUpdate {
return c.statusCh
}
// ConnectionStateChannel exposes connectivity updates for tray consumers.
func (c *Client) ConnectionStateChannel() <-chan tray.ConnectionState {
return c.connectionStateCh
}
// connectSSE establishes the SSE connection and processes events
func (c *Client) connectSSE(ctx context.Context) error {
url, err := c.buildURL("/events")
if err != nil {
return err
}
if c.apiKey != "" {
separator := "?"
if strings.Contains(url, "?") {
separator = "&"
}
url += separator + "apikey=" + c.apiKey
}
req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
return err
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Cache-Control", "no-cache")
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("SSE connection failed with status: %d", resp.StatusCode)
}
c.publishConnectionState(tray.ConnectionStateConnected)
scanner := bufio.NewScanner(resp.Body)
var eventType string
var data strings.Builder
for scanner.Scan() {
line := scanner.Text()
if line == "" {
// End of event, process it
if eventType != "" && data.Len() > 0 {
c.processSSEEvent(eventType, data.String())
eventType = ""
data.Reset()
}
} else if strings.HasPrefix(line, "event:") {
eventType = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
} else if strings.HasPrefix(line, "data:") {
dataLine := strings.TrimSpace(strings.TrimPrefix(line, "data:"))
if data.Len() > 0 {
data.WriteString("\n")
}
data.WriteString(dataLine)
}
}
return scanner.Err()
}
// processSSEEvent processes incoming SSE events
func (c *Client) processSSEEvent(eventType, data string) {
if eventType == "status" {
var statusUpdate StatusUpdate
if err := json.Unmarshal([]byte(data), &statusUpdate); err != nil {
if c.logger != nil {
c.logger.Errorw("Failed to parse SSE status data", "error", err)
}
return
}
// Send to status channel (non-blocking)
select {
case c.statusCh <- statusUpdate:
default:
// Channel full, skip this update
}
}
}
// publishConnectionState attempts to deliver a connection state update without blocking the SSE loop.
func (c *Client) publishConnectionState(state tray.ConnectionState) {
select {
case c.connectionStateCh <- state:
default:
if c.logger != nil {
c.logger.Debugw("Dropping connection state update", "state", state)
}
}
}
// GetReady checks if the core API is ready to serve requests
func (c *Client) GetReady(ctx context.Context) error {
url, err := c.buildURL("/ready")
if err != nil {
return fmt.Errorf("failed to build ready URL: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "GET", url, http.NoBody)
if err != nil {
return fmt.Errorf("failed to create ready request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("ready request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("ready endpoint returned status %d", resp.StatusCode)
}
return nil
}
// GetServers fetches the list of servers from the API
func (c *Client) GetServers() ([]Server, error) {
resp, err := c.makeRequest("GET", "/api/v1/servers", nil)
if err != nil {
if c.logger != nil {
c.logger.Warnw("Failed to fetch upstream servers", "error", err)
}
return nil, err
}
if !resp.Success {
if c.logger != nil {
c.logger.Warnw("API reported failure while fetching servers", "error", resp.Error)
}
return nil, fmt.Errorf("API error: %s", resp.Error)
}
servers, ok := resp.Data["servers"].([]interface{})
if !ok {
if c.logger != nil {
c.logger.Warnw("Unexpected server list payload shape", "data_keys", keys(resp.Data))
}
return nil, fmt.Errorf("unexpected response format")
}
var result []Server
for _, serverData := range servers {
serverMap, ok := serverData.(map[string]interface{})
if !ok {
continue
}
server := Server{
Name: getString(serverMap, "name"),
Connected: getBool(serverMap, "connected"),
Connecting: getBool(serverMap, "connecting"),
Enabled: getBool(serverMap, "enabled"),
Quarantined: getBool(serverMap, "quarantined"),
Protocol: getString(serverMap, "protocol"),
URL: getString(serverMap, "url"),
Command: getString(serverMap, "command"),
ToolCount: getInt(serverMap, "tool_count"),
LastError: getString(serverMap, "last_error"),
Status: getString(serverMap, "status"),
ShouldRetry: getBool(serverMap, "should_retry"),
RetryCount: getInt(serverMap, "retry_count"),
LastRetry: getString(serverMap, "last_retry_time"),
}
// Extract health status (Spec 013: Health is source of truth)
healthRaw := serverMap["health"]
if healthMap, ok := healthRaw.(map[string]interface{}); ok && healthMap != nil {
server.Health = &HealthStatus{
Level: getString(healthMap, "level"),
AdminState: getString(healthMap, "admin_state"),
Summary: getString(healthMap, "summary"),
Detail: getString(healthMap, "detail"),
Action: getString(healthMap, "action"),
}
if c.logger != nil && server.Health.Level != "" {
c.logger.Debugw("Health extracted",
"server", server.Name,
"level", server.Health.Level,
"summary", server.Health.Summary)
}
} else if healthRaw != nil && c.logger != nil {
// Health field exists but wasn't a map - log for debugging
c.logger.Warnw("Health field present but wrong type",
"server", server.Name,
"health_type", fmt.Sprintf("%T", healthRaw))
}
result = append(result, server)
}
// Compute state hash to detect changes and reduce logging noise
stateHash := c.computeServerStateHash(result)
stateChanged := stateHash != c.lastServerState
if c.logger != nil {
// Count servers with health for debugging
healthyCount := 0
withHealthCount := 0
for _, s := range result {
if s.Health != nil {
withHealthCount++
if s.Health.Level == "healthy" {
healthyCount++
}
}
}
if len(result) == 0 {
c.logger.Warnw("API returned zero upstream servers",
"base_url", c.baseURL)
} else if stateChanged {
// Only log when server states actually change
c.logger.Debugw("Server state changed",
"count", len(result),
"connected", countConnected(result),
"with_health", withHealthCount,
"healthy", healthyCount,
"quarantined", countQuarantined(result))
c.lastServerState = stateHash
}
// Silent when no changes - reduces log noise from frequent polling
}
return result, nil
}
// EnableServer enables or disables a server
func (c *Client) EnableServer(serverName string, enabled bool) error {
var endpoint string
if enabled {
endpoint = fmt.Sprintf("/api/v1/servers/%s/enable", serverName)
} else {
endpoint = fmt.Sprintf("/api/v1/servers/%s/disable", serverName)
}
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// RestartServer restarts a server
func (c *Client) RestartServer(serverName string) error {
endpoint := fmt.Sprintf("/api/v1/servers/%s/restart", serverName)
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// ForceReconnectAllServers triggers reconnection attempts for all upstream servers
func (c *Client) ForceReconnectAllServers(reason string) error {
endpoint := "/api/v1/servers/reconnect"
if reason != "" {
endpoint = endpoint + "?reason=" + url.QueryEscape(reason)
}
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// TriggerOAuthLogin triggers OAuth login for a server
func (c *Client) TriggerOAuthLogin(serverName string) error {
endpoint := fmt.Sprintf("/api/v1/servers/%s/login", serverName)
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// GetServerTools gets tools for a specific server
func (c *Client) GetServerTools(serverName string) ([]Tool, error) {
endpoint := fmt.Sprintf("/api/v1/servers/%s/tools", serverName)
resp, err := c.makeRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("API error: %s", resp.Error)
}
tools, ok := resp.Data["tools"].([]interface{})
if !ok {
return nil, fmt.Errorf("unexpected response format")
}
var result []Tool
for _, toolData := range tools {
toolMap, ok := toolData.(map[string]interface{})
if !ok {
continue
}
tool := Tool{
Name: getString(toolMap, "name"),
Description: getString(toolMap, "description"),
Server: getString(toolMap, "server"),
}
if schema, ok := toolMap["input_schema"].(map[string]interface{}); ok {
tool.InputSchema = schema
}
result = append(result, tool)
}
return result, nil
}
// QuarantineServer places a server in quarantine
func (c *Client) QuarantineServer(serverName string) error {
endpoint := fmt.Sprintf("/api/v1/servers/%s/quarantine", serverName)
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// UnquarantineServer removes a server from quarantine
func (c *Client) UnquarantineServer(serverName string) error {
endpoint := fmt.Sprintf("/api/v1/servers/%s/unquarantine", serverName)
resp, err := c.makeRequest("POST", endpoint, nil)
if err != nil {
return err
}
if !resp.Success {
return fmt.Errorf("API error: %s", resp.Error)
}
return nil
}
// SearchTools searches for tools
// GetInfo fetches server information from /api/v1/info endpoint
func (c *Client) GetInfo() (map[string]interface{}, error) {
resp, err := c.makeRequest("GET", "/api/v1/info", nil)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("API error: %s", resp.Error)
}
// Return the full response including the "data" field
result := map[string]interface{}{
"success": resp.Success,
"data": resp.Data,
}
return result, nil
}
// GetStatus fetches the current status snapshot from /api/v1/status
func (c *Client) GetStatus() (map[string]interface{}, error) {
resp, err := c.makeRequest("GET", "/api/v1/status", nil)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("API error: %s", resp.Error)
}
status, ok := resp.Data["status"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("unexpected status payload")
}
return status, nil
}
// GetDockerStatus retrieves the current Docker recovery status
func (c *Client) GetDockerStatus() (*DockerStatus, error) {
resp, err := c.makeRequest("GET", "/api/v1/docker/status", nil)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("API error: %s", resp.Error)
}
// Parse the data field into DockerStatus
var status DockerStatus
if resp.Data != nil {
// Convert map to JSON and back to struct for proper type conversion
jsonData, err := json.Marshal(resp.Data)
if err != nil {
return nil, fmt.Errorf("failed to marshal Docker status: %w", err)
}
if err := json.Unmarshal(jsonData, &status); err != nil {
return nil, fmt.Errorf("failed to unmarshal Docker status: %w", err)
}
}
return &status, nil
}
func (c *Client) SearchTools(query string, limit int) ([]SearchResult, error) {
endpoint := fmt.Sprintf("/api/v1/index/search?q=%s&limit=%d", query, limit)
resp, err := c.makeRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
if !resp.Success {
return nil, fmt.Errorf("API error: %s", resp.Error)
}
results, ok := resp.Data["results"].([]interface{})
if !ok {
return nil, fmt.Errorf("unexpected response format")
}
var searchResults []SearchResult
for _, resultData := range results {
resultMap, ok := resultData.(map[string]interface{})
if !ok {
continue
}
result := SearchResult{
Name: getString(resultMap, "name"),
Description: getString(resultMap, "description"),
Server: getString(resultMap, "server"),
Score: getFloat64(resultMap, "score"),
}
if schema, ok := resultMap["input_schema"].(map[string]interface{}); ok {
result.InputSchema = schema
}
searchResults = append(searchResults, result)
}
return searchResults, nil
}
// OpenWebUI opens the web control panel in the default browser
func (c *Client) OpenWebUI() error {
// Get the actual web UI URL from the /api/v1/info endpoint
// This ensures we use the correct HTTP URL even when connected via socket
resp, err := c.makeRequest("GET", "/api/v1/info", nil)
if err != nil {
if c.logger != nil {
c.logger.Errorw("Failed to get server info", "error", err)
}
return fmt.Errorf("failed to get server info: %w", err)
}
// Extract web_ui_url from response
if resp.Data == nil {
return fmt.Errorf("no data in response from /api/v1/info")
}
webUIURL, ok := resp.Data["web_ui_url"].(string)
if !ok || webUIURL == "" {
return fmt.Errorf("web_ui_url not found in server info")
}
// Add API key if not using socket communication
url := webUIURL
if c.apiKey != "" && !strings.HasPrefix(c.baseURL, "unix://") && !strings.HasPrefix(c.baseURL, "npipe://") {
separator := "?"
if strings.Contains(url, "?") {
separator = "&"
}
url += separator + "apikey=" + c.apiKey
}
displayURL := url
if c.apiKey != "" {
displayURL = strings.ReplaceAll(url, c.apiKey, maskForLog(c.apiKey))
}
if c.logger != nil {
c.logger.Infow("Opening web control panel", "url", displayURL)
}
switch runtime.GOOS {
case "darwin":
cmd := exec.Command("open", url)
if err := cmd.Run(); err != nil {
if c.logger != nil {
c.logger.Errorw("Failed to open web control panel", "url", displayURL, "error", err)
}
return fmt.Errorf("failed to open web control panel: %w", err)
}
return nil
case "windows":
// Try rundll32 first
if err := exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Run(); err == nil {
return nil
}
// Fallback to cmd start
if err := exec.Command("cmd", "/c", "start", "", url).Run(); err != nil {
if c.logger != nil {
c.logger.Errorw("Failed to open web control panel", "url", displayURL, "error", err)
}
return fmt.Errorf("failed to open web control panel: %w", err)
}
return nil
default:
return fmt.Errorf("unsupported OS for OpenWebUI: %s", runtime.GOOS)
}
}
// makeRequest makes an HTTP request to the API with enhanced error handling and retry logic
func (c *Client) makeRequest(method, path string, _ interface{}) (*Response, error) {
url, err := c.buildURL(path)
if err != nil {
return nil, err
}
maxRetries := 3
baseDelay := 1 * time.Second
for attempt := 1; attempt <= maxRetries; attempt++ {
req, err := http.NewRequest(method, url, http.NoBody)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "mcpproxy-tray/1.0")
// Add API key header if available
if c.apiKey != "" {
req.Header.Set("X-API-Key", c.apiKey)
}
// Increased timeout to 15s to allow core to gather status from all servers
// With 14 servers, some may be connecting/Docker starting which takes time
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel() // Defer cancel to ensure response body is fully read before canceling
req = req.WithContext(ctx)
resp, err := c.httpClient.Do(req)
if err != nil {
if attempt < maxRetries {
delay := time.Duration(attempt) * baseDelay
if c.logger != nil {
c.logger.Debugw("Request failed, retrying",
"attempt", attempt,
"max_retries", maxRetries,
"delay", delay,
"error", err)
}
time.Sleep(delay)
continue
}
return nil, fmt.Errorf("request failed after %d attempts: %w", maxRetries, err)
}
// Process response with proper cleanup
result, shouldContinue, err := c.processResponse(resp, attempt, maxRetries, baseDelay, path)
if err != nil {
return nil, err
}
if shouldContinue {
continue
}
return result, nil
}
return nil, fmt.Errorf("unexpected error in request retry loop")
}
// processResponse handles response processing with proper cleanup
func (c *Client) processResponse(resp *http.Response, attempt, maxRetries int, baseDelay time.Duration, path string) (*Response, bool, error) {
defer resp.Body.Close()
// Handle specific HTTP status codes
switch resp.StatusCode {
case 401:
return nil, false, fmt.Errorf("authentication failed: invalid or missing API key")
case 403:
return nil, false, fmt.Errorf("authorization failed: insufficient permissions")
case 404:
return nil, false, fmt.Errorf("endpoint not found: %s", path)
case 429:
// Rate limited - retry with exponential backoff
if attempt < maxRetries {
delay := time.Duration(attempt*attempt) * baseDelay
if c.logger != nil {
c.logger.Warnw("Rate limited, retrying",
"attempt", attempt,
"delay", delay,
"status", resp.StatusCode)
}
time.Sleep(delay)
return nil, true, nil
}
return nil, false, fmt.Errorf("rate limited after %d attempts", maxRetries)
case 500, 502, 503, 504:
// Server errors - retry
if attempt < maxRetries {
delay := time.Duration(attempt) * baseDelay
if c.logger != nil {
c.logger.Warnw("Server error, retrying",
"attempt", attempt,
"status", resp.StatusCode,
"delay", delay)
}
time.Sleep(delay)
return nil, true, nil
}
return nil, false, fmt.Errorf("server error after %d attempts: status %d", maxRetries, resp.StatusCode)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, false, fmt.Errorf("API call failed with status %d", resp.StatusCode)
}
var apiResp Response
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
return nil, false, fmt.Errorf("failed to decode response: %w", err)
}
return &apiResp, false, nil