xonecas.io
60255
Zn

Zoea-Nova / files

Zoea-Nova / internal / mcp / proxy.go

15.0 KB
1package mcp
2
3import (
4	"context"
5	"encoding/json"
6	"errors"
7	"fmt"
8	"regexp"
9	"strconv"
10	"strings"
11	"sync"
12	"time"
13
14	"github.com/rs/zerolog/log"
15)
16
17// ToolHandler is a function that handles a tool call.
18type ToolHandler func(ctx context.Context, arguments json.RawMessage) (*ToolResult, error)
19
20// CallerContext provides information about who is calling a tool.
21type CallerContext struct {
22	MysisID   string
23	MysisName string
24}
25
26// ToolHandlerWithContext is a function that handles a tool call with caller context.
27type ToolHandlerWithContext func(ctx context.Context, caller CallerContext, arguments json.RawMessage) (*ToolResult, error)
28
29type AccountStore interface {
30	CreateAccount(username, password string, mysisID ...string) (*Account, error)
31	GetAccountByMysisID(mysisID string) (*Account, error)
32	AssignAccount(username, mysisID string) error
33	ReleaseAccount(username string) error
34	ReleaseAccountByMysisID(mysisID string) error
35	ReleaseAllAccounts() error
36}
37
38type Account struct {
39	Username string
40	Password string
41}
42
43type GameStateStore interface {
44	StoreGameStateSnapshot(username, toolName, content string, gameTick int64) error
45	DeleteGameStateSnapshotsForUsername(username string) error
46}
47
48// Proxy combines an upstream MCP client with local tool handlers.
49type Proxy struct {
50	mu              sync.RWMutex
51	upstream        UpstreamClient
52	localTools      map[string]Tool
53	localHandlers   map[string]ToolHandler
54	contextHandlers map[string]ToolHandlerWithContext
55	accountStore    AccountStore
56	gameStateStore  GameStateStore
57}
58
59var (
60	ErrToolRetryExhausted = errors.New("mcp tool call failed after retries")
61)
62
63// Retry delays increased to respect SpaceMolt's "Try again in 5 seconds" rate limit
64var toolRetryDelays = []time.Duration{2 * time.Second, 5 * time.Second, 10 * time.Second}
65
66// retryAfterRegex matches "Retry-After: N" in error messages
67var retryAfterRegex = regexp.MustCompile(`Retry-After:\s*(\d+)`)
68
69// parseRetryAfter extracts retry delay from error message containing "Retry-After: N seconds"
70func parseRetryAfter(err error) (time.Duration, bool) {
71	if err == nil {
72		return 0, false
73	}
74
75	errMsg := err.Error()
76
77	// Try to extract from "Retry-After: N" header format
78	if matches := retryAfterRegex.FindStringSubmatch(errMsg); len(matches) > 1 {
79		if seconds, parseErr := strconv.Atoi(matches[1]); parseErr == nil {
80			return time.Duration(seconds) * time.Second, true
81		}
82	}
83
84	// Try to extract from "Try again in N seconds" message format
85	if strings.Contains(errMsg, "Try again in") {
86		re := regexp.MustCompile(`Try again in (\d+) seconds?`)
87		if matches := re.FindStringSubmatch(errMsg); len(matches) > 1 {
88			if seconds, parseErr := strconv.Atoi(matches[1]); parseErr == nil {
89				return time.Duration(seconds) * time.Second, true
90			}
91		}
92	}
93
94	return 0, false
95}
96
97// NewProxy creates a new MCP proxy.
98func NewProxy(upstream UpstreamClient) *Proxy {
99	return &Proxy{
100		upstream:        upstream,
101		localTools:      make(map[string]Tool),
102		localHandlers:   make(map[string]ToolHandler),
103		contextHandlers: make(map[string]ToolHandlerWithContext),
104	}
105}
106
107func (p *Proxy) SetAccountStore(store AccountStore) {
108	p.mu.Lock()
109	defer p.mu.Unlock()
110	p.accountStore = store
111}
112
113func (p *Proxy) SetGameStateStore(store GameStateStore) {
114	p.mu.Lock()
115	defer p.mu.Unlock()
116	p.gameStateStore = store
117}
118
119// RegisterTool registers a local tool with the proxy.
120func (p *Proxy) RegisterTool(tool Tool, handler ToolHandler) {
121	p.mu.Lock()
122	defer p.mu.Unlock()
123
124	p.localTools[tool.Name] = tool
125	p.localHandlers[tool.Name] = handler
126}
127
128// RegisterToolWithContext registers a tool handler that receives caller context.
129func (p *Proxy) RegisterToolWithContext(tool Tool, handler ToolHandlerWithContext) {
130	p.mu.Lock()
131	defer p.mu.Unlock()
132
133	p.localTools[tool.Name] = tool
134	p.contextHandlers[tool.Name] = handler
135}
136
137// ListTools returns all available tools (local + upstream).
138func (p *Proxy) ListTools(ctx context.Context) ([]Tool, error) {
139	p.mu.RLock()
140	defer p.mu.RUnlock()
141
142	// Start with local tools
143	tools := make([]Tool, 0, len(p.localTools))
144	for _, t := range p.localTools {
145		tools = append(tools, t)
146	}
147
148	// Add upstream tools if available
149	if p.upstream != nil {
150		upstreamTools, err := p.upstream.ListTools(ctx)
151		if err != nil {
152			log.Warn().
153				Err(err).
154				Msg("failed to list upstream tools")
155		} else {
156			tools = append(tools, upstreamTools...)
157		}
158	}
159
160	return tools, nil
161}
162
163// CallTool invokes a tool, checking local handlers first then upstream.
164func (p *Proxy) CallTool(ctx context.Context, caller CallerContext, name string, arguments json.RawMessage) (*ToolResult, error) {
165	p.mu.RLock()
166	handler, isLocal := p.localHandlers[name]
167	contextHandler, hasContext := p.contextHandlers[name]
168	accountStore := p.accountStore
169	p.mu.RUnlock()
170
171	if hasContext {
172		return contextHandler(ctx, caller, arguments)
173	}
174
175	// Try local handler first
176	if isLocal {
177		return handler(ctx, arguments)
178	}
179
180	// Fall back to upstream
181	if p.upstream != nil {
182		// Intercept register - check if mysis already has an assigned account
183		if name == "register" && accountStore != nil {
184			// Check if mysis already has a permanently assigned account
185			if assignedAccount, err := accountStore.GetAccountByMysisID(caller.MysisID); err == nil && assignedAccount != nil {
186				// Mysis already has an account - return error
187				errorMsg := fmt.Sprintf("Already have account. Use login(username=\"%s\", password=\"...\").", assignedAccount.Username)
188				return &ToolResult{
189					Content: []ContentBlock{{Type: "text", Text: errorMsg}},
190					IsError: true,
191				}, nil
192			}
193
194			// Try to claim an available account from pool
195			if poolAccount := p.tryClaimPoolAccount(caller.MysisID); poolAccount != nil {
196				// Account claimed - login with pool account to get real session
197				loginArgs := map[string]interface{}{
198					"username": poolAccount.Username,
199					"password": poolAccount.Password,
200				}
201				result, err := p.callUpstreamWithRetry(ctx, "login", loginArgs)
202				if result != nil && !result.IsError {
203					// Transform login response to look like register response
204					// (inject password field so mysis can extract it)
205					p.injectPasswordIntoResult(result, poolAccount.Password)
206				}
207				return result, err
208			}
209		}
210
211		// Intercept login - substitute credentials with assigned account if mysis has one
212		if name == "login" && accountStore != nil {
213			if assignedAccount, err := accountStore.GetAccountByMysisID(caller.MysisID); err == nil && assignedAccount != nil {
214				// Mysis has assigned account - substitute credentials
215				loginArgs := map[string]interface{}{
216					"username": assignedAccount.Username,
217					"password": assignedAccount.Password,
218				}
219				result, err := p.callUpstreamWithRetry(ctx, "login", loginArgs)
220				return result, err
221			}
222		}
223
224		var args interface{}
225		if len(arguments) > 0 {
226			if err := json.Unmarshal(arguments, &args); err != nil {
227				return nil, fmt.Errorf("unmarshal arguments: %w", err)
228			}
229		}
230
231		result, err := p.callUpstreamWithRetry(ctx, name, args)
232
233		if result != nil && !result.IsError && accountStore != nil {
234			p.interceptAuthTools(name, arguments, result, caller.MysisID)
235		}
236
237		return result, err
238	}
239
240	errorMsg := fmt.Sprintf("tool not found: %s", name)
241	return &ToolResult{
242		Content: []ContentBlock{{Type: "text", Text: errorMsg}},
243		IsError: true,
244	}, nil
245}
246
247func (p *Proxy) callUpstreamWithRetry(ctx context.Context, name string, args interface{}) (*ToolResult, error) {
248	var lastErr error
249	for attempt := 0; attempt <= len(toolRetryDelays); attempt++ {
250		if attempt > 0 {
251			delay := toolRetryDelays[attempt-1]
252
253			// Check if error is a 429 rate limit
254			is429 := lastErr != nil && (strings.Contains(lastErr.Error(), "429") || strings.Contains(lastErr.Error(), "Rate limited"))
255
256			// Try to parse Retry-After from error message
257			if retryAfter, ok := parseRetryAfter(lastErr); ok {
258				// Use server-specified delay, but cap at 30 seconds for safety
259				if retryAfter > 30*time.Second {
260					retryAfter = 30 * time.Second
261				}
262				delay = retryAfter
263
264				log.Warn().
265					Str("tool", name).
266					Int("attempt", attempt).
267					Dur("delay", delay).
268					Dur("server_requested", retryAfter).
269					Err(lastErr).
270					Msg("MCP tool rate limited - respecting Retry-After")
271			} else if is429 {
272				log.Warn().
273					Str("tool", name).
274					Int("attempt", attempt).
275					Dur("delay", delay).
276					Err(lastErr).
277					Msg("MCP tool rate limited - waiting before retry")
278			} else {
279				log.Warn().
280					Str("tool", name).
281					Int("attempt", attempt).
282					Dur("delay", delay).
283					Msg("Retrying MCP tool call after error")
284			}
285
286			select {
287			case <-time.After(delay):
288			case <-ctx.Done():
289				return nil, ctx.Err()
290			}
291		}
292
293		result, err := p.upstream.CallTool(ctx, name, args)
294		if err == nil {
295			// Log successful call at Info level for visibility
296			if attempt > 0 {
297				log.Info().
298					Str("tool", name).
299					Int("attempt", attempt+1).
300					Msg("MCP tool call succeeded after retry")
301			}
302			return result, nil
303		}
304
305		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
306			return nil, err
307		}
308
309		lastErr = err
310	}
311
312	// Log final failure with more context
313	log.Error().
314		Str("tool", name).
315		Int("total_attempts", len(toolRetryDelays)+1).
316		Err(lastErr).
317		Msg("MCP tool call failed after all retries")
318
319	return nil, fmt.Errorf("%w: %v", ErrToolRetryExhausted, lastErr)
320}
321
322func (p *Proxy) interceptAuthTools(toolName string, arguments json.RawMessage, result *ToolResult, mysisID string) {
323	switch toolName {
324	case "register":
325		p.handleRegisterResponse(arguments, result, mysisID)
326	case "login":
327		p.handleLoginResponse(arguments, result, mysisID)
328	case "logout":
329		p.handleLogoutResponse(arguments, result)
330	}
331}
332
333func (p *Proxy) handleRegisterResponse(arguments json.RawMessage, result *ToolResult, mysisID string) {
334	var args struct {
335		Username string `json:"username"`
336	}
337	if err := json.Unmarshal(arguments, &args); err != nil {
338		return
339	}
340
341	payload, ok := parseToolResultPayload(result)
342	if !ok {
343		return
344	}
345
346	password, ok := findStringField(payload, "password", "token")
347	if args.Username != "" && ok && password != "" {
348		_, _ = p.accountStore.CreateAccount(args.Username, password, mysisID)
349	}
350}
351
352func (p *Proxy) handleLoginResponse(arguments json.RawMessage, result *ToolResult, mysisID string) {
353	var args struct {
354		Username string `json:"username"`
355	}
356	if err := json.Unmarshal(arguments, &args); err != nil {
357		return
358	}
359
360	if args.Username != "" {
361		_ = p.accountStore.AssignAccount(args.Username, mysisID)
362	}
363}
364
365func (p *Proxy) handleLogoutResponse(arguments json.RawMessage, result *ToolResult) {
366	payload, ok := parseToolResultPayload(result)
367	if !ok {
368		return
369	}
370
371	username, ok := findStringFieldAtPath(payload, "player", "username")
372	if !ok {
373		username, _ = findStringField(payload, "username")
374	}
375
376	if username != "" {
377		// Clear game state cache on logout (but keep account assignment)
378		if p.gameStateStore != nil {
379			_ = p.gameStateStore.DeleteGameStateSnapshotsForUsername(username)
380		}
381	}
382}
383
384// injectPasswordIntoResult adds the password field to a tool result payload.
385// This is used when substituting register with pool account login, since login
386// responses don't include the password but the mysis expects it (to match register behavior).
387func (p *Proxy) injectPasswordIntoResult(result *ToolResult, password string) {
388	if result == nil || len(result.Content) == 0 {
389		return
390	}
391
392	// Find the text content block with JSON payload
393	for i := range result.Content {
394		if result.Content[i].Type == "text" {
395			var data map[string]interface{}
396			if err := json.Unmarshal([]byte(result.Content[i].Text), &data); err == nil {
397				// Add password to the payload
398				data["password"] = password
399				// Re-marshal and update the content
400				if updatedJSON, err := json.Marshal(data); err == nil {
401					result.Content[i].Text = string(updatedJSON)
402				}
403				return
404			}
405		}
406	}
407}
408
409// tryClaimPoolAccount attempts to claim an available account from the pool.
410// Returns the account if one is available, nil otherwise.
411func (p *Proxy) tryClaimPoolAccount(mysisID string) *Account {
412	p.mu.RLock()
413	accountStore := p.accountStore
414	p.mu.RUnlock()
415
416	if accountStore == nil {
417		return nil
418	}
419
420	// Try to claim an account from the pool
421	type accountClaimer interface {
422		ClaimAccount(mysisID string) (*Account, error)
423	}
424
425	if claimer, ok := accountStore.(accountClaimer); ok {
426		account, err := claimer.ClaimAccount(mysisID)
427		if err == nil && account != nil {
428			return account
429		}
430	}
431
432	return nil
433}
434
435func parseToolResultPayload(result *ToolResult) (interface{}, bool) {
436	if result == nil {
437		return nil, false
438	}
439
440	content := strings.TrimSpace(joinToolResultText(result))
441	if content == "" {
442		return nil, false
443	}
444	if !strings.HasPrefix(content, "{") && !strings.HasPrefix(content, "[") {
445		return nil, false
446	}
447
448	decoder := json.NewDecoder(strings.NewReader(content))
449	decoder.UseNumber()
450	var payload interface{}
451	if err := decoder.Decode(&payload); err != nil {
452		return nil, false
453	}
454
455	return payload, true
456}
457
458func joinToolResultText(result *ToolResult) string {
459	if result == nil {
460		return ""
461	}
462
463	var parts []string
464	for _, block := range result.Content {
465		if block.Type == "text" {
466			parts = append(parts, block.Text)
467		}
468	}
469	return strings.Join(parts, "\n")
470}
471
472func findStringField(payload interface{}, keys ...string) (string, bool) {
473	queue := []interface{}{payload}
474
475	for len(queue) > 0 {
476		current := queue[0]
477		queue = queue[1:]
478
479		switch value := current.(type) {
480		case map[string]interface{}:
481			for _, key := range keys {
482				if raw, ok := value[key]; ok {
483					if str, ok := raw.(string); ok {
484						return str, true
485					}
486				}
487			}
488
489			for _, child := range value {
490				queue = append(queue, child)
491			}
492		case []interface{}:
493			queue = append(queue, value...)
494		}
495	}
496
497	return "", false
498}
499
500func findStringFieldAtPath(payload interface{}, path ...string) (string, bool) {
501	current, ok := payload.(map[string]interface{})
502	if !ok {
503		return "", false
504	}
505
506	for i, key := range path {
507		value, exists := current[key]
508		if !exists {
509			return "", false
510		}
511		if i == len(path)-1 {
512			str, ok := value.(string)
513			return str, ok
514		}
515		next, ok := value.(map[string]interface{})
516		if !ok {
517			return "", false
518		}
519		current = next
520	}
521
522	return "", false
523}
524
525// Initialize initializes the upstream connection if available.
526func (p *Proxy) Initialize(ctx context.Context) error {
527	if p.upstream == nil {
528		return nil
529	}
530
531	clientInfo := map[string]interface{}{
532		"name":    "zoea-nova",
533		"version": "0.1.0",
534	}
535
536	resp, err := p.upstream.Initialize(ctx, clientInfo)
537	if err != nil {
538		return fmt.Errorf("initialize upstream: %w", err)
539	}
540
541	if resp.Error != nil {
542		return fmt.Errorf("upstream error: %s", resp.Error.Message)
543	}
544
545	return nil
546}
547
548// HasUpstream returns true if an upstream client is configured.
549func (p *Proxy) HasUpstream() bool {
550	return p.upstream != nil
551}
552
553// LocalToolCount returns the number of registered local tools.
554func (p *Proxy) LocalToolCount() int {
555	p.mu.RLock()
556	defer p.mu.RUnlock()
557	return len(p.localTools)
558}
559
560// Close closes the upstream client connection if available.
561func (p *Proxy) Close() error {
562	p.mu.RLock()
563	upstream := p.upstream
564	p.mu.RUnlock()
565
566	if upstream != nil {
567		if closer, ok := upstream.(interface{ Close() error }); ok {
568			return closer.Close()
569		}
570	}
571	return nil
572}