@@ -13,6 +13,7 @@ import (
1313
1414 "github.com/rs/zerolog/log"
1515 "github.com/xonecas/zoea-nova/internal/constants"
16+ "github.com/xonecas/zoea-nova/internal/gamestate"
1617 "github.com/xonecas/zoea-nova/internal/mcp"
1718 "github.com/xonecas/zoea-nova/internal/provider"
1819 "github.com/xonecas/zoea-nova/internal/store"
@@ -435,16 +436,16 @@ type accountStoreAdapter struct {
435436 store *store.Store
436437 }
437438
438-func (a *accountStoreAdapter) CreateAccount(username, password string) (*mcp.Account, error) {
439- acc, err := a.store.CreateAccount(username, password)
439+func (a *accountStoreAdapter) CreateAccount(username, password string, mysisID ...string) (*mcp.Account, error) {
440+ acc, err := a.store.CreateAccount(username, password, mysisID...)
440441 if err != nil {
441442 return nil, err
442443 }
443444 return &mcp.Account{Username: acc.Username, Password: acc.Password}, nil
444445 }
445446
446-func (a *accountStoreAdapter) MarkAccountInUse(username string) error {
447- return a.store.MarkAccountInUse(username)
447+func (a *accountStoreAdapter) MarkAccountInUse(username, mysisID string) error {
448+ return a.store.MarkAccountInUse(username, mysisID)
448449 }
449450
450451 func (a *accountStoreAdapter) ReleaseAccount(username string) error {
@@ -455,8 +456,8 @@ func (a *accountStoreAdapter) ReleaseAllAccounts() error {
455456 return a.store.ReleaseAllAccounts()
456457 }
457458
458-func (a *accountStoreAdapter) ClaimAccount() (*mcp.Account, error) {
459- acc, err := a.store.ClaimAccount()
459+func (a *accountStoreAdapter) ClaimAccount(mysisID string) (*mcp.Account, error) {
460+ acc, err := a.store.ClaimAccount(mysisID)
460461 if err != nil {
461462 return nil, err
462463 }
@@ -620,6 +621,28 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
620621 if mcpProxy != nil {
621622 mcpTools, err := mcpProxy.ListTools(ctx)
622623 if err != nil {
624+ if isMCPConnectionLost(err) {
625+ log.Warn().
626+ Str("mysis", a.name).
627+ Err(err).
628+ Msg("MCP connection lost - releasing account")
629+ a.releaseCurrentAccount()
630+ if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
631+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
632+ }
633+ }
634+
635+ // Check if this is a session expiration error
636+ if strings.Contains(err.Error(), "Session not initialized") || strings.Contains(err.Error(), "-32600") {
637+ log.Warn().
638+ Str("mysis", a.name).
639+ Err(err).
640+ Msg("MCP session expired - attempting reinitialization")
641+
642+ // Trigger MCP reinitialization in background
643+ go a.initializeMCP(parentCtx)
644+ }
645+
623646 // Log error but continue - mysis can still chat without tools
624647 a.publishCriticalEvent(Event{
625648 Type: EventMysisError,
@@ -1055,6 +1078,17 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
10551078 }
10561079
10571080 result, err := mcpProxy.CallTool(ctx, caller, tc.Name, tc.Arguments)
1081+ if err != nil && isMCPConnectionLost(err) {
1082+ log.Warn().
1083+ Str("mysis", a.name).
1084+ Str("tool", tc.Name).
1085+ Err(err).
1086+ Msg("MCP connection lost during tool call - releasing account")
1087+ a.releaseCurrentAccount()
1088+ if rebuildErr := a.rebuildSystemMemory(); rebuildErr != nil {
1089+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after MCP session loss")
1090+ }
1091+ }
10581092 if err == nil && result != nil && !result.IsError {
10591093 switch tc.Name {
10601094 case "login", "register":
@@ -1103,10 +1137,11 @@ func (m *Mysis) executeToolCall(ctx context.Context, mcpProxy *mcp.Proxy, tc pro
11031137
11041138 func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11051139 m.mu.Lock()
1106- defer m.mu.Unlock()
1140+ storeRef := m.store
11071141
11081142 // Ignore empty username (no-op)
11091143 if username == "" {
1144+ m.mu.Unlock()
11101145 return
11111146 }
11121147
@@ -1119,6 +1154,13 @@ func (m *Mysis) setCurrentAccount(username, password, sessionID string) {
11191154 m.currentAccountUsername = username
11201155 m.currentPassword = password
11211156 m.currentSessionID = sessionID
1157+ m.mu.Unlock()
1158+
1159+ if storeRef != nil {
1160+ if err := storeRef.MarkAccountInUse(username, m.id); err != nil {
1161+ log.Error().Err(err).Str("username", username).Msg("failed to mark account in use")
1162+ }
1163+ }
11221164 }
11231165
11241166 func (m *Mysis) releaseCurrentAccount() {
@@ -1271,6 +1313,28 @@ func isToolRetryExhausted(err error) bool {
12711313 return errors.Is(err, mcp.ErrToolRetryExhausted)
12721314 }
12731315
1316+func isMCPConnectionLost(err error) bool {
1317+ if err == nil {
1318+ return false
1319+ }
1320+ return isMCPConnectionLostMessage(err.Error())
1321+}
1322+
1323+func isMCPConnectionLostMessage(message string) bool {
1324+ if message == "" {
1325+ return false
1326+ }
1327+ msg := strings.ToLower(message)
1328+ return strings.Contains(msg, "session not initialized") ||
1329+ strings.Contains(msg, "-32600") ||
1330+ strings.Contains(msg, "connection refused") ||
1331+ strings.Contains(msg, "connection reset") ||
1332+ strings.Contains(msg, "no such host") ||
1333+ strings.Contains(msg, "dial tcp") ||
1334+ strings.Contains(msg, "unexpected eof") ||
1335+ strings.Contains(msg, "eof")
1336+}
1337+
12741338 // formatToolResultDisplay formats a tool result for UI display (human-readable).
12751339 func (m *Mysis) formatToolResultDisplay(result *mcp.ToolResult, err error) string {
12761340 if err != nil {
@@ -1922,10 +1986,11 @@ func (m *Mysis) buildGameStateSummary() string {
19221986 recency := snapshot.RecencyMessage(currentTick)
19231987 summary.WriteString(fmt.Sprintf("### %s (%s)\n", toolName, recency))
19241988
1925- // Parse and extract key fields for compact display
1926- compactInfo := extractCompactInfo(snapshot.Content, toolName)
1927- if compactInfo != "" {
1928- summary.WriteString(compactInfo)
1989+ // Render a safe summary without schema assumptions
1990+ lines := gamestate.SnapshotLines(snapshot.Content)
1991+ for _, line := range lines {
1992+ summary.WriteString("- ")
1993+ summary.WriteString(line)
19291994 summary.WriteString("\n")
19301995 }
19311996 summary.WriteString("\n")
@@ -1946,58 +2011,6 @@ func (m *Mysis) buildGameStateSummary() string {
19462011 return summary.String()
19472012 }
19482013
1949-// extractCompactInfo extracts key information from a snapshot for compact display.
1950-func extractCompactInfo(content, toolName string) string {
1951- // Parse JSON content
1952- var data interface{}
1953- decoder := json.NewDecoder(strings.NewReader(content))
1954- decoder.UseNumber()
1955- if err := decoder.Decode(&data); err != nil {
1956- return ""
1957- }
1958-
1959- var info strings.Builder
1960-
1961- switch toolName {
1962- case "get_status", "get_player":
1963- if credits, ok := findIntField(data, "credits", "balance"); ok {
1964- info.WriteString(fmt.Sprintf("- Credits: %d\n", credits))
1965- }
1966- if location, ok := findStringField(data, "location", "current_location"); ok {
1967- info.WriteString(fmt.Sprintf("- Location: %s\n", location))
1968- }
1969- if ship, ok := findStringField(data, "ship", "ship_name"); ok {
1970- info.WriteString(fmt.Sprintf("- Ship: %s\n", ship))
1971- }
1972-
1973- case "get_ship":
1974- if hull, ok := findIntField(data, "hull", "hull_health"); ok {
1975- info.WriteString(fmt.Sprintf("- Hull: %d\n", hull))
1976- }
1977- if fuel, ok := findIntField(data, "fuel", "fuel_level"); ok {
1978- info.WriteString(fmt.Sprintf("- Fuel: %d\n", fuel))
1979- }
1980- if cargo, ok := findIntField(data, "cargo_used", "cargo"); ok {
1981- info.WriteString(fmt.Sprintf("- Cargo: %d\n", cargo))
1982- }
1983-
1984- case "get_system", "get_location":
1985- if system, ok := findStringField(data, "system", "system_name"); ok {
1986- info.WriteString(fmt.Sprintf("- System: %s\n", system))
1987- }
1988- if faction, ok := findStringField(data, "faction", "controlling_faction"); ok {
1989- info.WriteString(fmt.Sprintf("- Faction: %s\n", faction))
1990- }
1991-
1992- case "get_map", "get_galaxy":
1993- if systemCount, ok := findIntField(data, "system_count", "systems"); ok {
1994- info.WriteString(fmt.Sprintf("- Systems: %d\n", systemCount))
1995- }
1996- }
1997-
1998- return info.String()
1999-}
2000-
20012014 // rebuildSystemMemory rebuilds the system memory with current state
20022015 func (m *Mysis) rebuildSystemMemory() error {
20032016 // Build new system prompt with current credentials and broadcasts
@@ -2122,7 +2135,11 @@ func (m *Mysis) cacheSnapshotToolResult(toolName string, result *mcp.ToolResult,
21222135 }
21232136
21242137 // Store in cache (ignore errors - caching is best-effort)
2125- _ = m.store.StoreGameStateSnapshot(username, toolName, content.String(), gameTick)
2138+ if err := m.store.StoreGameStateSnapshot(username, toolName, content.String(), gameTick); err == nil {
2139+ if rebuildErr := m.rebuildSystemMemory(); rebuildErr != nil {
2140+ log.Error().Err(rebuildErr).Msg("failed to rebuild system memory after snapshot update")
2141+ }
2142+ }
21262143 }
21272144
21282145 func (m *Mysis) setActivity(state ActivityState, until time.Time) {