Spaces:
Sleeping
Sleeping
Upload 4 files
Browse files- requirements_mcp.txt +31 -0
- utils/__init__.py +1 -0
- utils/agent_factory.py +142 -0
- utils/pokemon_utils.py +600 -0
requirements_mcp.txt
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pokemon Battle MCP Server Requirements
|
| 2 |
+
|
| 3 |
+
# MCP Framework
|
| 4 |
+
fastmcp
|
| 5 |
+
|
| 6 |
+
# Pokemon Environment
|
| 7 |
+
poke-env
|
| 8 |
+
|
| 9 |
+
# AI API Libraries
|
| 10 |
+
openai
|
| 11 |
+
google-genai
|
| 12 |
+
mistralai
|
| 13 |
+
|
| 14 |
+
# Core Python Libraries
|
| 15 |
+
asyncio-mqtt
|
| 16 |
+
python-dotenv
|
| 17 |
+
requests
|
| 18 |
+
tabulate
|
| 19 |
+
|
| 20 |
+
# Data Processing
|
| 21 |
+
pandas
|
| 22 |
+
matplotlib
|
| 23 |
+
seaborn
|
| 24 |
+
|
| 25 |
+
# Standard libraries (these come with Python but listed for clarity)
|
| 26 |
+
# asyncio
|
| 27 |
+
# os
|
| 28 |
+
# json
|
| 29 |
+
# random
|
| 30 |
+
# time
|
| 31 |
+
# typing
|
utils/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Utils package for Pokemon MCP server
|
utils/agent_factory.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
from poke_env import AccountConfiguration, ServerConfiguration
|
| 3 |
+
from poke_env.player.random_player import RandomPlayer
|
| 4 |
+
from agents import OpenAIAgent, GeminiAgent, MistralAgent, MaxDamagePlayer
|
| 5 |
+
|
| 6 |
+
# Custom server configuration
|
| 7 |
+
CUSTOM_SERVER_URL = "wss://jofthomas.com/showdown/websocket"
|
| 8 |
+
CUSTOM_ACTION_URL = 'https://play.pokemonshowdown.com/action.php?'
|
| 9 |
+
custom_config = ServerConfiguration(CUSTOM_SERVER_URL, CUSTOM_ACTION_URL)
|
| 10 |
+
|
| 11 |
+
# Avatar mappings for different agent types
|
| 12 |
+
AGENT_AVATARS = {
|
| 13 |
+
'openai': ['giovanni', 'lusamine', 'guzma'],
|
| 14 |
+
'mistral': ['alder', 'lance', 'cynthia'],
|
| 15 |
+
'gemini': ['steven', 'diantha', 'leon'],
|
| 16 |
+
'maxdamage': ['red'],
|
| 17 |
+
'random': ['youngster']
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
def create_agent(agent_type: str, api_key: str = None, model: str = None, username_suffix: str = None):
|
| 21 |
+
"""
|
| 22 |
+
Factory function to create different types of Pokemon agents.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
agent_type (str): Type of agent ('openai', 'gemini', 'mistral', 'maxdamage', 'random')
|
| 26 |
+
api_key (str, optional): API key for AI agents
|
| 27 |
+
model (str, optional): Specific model to use
|
| 28 |
+
username_suffix (str, optional): Suffix for username uniqueness
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Player: A Pokemon battle agent
|
| 32 |
+
"""
|
| 33 |
+
if not username_suffix:
|
| 34 |
+
username_suffix = str(random.randint(1000, 9999))
|
| 35 |
+
|
| 36 |
+
agent_type = agent_type.lower()
|
| 37 |
+
|
| 38 |
+
if agent_type == 'openai':
|
| 39 |
+
if not api_key:
|
| 40 |
+
raise ValueError("API key required for OpenAI agent")
|
| 41 |
+
|
| 42 |
+
model = model or "gpt-4o"
|
| 43 |
+
username = f"OpenAI-{username_suffix}"
|
| 44 |
+
avatar = random.choice(AGENT_AVATARS['openai'])
|
| 45 |
+
|
| 46 |
+
return OpenAIAgent(
|
| 47 |
+
account_configuration=AccountConfiguration(username, None),
|
| 48 |
+
server_configuration=custom_config,
|
| 49 |
+
api_key=api_key,
|
| 50 |
+
model=model,
|
| 51 |
+
avatar=avatar,
|
| 52 |
+
max_concurrent_battles=1,
|
| 53 |
+
battle_delay=0.1,
|
| 54 |
+
save_replays="battle_replays",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
elif agent_type == 'gemini':
|
| 58 |
+
if not api_key:
|
| 59 |
+
raise ValueError("API key required for Gemini agent")
|
| 60 |
+
|
| 61 |
+
model = model or "gemini-1.5-flash"
|
| 62 |
+
username = f"Gemini-{username_suffix}"
|
| 63 |
+
avatar = random.choice(AGENT_AVATARS['gemini'])
|
| 64 |
+
|
| 65 |
+
return GeminiAgent(
|
| 66 |
+
account_configuration=AccountConfiguration(username, None),
|
| 67 |
+
server_configuration=custom_config,
|
| 68 |
+
api_key=api_key,
|
| 69 |
+
model=model,
|
| 70 |
+
avatar=avatar,
|
| 71 |
+
max_concurrent_battles=1,
|
| 72 |
+
battle_delay=0.1,
|
| 73 |
+
save_replays="battle_replays",
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
elif agent_type == 'mistral':
|
| 77 |
+
if not api_key:
|
| 78 |
+
raise ValueError("API key required for Mistral agent")
|
| 79 |
+
|
| 80 |
+
model = model or "mistral-large-latest"
|
| 81 |
+
username = f"Mistral-{username_suffix}"
|
| 82 |
+
avatar = random.choice(AGENT_AVATARS['mistral'])
|
| 83 |
+
|
| 84 |
+
return MistralAgent(
|
| 85 |
+
account_configuration=AccountConfiguration(username, None),
|
| 86 |
+
server_configuration=custom_config,
|
| 87 |
+
api_key=api_key,
|
| 88 |
+
model=model,
|
| 89 |
+
avatar=avatar,
|
| 90 |
+
max_concurrent_battles=1,
|
| 91 |
+
battle_delay=0.1,
|
| 92 |
+
save_replays="battle_replays",
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
elif agent_type == 'maxdamage':
|
| 96 |
+
username = f"MaxDamage-{username_suffix}"
|
| 97 |
+
avatar = random.choice(AGENT_AVATARS['maxdamage'])
|
| 98 |
+
|
| 99 |
+
return MaxDamagePlayer(
|
| 100 |
+
account_configuration=AccountConfiguration(username, None),
|
| 101 |
+
server_configuration=custom_config,
|
| 102 |
+
max_concurrent_battles=1,
|
| 103 |
+
save_replays="battle_replays",
|
| 104 |
+
avatar=avatar,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
elif agent_type == 'random':
|
| 108 |
+
username = f"Random-{username_suffix}"
|
| 109 |
+
avatar = random.choice(AGENT_AVATARS['random'])
|
| 110 |
+
|
| 111 |
+
return RandomPlayer(
|
| 112 |
+
account_configuration=AccountConfiguration(username, None),
|
| 113 |
+
server_configuration=custom_config,
|
| 114 |
+
max_concurrent_battles=1,
|
| 115 |
+
save_replays="battle_replays",
|
| 116 |
+
avatar=avatar,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
else:
|
| 120 |
+
raise ValueError(f"Unknown agent type: {agent_type}. Supported types: openai, gemini, mistral, maxdamage, random")
|
| 121 |
+
|
| 122 |
+
def get_supported_agent_types():
|
| 123 |
+
"""
|
| 124 |
+
Returns a list of supported agent types.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
list: List of supported agent type strings
|
| 128 |
+
"""
|
| 129 |
+
return ['openai', 'gemini', 'mistral', 'maxdamage', 'random']
|
| 130 |
+
|
| 131 |
+
def get_default_models():
|
| 132 |
+
"""
|
| 133 |
+
Returns default models for each AI agent type.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
dict: Mapping of agent types to default models
|
| 137 |
+
"""
|
| 138 |
+
return {
|
| 139 |
+
'openai': 'gpt-4o',
|
| 140 |
+
'gemini': 'gemini-1.5-flash',
|
| 141 |
+
'mistral': 'mistral-large-latest'
|
| 142 |
+
}
|
utils/pokemon_utils.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import random
|
| 4 |
+
import uuid
|
| 5 |
+
from typing import Optional, Dict, Any, List, Union
|
| 6 |
+
from poke_env import AccountConfiguration, ServerConfiguration
|
| 7 |
+
from poke_env.player import Player
|
| 8 |
+
from poke_env.environment.battle import Battle
|
| 9 |
+
from poke_env.environment.move import Move
|
| 10 |
+
from poke_env.environment.pokemon import Pokemon
|
| 11 |
+
from agents import LLMAgentBase
|
| 12 |
+
|
| 13 |
+
# Custom server configuration
|
| 14 |
+
CUSTOM_SERVER_URL = "wss://jofthomas.com/showdown/websocket"
|
| 15 |
+
CUSTOM_ACTION_URL = 'https://play.pokemonshowdown.com/action.php?'
|
| 16 |
+
custom_config = ServerConfiguration(CUSTOM_SERVER_URL, CUSTOM_ACTION_URL)
|
| 17 |
+
|
| 18 |
+
# Global battle state management
|
| 19 |
+
active_battles = {}
|
| 20 |
+
player_instances = {}
|
| 21 |
+
|
| 22 |
+
class MCPPokemonAgent(LLMAgentBase):
|
| 23 |
+
"""
|
| 24 |
+
Special Pokemon agent controlled by MCP that allows external move selection.
|
| 25 |
+
"""
|
| 26 |
+
def __init__(self, username: str, *args, **kwargs):
|
| 27 |
+
# Add random suffix to make username unique
|
| 28 |
+
unique_username = f"{username}_{random.randint(1000, 9999)}"
|
| 29 |
+
account_config = AccountConfiguration(unique_username, None)
|
| 30 |
+
super().__init__(
|
| 31 |
+
account_configuration=account_config,
|
| 32 |
+
server_configuration=custom_config,
|
| 33 |
+
max_concurrent_battles=1,
|
| 34 |
+
save_replays="battle_replays",
|
| 35 |
+
avatar="ash",
|
| 36 |
+
log_level=25, # Reduce logging verbosity
|
| 37 |
+
*args, **kwargs
|
| 38 |
+
)
|
| 39 |
+
self.external_move_queue = asyncio.Queue()
|
| 40 |
+
self.battle_state_callback = None
|
| 41 |
+
self.current_battle_id = None
|
| 42 |
+
|
| 43 |
+
async def choose_move(self, battle: Battle) -> str:
|
| 44 |
+
"""Wait for external move selection via MCP"""
|
| 45 |
+
self.current_battle_id = battle.battle_tag
|
| 46 |
+
|
| 47 |
+
# Update active battle state
|
| 48 |
+
if battle.battle_tag in active_battles:
|
| 49 |
+
active_battles[battle.battle_tag]['battle_state'] = self._format_battle_state(battle)
|
| 50 |
+
active_battles[battle.battle_tag]['waiting_for_move'] = True
|
| 51 |
+
active_battles[battle.battle_tag]['available_moves'] = [move.id for move in battle.available_moves]
|
| 52 |
+
active_battles[battle.battle_tag]['available_switches'] = [pkmn.species for pkmn in battle.available_switches]
|
| 53 |
+
|
| 54 |
+
try:
|
| 55 |
+
# Wait for external move selection (with timeout)
|
| 56 |
+
move_order = await asyncio.wait_for(self.external_move_queue.get(), timeout=30.0)
|
| 57 |
+
|
| 58 |
+
# Update battle state
|
| 59 |
+
if battle.battle_tag in active_battles:
|
| 60 |
+
active_battles[battle.battle_tag]['waiting_for_move'] = False
|
| 61 |
+
|
| 62 |
+
return move_order
|
| 63 |
+
except asyncio.TimeoutError:
|
| 64 |
+
print(f"Move selection timeout for battle {battle.battle_tag}, choosing random move")
|
| 65 |
+
if battle.battle_tag in active_battles:
|
| 66 |
+
active_battles[battle.battle_tag]['waiting_for_move'] = False
|
| 67 |
+
return self.choose_random_move(battle)
|
| 68 |
+
|
| 69 |
+
async def submit_move(self, move_name: str = None, pokemon_name: str = None, battle: Battle = None):
|
| 70 |
+
"""Submit a move or switch externally"""
|
| 71 |
+
if not battle and self.current_battle_id:
|
| 72 |
+
# Find the battle by ID
|
| 73 |
+
for battle_obj in self.battles.values():
|
| 74 |
+
if battle_obj.battle_tag == self.current_battle_id:
|
| 75 |
+
battle = battle_obj
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
if not battle:
|
| 79 |
+
raise ValueError("No active battle found")
|
| 80 |
+
|
| 81 |
+
if move_name:
|
| 82 |
+
# Find and execute move
|
| 83 |
+
chosen_move = self._find_move_by_name(battle, move_name)
|
| 84 |
+
if chosen_move and chosen_move in battle.available_moves:
|
| 85 |
+
move_order = self.create_order(chosen_move)
|
| 86 |
+
await self.external_move_queue.put(move_order)
|
| 87 |
+
return f"Submitted move: {chosen_move.id}"
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError(f"Move '{move_name}' not available")
|
| 90 |
+
|
| 91 |
+
elif pokemon_name:
|
| 92 |
+
# Find and execute switch
|
| 93 |
+
chosen_switch = self._find_pokemon_by_name(battle, pokemon_name)
|
| 94 |
+
if chosen_switch and chosen_switch in battle.available_switches:
|
| 95 |
+
switch_order = self.create_order(chosen_switch)
|
| 96 |
+
await self.external_move_queue.put(switch_order)
|
| 97 |
+
return f"Submitted switch: {chosen_switch.species}"
|
| 98 |
+
else:
|
| 99 |
+
raise ValueError(f"Pokemon '{pokemon_name}' not available for switch")
|
| 100 |
+
|
| 101 |
+
else:
|
| 102 |
+
raise ValueError("Must specify either move_name or pokemon_name")
|
| 103 |
+
|
| 104 |
+
def normalize_name(name: str) -> str:
|
| 105 |
+
"""Lowercase and remove non-alphanumeric characters."""
|
| 106 |
+
return "".join(filter(str.isalnum, name)).lower()
|
| 107 |
+
|
| 108 |
+
def format_battle_state(battle: Battle) -> Dict[str, Any]:
|
| 109 |
+
"""
|
| 110 |
+
Format battle state into a structured dictionary.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
battle (Battle): The current battle object
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
dict: Formatted battle state
|
| 117 |
+
"""
|
| 118 |
+
active_pkmn = battle.active_pokemon
|
| 119 |
+
opponent_pkmn = battle.opponent_active_pokemon
|
| 120 |
+
|
| 121 |
+
# Format active Pokemon info
|
| 122 |
+
try:
|
| 123 |
+
active_info = {
|
| 124 |
+
'species': getattr(active_pkmn, 'species', 'unknown') if active_pkmn else None,
|
| 125 |
+
'types': [str(t) for t in getattr(active_pkmn, 'types', [])] if active_pkmn else [],
|
| 126 |
+
'hp_fraction': getattr(active_pkmn, 'current_hp_fraction', 0) if active_pkmn else 0,
|
| 127 |
+
'status': getattr(active_pkmn.status, 'name', None) if active_pkmn and hasattr(active_pkmn, 'status') and active_pkmn.status else None,
|
| 128 |
+
'boosts': dict(getattr(active_pkmn, 'boosts', {})) if active_pkmn else {},
|
| 129 |
+
'ability': str(active_pkmn.ability) if active_pkmn and hasattr(active_pkmn, 'ability') and active_pkmn.ability else None
|
| 130 |
+
}
|
| 131 |
+
except Exception as e:
|
| 132 |
+
active_info = {
|
| 133 |
+
'species': 'error',
|
| 134 |
+
'types': [],
|
| 135 |
+
'hp_fraction': 0,
|
| 136 |
+
'status': None,
|
| 137 |
+
'boosts': {},
|
| 138 |
+
'ability': None,
|
| 139 |
+
'error': f"Error formatting active Pokemon: {e}"
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
# Format opponent Pokemon info
|
| 143 |
+
try:
|
| 144 |
+
opponent_info = {
|
| 145 |
+
'species': getattr(opponent_pkmn, 'species', 'unknown') if opponent_pkmn else None,
|
| 146 |
+
'types': [str(t) for t in getattr(opponent_pkmn, 'types', [])] if opponent_pkmn else [],
|
| 147 |
+
'hp_fraction': getattr(opponent_pkmn, 'current_hp_fraction', 0) if opponent_pkmn else 0,
|
| 148 |
+
'status': getattr(opponent_pkmn.status, 'name', None) if opponent_pkmn and hasattr(opponent_pkmn, 'status') and opponent_pkmn.status else None,
|
| 149 |
+
'boosts': dict(getattr(opponent_pkmn, 'boosts', {})) if opponent_pkmn else {},
|
| 150 |
+
'ability': str(opponent_pkmn.ability) if opponent_pkmn and hasattr(opponent_pkmn, 'ability') and opponent_pkmn.ability else None
|
| 151 |
+
}
|
| 152 |
+
except Exception as e:
|
| 153 |
+
opponent_info = {
|
| 154 |
+
'species': 'error',
|
| 155 |
+
'types': [],
|
| 156 |
+
'hp_fraction': 0,
|
| 157 |
+
'status': None,
|
| 158 |
+
'boosts': {},
|
| 159 |
+
'ability': None,
|
| 160 |
+
'error': f"Error formatting opponent Pokemon: {e}"
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# Format available moves
|
| 164 |
+
available_moves = []
|
| 165 |
+
if battle.available_moves:
|
| 166 |
+
for move in battle.available_moves:
|
| 167 |
+
try:
|
| 168 |
+
available_moves.append({
|
| 169 |
+
'id': move.id,
|
| 170 |
+
'name': getattr(move, 'name', move.id), # Fallback to id if no name
|
| 171 |
+
'type': str(move.type) if hasattr(move, 'type') else 'unknown',
|
| 172 |
+
'base_power': getattr(move, 'base_power', 0),
|
| 173 |
+
'accuracy': getattr(move, 'accuracy', 100),
|
| 174 |
+
'pp': f"{getattr(move, 'current_pp', '?')}/{getattr(move, 'max_pp', '?')}",
|
| 175 |
+
'category': getattr(move.category, 'name', 'unknown') if hasattr(move, 'category') else 'unknown',
|
| 176 |
+
'description': getattr(move, 'description', '') or ""
|
| 177 |
+
})
|
| 178 |
+
except Exception as e:
|
| 179 |
+
# If there's any error with a specific move, add minimal info
|
| 180 |
+
available_moves.append({
|
| 181 |
+
'id': getattr(move, 'id', 'unknown'),
|
| 182 |
+
'name': str(move),
|
| 183 |
+
'type': 'unknown',
|
| 184 |
+
'base_power': 0,
|
| 185 |
+
'accuracy': 100,
|
| 186 |
+
'pp': '?/?',
|
| 187 |
+
'category': 'unknown',
|
| 188 |
+
'description': f"Error formatting move: {e}"
|
| 189 |
+
})
|
| 190 |
+
|
| 191 |
+
# Format available switches
|
| 192 |
+
available_switches = []
|
| 193 |
+
if battle.available_switches:
|
| 194 |
+
for pkmn in battle.available_switches:
|
| 195 |
+
try:
|
| 196 |
+
available_switches.append({
|
| 197 |
+
'species': getattr(pkmn, 'species', 'unknown'),
|
| 198 |
+
'hp_fraction': getattr(pkmn, 'current_hp_fraction', 0),
|
| 199 |
+
'status': getattr(pkmn.status, 'name', None) if hasattr(pkmn, 'status') and pkmn.status else None,
|
| 200 |
+
'types': [str(t) for t in getattr(pkmn, 'types', [])]
|
| 201 |
+
})
|
| 202 |
+
except Exception as e:
|
| 203 |
+
available_switches.append({
|
| 204 |
+
'species': 'error',
|
| 205 |
+
'hp_fraction': 0,
|
| 206 |
+
'status': None,
|
| 207 |
+
'types': [],
|
| 208 |
+
'error': f"Error formatting switch: {e}"
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
# Safely build the return dictionary
|
| 212 |
+
try:
|
| 213 |
+
result = {
|
| 214 |
+
'battle_id': getattr(battle, 'battle_tag', 'unknown'),
|
| 215 |
+
'turn': getattr(battle, 'turn', 0),
|
| 216 |
+
'active_pokemon': active_info,
|
| 217 |
+
'opponent_pokemon': opponent_info,
|
| 218 |
+
'available_moves': available_moves,
|
| 219 |
+
'available_switches': available_switches,
|
| 220 |
+
'weather': str(battle.weather) if hasattr(battle, 'weather') and battle.weather else None,
|
| 221 |
+
'fields': [str(field) for field in getattr(battle, 'fields', [])],
|
| 222 |
+
'side_conditions': [str(cond) for cond in getattr(battle, 'side_conditions', [])],
|
| 223 |
+
'opponent_side_conditions': [str(cond) for cond in getattr(battle, 'opponent_side_conditions', [])],
|
| 224 |
+
'force_switch': getattr(battle, 'force_switch', False),
|
| 225 |
+
'can_z_move': getattr(battle, 'can_z_move', False),
|
| 226 |
+
'can_dynamax': getattr(battle, 'can_dynamax', False),
|
| 227 |
+
'can_mega_evolve': getattr(battle, 'can_mega_evolve', False)
|
| 228 |
+
}
|
| 229 |
+
return result
|
| 230 |
+
except Exception as e:
|
| 231 |
+
# Fallback minimal battle state
|
| 232 |
+
return {
|
| 233 |
+
'battle_id': str(battle) if battle else 'error',
|
| 234 |
+
'turn': 0,
|
| 235 |
+
'active_pokemon': active_info,
|
| 236 |
+
'opponent_pokemon': opponent_info,
|
| 237 |
+
'available_moves': available_moves,
|
| 238 |
+
'available_switches': available_switches,
|
| 239 |
+
'weather': None,
|
| 240 |
+
'fields': [],
|
| 241 |
+
'side_conditions': [],
|
| 242 |
+
'opponent_side_conditions': [],
|
| 243 |
+
'force_switch': False,
|
| 244 |
+
'can_z_move': False,
|
| 245 |
+
'can_dynamax': False,
|
| 246 |
+
'can_mega_evolve': False,
|
| 247 |
+
'formatting_error': f"Error formatting battle state: {e}"
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
async def _start_ladder_task(player, username: str):
|
| 251 |
+
"""Background task to start ladder search - fire and forget"""
|
| 252 |
+
try:
|
| 253 |
+
await player.ladder(1) # Play 1 ladder battle
|
| 254 |
+
print(f"Ladder search started for {username}")
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"Failed to start ladder search for {username}: {e}")
|
| 257 |
+
|
| 258 |
+
def start_ladder_battle(username: str) -> Dict[str, str]:
|
| 259 |
+
"""
|
| 260 |
+
Start a ladder battle for the MCP-controlled player (fire-and-forget).
|
| 261 |
+
|
| 262 |
+
Args:
|
| 263 |
+
username (str): Username for the MCP player
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
dict: Status information about the ladder request
|
| 267 |
+
"""
|
| 268 |
+
if username in player_instances:
|
| 269 |
+
player = player_instances[username]
|
| 270 |
+
else:
|
| 271 |
+
player = MCPPokemonAgent(username)
|
| 272 |
+
player_instances[username] = player
|
| 273 |
+
|
| 274 |
+
# Start ladder battle (this will connect to showdown and find a match)
|
| 275 |
+
try:
|
| 276 |
+
# Start ladder search in background task (fire-and-forget)
|
| 277 |
+
asyncio.create_task(_start_ladder_task(player, username))
|
| 278 |
+
|
| 279 |
+
# Return immediately
|
| 280 |
+
return {
|
| 281 |
+
'status': 'ladder_search_queued',
|
| 282 |
+
'player_username': username,
|
| 283 |
+
'message': f'Ladder search queued for {username}. Use find_recent_battles() or get_player_status() to check when match is found.'
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
except Exception as e:
|
| 287 |
+
# Clean up player instance on failure
|
| 288 |
+
if username in player_instances:
|
| 289 |
+
del player_instances[username]
|
| 290 |
+
raise Exception(f"Failed to queue ladder search: {str(e)}")
|
| 291 |
+
|
| 292 |
+
async def start_battle_against_agent(username: str, opponent_agent, battle_format: str = "gen9randombattle") -> str:
|
| 293 |
+
"""
|
| 294 |
+
Start a battle against a specific agent.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
username (str): Username for the MCP player
|
| 298 |
+
opponent_agent: The opponent agent to battle against
|
| 299 |
+
battle_format (str): Battle format
|
| 300 |
+
|
| 301 |
+
Returns:
|
| 302 |
+
str: Battle ID
|
| 303 |
+
"""
|
| 304 |
+
if username in player_instances:
|
| 305 |
+
player = player_instances[username]
|
| 306 |
+
else:
|
| 307 |
+
player = MCPPokemonAgent(username)
|
| 308 |
+
player_instances[username] = player
|
| 309 |
+
|
| 310 |
+
try:
|
| 311 |
+
# Start battle against opponent
|
| 312 |
+
await player.battle_against(opponent_agent, n_battles=1)
|
| 313 |
+
|
| 314 |
+
# Wait for battle to start with shorter intervals for responsiveness
|
| 315 |
+
max_wait_time = 10 # Maximum 10 seconds
|
| 316 |
+
check_interval = 0.5 # Check every 0.5 seconds
|
| 317 |
+
wait_time = 0
|
| 318 |
+
|
| 319 |
+
while wait_time < max_wait_time:
|
| 320 |
+
await asyncio.sleep(check_interval)
|
| 321 |
+
wait_time += check_interval
|
| 322 |
+
|
| 323 |
+
# Check if a new battle has started
|
| 324 |
+
if player.battles:
|
| 325 |
+
battle_id = list(player.battles.keys())[-1]
|
| 326 |
+
battle = player.battles[battle_id]
|
| 327 |
+
|
| 328 |
+
# Store battle info
|
| 329 |
+
active_battles[battle_id] = {
|
| 330 |
+
'type': 'agent',
|
| 331 |
+
'player_username': username,
|
| 332 |
+
'opponent': opponent_agent.username,
|
| 333 |
+
'battle_state': format_battle_state(battle),
|
| 334 |
+
'waiting_for_move': False,
|
| 335 |
+
'completed': False,
|
| 336 |
+
'battle_url': f"https://jofthomas.com/play.pokemonshowdown.com/testclient.html#battle-{battle_id}"
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
return battle_id
|
| 340 |
+
|
| 341 |
+
# If we get here, no battle started within timeout
|
| 342 |
+
raise Exception(f"Battle against {opponent_agent.username} requested, but no battle started within {max_wait_time} seconds.")
|
| 343 |
+
|
| 344 |
+
except Exception as e:
|
| 345 |
+
raise Exception(f"Failed to start battle against agent: {str(e)}")
|
| 346 |
+
|
| 347 |
+
async def _send_challenge_task(player, opponent_username: str):
|
| 348 |
+
"""Background task to send challenge - fire and forget"""
|
| 349 |
+
try:
|
| 350 |
+
await player.send_challenges(opponent_username, n_challenges=1)
|
| 351 |
+
print(f"Challenge sent to {opponent_username}")
|
| 352 |
+
except Exception as e:
|
| 353 |
+
print(f"Failed to send challenge to {opponent_username}: {e}")
|
| 354 |
+
|
| 355 |
+
def start_battle_against_player(username: str, opponent_username: str) -> Dict[str, str]:
|
| 356 |
+
"""
|
| 357 |
+
Start a battle against a specific player (fire-and-forget).
|
| 358 |
+
|
| 359 |
+
Args:
|
| 360 |
+
username (str): Username for the MCP player
|
| 361 |
+
opponent_username (str): Username of the opponent
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
dict: Status information about the challenge request
|
| 365 |
+
"""
|
| 366 |
+
if username in player_instances:
|
| 367 |
+
player = player_instances[username]
|
| 368 |
+
else:
|
| 369 |
+
player = MCPPokemonAgent(username)
|
| 370 |
+
player_instances[username] = player
|
| 371 |
+
|
| 372 |
+
try:
|
| 373 |
+
# Start challenge in background task (fire-and-forget)
|
| 374 |
+
asyncio.create_task(_send_challenge_task(player, opponent_username))
|
| 375 |
+
|
| 376 |
+
# Return immediately
|
| 377 |
+
return {
|
| 378 |
+
'status': 'challenge_queued',
|
| 379 |
+
'player_username': username,
|
| 380 |
+
'opponent': opponent_username,
|
| 381 |
+
'message': f'Challenge to {opponent_username} queued. Use find_recent_battles() or get_player_status() to check if battle started.'
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
except Exception as e:
|
| 385 |
+
# Clean up player instance on failure
|
| 386 |
+
if username in player_instances:
|
| 387 |
+
del player_instances[username]
|
| 388 |
+
raise Exception(f"Failed to queue challenge to {opponent_username}: {str(e)}")
|
| 389 |
+
|
| 390 |
+
async def submit_move_for_battle(battle_id: str, move_name: str = None, pokemon_name: str = None) -> str:
|
| 391 |
+
"""
|
| 392 |
+
Submit a move or switch for a specific battle.
|
| 393 |
+
|
| 394 |
+
Args:
|
| 395 |
+
battle_id (str): The battle ID
|
| 396 |
+
move_name (str, optional): Name of move to use
|
| 397 |
+
pokemon_name (str, optional): Name of Pokemon to switch to
|
| 398 |
+
|
| 399 |
+
Returns:
|
| 400 |
+
str: Result message
|
| 401 |
+
"""
|
| 402 |
+
if battle_id not in active_battles:
|
| 403 |
+
raise ValueError(f"Battle {battle_id} not found")
|
| 404 |
+
|
| 405 |
+
battle_info = active_battles[battle_id]
|
| 406 |
+
username = battle_info['player_username']
|
| 407 |
+
|
| 408 |
+
if username not in player_instances:
|
| 409 |
+
raise ValueError(f"Player {username} not found")
|
| 410 |
+
|
| 411 |
+
player = player_instances[username]
|
| 412 |
+
|
| 413 |
+
# Find the battle object
|
| 414 |
+
battle = None
|
| 415 |
+
for battle_obj in player.battles.values():
|
| 416 |
+
if battle_obj.battle_tag == battle_id:
|
| 417 |
+
battle = battle_obj
|
| 418 |
+
break
|
| 419 |
+
|
| 420 |
+
if not battle:
|
| 421 |
+
raise ValueError(f"Battle object for {battle_id} not found")
|
| 422 |
+
|
| 423 |
+
# Submit the move
|
| 424 |
+
result = await player.submit_move(move_name=move_name, pokemon_name=pokemon_name, battle=battle)
|
| 425 |
+
|
| 426 |
+
# Update battle state
|
| 427 |
+
active_battles[battle_id]['battle_state'] = format_battle_state(battle)
|
| 428 |
+
|
| 429 |
+
return result
|
| 430 |
+
|
| 431 |
+
def get_battle_state(battle_id: str) -> Dict[str, Any]:
|
| 432 |
+
"""
|
| 433 |
+
Get the current state of a battle.
|
| 434 |
+
|
| 435 |
+
Args:
|
| 436 |
+
battle_id (str): The battle ID
|
| 437 |
+
|
| 438 |
+
Returns:
|
| 439 |
+
dict: Current battle state
|
| 440 |
+
"""
|
| 441 |
+
if battle_id not in active_battles:
|
| 442 |
+
raise ValueError(f"Battle {battle_id} not found")
|
| 443 |
+
|
| 444 |
+
return active_battles[battle_id]
|
| 445 |
+
|
| 446 |
+
def list_active_battles() -> List[Dict[str, Any]]:
|
| 447 |
+
"""
|
| 448 |
+
List all active battles.
|
| 449 |
+
|
| 450 |
+
Returns:
|
| 451 |
+
list: List of active battle info
|
| 452 |
+
"""
|
| 453 |
+
return [
|
| 454 |
+
{
|
| 455 |
+
'battle_id': battle_id,
|
| 456 |
+
'type': info['type'],
|
| 457 |
+
'opponent': info['opponent'],
|
| 458 |
+
'waiting_for_move': info['waiting_for_move'],
|
| 459 |
+
'completed': info['completed'],
|
| 460 |
+
'battle_url': info.get('battle_url', f"https://jofthomas.com/play.pokemonshowdown.com/testclient.html#battle-{battle_id}")
|
| 461 |
+
}
|
| 462 |
+
for battle_id, info in active_battles.items()
|
| 463 |
+
]
|
| 464 |
+
|
| 465 |
+
def check_recent_battles(username: str) -> List[Dict[str, Any]]:
|
| 466 |
+
"""
|
| 467 |
+
Check for recent battles that may have started after a timeout.
|
| 468 |
+
|
| 469 |
+
Args:
|
| 470 |
+
username (str): Username to check battles for
|
| 471 |
+
|
| 472 |
+
Returns:
|
| 473 |
+
list: List of recent battle info
|
| 474 |
+
"""
|
| 475 |
+
if username not in player_instances:
|
| 476 |
+
return []
|
| 477 |
+
|
| 478 |
+
player = player_instances[username]
|
| 479 |
+
recent_battles = []
|
| 480 |
+
|
| 481 |
+
for battle_id, battle in player.battles.items():
|
| 482 |
+
if battle_id not in active_battles:
|
| 483 |
+
# This is a new battle that wasn't tracked yet
|
| 484 |
+
battle_url = f"https://jofthomas.com/play.pokemonshowdown.com/testclient.html#battle-{battle_id}"
|
| 485 |
+
battle_info = {
|
| 486 |
+
'battle_id': battle_id,
|
| 487 |
+
'battle_url': battle_url,
|
| 488 |
+
'opponent': getattr(battle, 'opponent_username', 'unknown'),
|
| 489 |
+
'format': battle.format if hasattr(battle, 'format') else 'unknown',
|
| 490 |
+
'turn': battle.turn if hasattr(battle, 'turn') else 0,
|
| 491 |
+
'battle_state': format_battle_state(battle)
|
| 492 |
+
}
|
| 493 |
+
|
| 494 |
+
# Add to active battles tracking
|
| 495 |
+
active_battles[battle_id] = {
|
| 496 |
+
'type': 'recovered',
|
| 497 |
+
'player_username': username,
|
| 498 |
+
'opponent': battle_info['opponent'],
|
| 499 |
+
'battle_state': battle_info['battle_state'],
|
| 500 |
+
'waiting_for_move': False,
|
| 501 |
+
'completed': False,
|
| 502 |
+
'battle_url': battle_url
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
recent_battles.append(battle_info)
|
| 506 |
+
|
| 507 |
+
return recent_battles
|
| 508 |
+
|
| 509 |
+
async def download_battle_replay(battle_id: str) -> str:
|
| 510 |
+
"""
|
| 511 |
+
Download the replay for a completed battle.
|
| 512 |
+
|
| 513 |
+
Args:
|
| 514 |
+
battle_id (str): The battle ID
|
| 515 |
+
|
| 516 |
+
Returns:
|
| 517 |
+
str: Path to the replay file or replay content
|
| 518 |
+
"""
|
| 519 |
+
if battle_id not in active_battles:
|
| 520 |
+
raise ValueError(f"Battle {battle_id} not found")
|
| 521 |
+
|
| 522 |
+
battle_info = active_battles[battle_id]
|
| 523 |
+
username = battle_info['player_username']
|
| 524 |
+
|
| 525 |
+
if username not in player_instances:
|
| 526 |
+
raise ValueError(f"Player {username} not found")
|
| 527 |
+
|
| 528 |
+
player = player_instances[username]
|
| 529 |
+
|
| 530 |
+
# Find the battle object
|
| 531 |
+
battle = None
|
| 532 |
+
for battle_obj in player.battles.values():
|
| 533 |
+
if battle_obj.battle_tag == battle_id:
|
| 534 |
+
battle = battle_obj
|
| 535 |
+
break
|
| 536 |
+
|
| 537 |
+
if not battle:
|
| 538 |
+
raise ValueError(f"Battle object for {battle_id} not found")
|
| 539 |
+
|
| 540 |
+
# Check if replay exists
|
| 541 |
+
replay_dir = "battle_replays"
|
| 542 |
+
os.makedirs(replay_dir, exist_ok=True)
|
| 543 |
+
|
| 544 |
+
# Look for replay file
|
| 545 |
+
potential_files = [
|
| 546 |
+
f"{replay_dir}/{battle_id}.html",
|
| 547 |
+
f"{replay_dir}/{battle_id}.txt",
|
| 548 |
+
f"{replay_dir}/{battle.battle_tag}.html",
|
| 549 |
+
f"{replay_dir}/{battle.battle_tag}.txt"
|
| 550 |
+
]
|
| 551 |
+
|
| 552 |
+
for file_path in potential_files:
|
| 553 |
+
if os.path.exists(file_path):
|
| 554 |
+
return file_path
|
| 555 |
+
|
| 556 |
+
# If no replay file found, return the battle's replay data if available
|
| 557 |
+
if hasattr(battle, 'replay') and battle.replay:
|
| 558 |
+
replay_path = f"{replay_dir}/{battle_id}_replay.txt"
|
| 559 |
+
with open(replay_path, 'w') as f:
|
| 560 |
+
f.write(str(battle.replay))
|
| 561 |
+
return replay_path
|
| 562 |
+
|
| 563 |
+
raise ValueError(f"No replay found for battle {battle_id}")
|
| 564 |
+
|
| 565 |
+
def cleanup_completed_battles():
|
| 566 |
+
"""Clean up completed battles to free memory."""
|
| 567 |
+
global active_battles
|
| 568 |
+
active_battles = {
|
| 569 |
+
battle_id: info for battle_id, info in active_battles.items()
|
| 570 |
+
if not info.get('completed', False)
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
def debug_move_attributes(battle) -> Dict[str, Any]:
|
| 574 |
+
"""Debug function to inspect Move object attributes"""
|
| 575 |
+
debug_info = {
|
| 576 |
+
"available_moves_count": len(battle.available_moves) if hasattr(battle, 'available_moves') and battle.available_moves else 0,
|
| 577 |
+
"move_attributes": []
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
if hasattr(battle, 'available_moves') and battle.available_moves:
|
| 581 |
+
for i, move in enumerate(battle.available_moves[:3]): # Check first 3 moves only
|
| 582 |
+
try:
|
| 583 |
+
move_attrs = {
|
| 584 |
+
"move_index": i,
|
| 585 |
+
"move_type": type(move).__name__,
|
| 586 |
+
"available_attributes": [attr for attr in dir(move) if not attr.startswith('_')],
|
| 587 |
+
"str_representation": str(move),
|
| 588 |
+
"has_id": hasattr(move, 'id'),
|
| 589 |
+
"has_name": hasattr(move, 'name'),
|
| 590 |
+
"id_value": getattr(move, 'id', 'NO_ID'),
|
| 591 |
+
"name_value": getattr(move, 'name', 'NO_NAME') if hasattr(move, 'name') else 'NO_NAME_ATTR'
|
| 592 |
+
}
|
| 593 |
+
debug_info["move_attributes"].append(move_attrs)
|
| 594 |
+
except Exception as e:
|
| 595 |
+
debug_info["move_attributes"].append({
|
| 596 |
+
"move_index": i,
|
| 597 |
+
"error": str(e)
|
| 598 |
+
})
|
| 599 |
+
|
| 600 |
+
return debug_info
|