Skip to main content
Glama
rainhan99

Cloud Manage MCP Server

by rainhan99

get_aws_instance_info

Retrieve AWS EC2 instance details by providing a public IP address or instance ID to access configuration, status, and metadata information.

Instructions

获取AWS EC2实例信息(只读)

Args:
    ip_address_or_id (str): 公网IP地址或实例ID
    
Returns:
    Dict: AWS实例信息

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ip_address_or_idYes

Implementation Reference

  • main.py:324-340 (handler)
    MCP tool handler for get_aws_instance_info. Determines if input is instance ID (starts with 'i-') or IP address and delegates to aws_provider methods. Includes schema via type hints and docstring.
    @mcp.tool()
    def get_aws_instance_info(ip_address_or_id: str) -> Dict:
        """
        获取AWS EC2实例信息(只读)
        
        Args:
            ip_address_or_id (str): 公网IP地址或实例ID
            
        Returns:
            Dict: AWS实例信息
        """
        # 判断是IP地址还是实例ID
        if ip_address_or_id.startswith('i-'):
            return aws_provider.get_instance_by_id(ip_address_or_id)
        else:
            return aws_provider.get_instance_by_ip(ip_address_or_id)
  • Core helper method in AWSProvider class to query EC2 instance by public IP using boto3 describe_instances with 'ip-address' filter. Handles errors and formats response.
    def get_instance_by_ip(self, ip_address: str) -> Dict:
        """
        根据公网IP地址查找EC2实例
        
        Args:
            ip_address (str): 公网IP地址
            
        Returns:
            Dict: 实例信息或错误信息
        """
        if not self.available:
            return {
                'error': f'AWS服务不可用: {getattr(self, "error", "未知错误")}',
                'provider': 'aws'
            }
        
        try:
            # 查找具有指定公网IP的实例
            response = self.ec2.describe_instances(
                Filters=[
                    {
                        'Name': 'ip-address',
                        'Values': [ip_address]
                    },
                    {
                        'Name': 'instance-state-name',
                        'Values': ['pending', 'running', 'shutting-down', 'terminated', 'stopping', 'stopped']
                    }
                ]
            )
            
            instances = []
            for reservation in response['Reservations']:
                for instance in reservation['Instances']:
                    instances.append(instance)
            
            if not instances:
                return {
                    'provider': 'aws',
                    'found': False,
                    'message': f'未找到使用IP地址 {ip_address} 的EC2实例',
                    'searched_region': self.region
                }
            
            # 获取第一个匹配的实例的详细信息
            instance = instances[0]
            instance_info = self._format_instance_info(instance)
            
            return {
                'provider': 'aws',
                'found': True,
                'instance_info': instance_info
            }
            
        except ClientError as e:
            return {
                'error': f'AWS API调用失败: {str(e)}',
                'provider': 'aws'
            }
        except Exception as e:
            return {
                'error': f'查询EC2实例时发生错误: {str(e)}',
                'provider': 'aws'
            }
  • Core helper method in AWSProvider class to query EC2 instance by instance ID using boto3 describe_instances(InstanceIds). Handles errors and formats response.
    def get_instance_by_id(self, instance_id: str) -> Dict:
        """
        根据实例ID查找EC2实例
        
        Args:
            instance_id (str): EC2实例ID
            
        Returns:
            Dict: 实例信息或错误信息
        """
        if not self.available:
            return {
                'error': f'AWS服务不可用: {getattr(self, "error", "未知错误")}',
                'provider': 'aws'
            }
        
        try:
            response = self.ec2.describe_instances(InstanceIds=[instance_id])
            
            if not response['Reservations']:
                return {
                    'provider': 'aws',
                    'found': False,
                    'message': f'未找到ID为 {instance_id} 的EC2实例'
                }
            
            instance = response['Reservations'][0]['Instances'][0]
            instance_info = self._format_instance_info(instance)
            
            return {
                'provider': 'aws',
                'found': True,
                'instance_info': instance_info
            }
            
        except ClientError as e:
            return {
                'error': f'AWS API调用失败: {str(e)}',
                'provider': 'aws'
            }
        except Exception as e:
            return {
                'error': f'查询EC2实例时发生错误: {str(e)}',
                'provider': 'aws'
            }
  • Private helper method to format raw boto3 EC2 instance data into a structured dictionary with extracted fields like name from tags, IPs, state, etc.
    def _format_instance_info(self, instance: Dict) -> Dict:
        """格式化实例详细信息"""
        # 获取名称标签
        name = '未命名'
        for tag in instance.get('Tags', []):
            if tag['Key'] == 'Name':
                name = tag['Value']
                break
        
        # 格式化网络信息
        public_ip = instance.get('PublicIpAddress')
        private_ip = instance.get('PrivateIpAddress')
        
        # 格式化安全组
        security_groups = [sg['GroupName'] for sg in instance.get('SecurityGroups', [])]
        
        # 格式化标签
        tags = {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])}
        
        return {
            'instance_id': instance.get('InstanceId'),
            'name': name,
            'instance_type': instance.get('InstanceType'),
            'state': instance.get('State', {}).get('Name'),
            'public_ip': public_ip,
            'private_ip': private_ip,
            'availability_zone': instance.get('Placement', {}).get('AvailabilityZone'),
            'launch_time': instance.get('LaunchTime').isoformat() if instance.get('LaunchTime') else None,
            'platform': instance.get('Platform', 'Linux/UNIX'),
            'architecture': instance.get('Architecture'),
            'virtualization_type': instance.get('VirtualizationType'),
            'root_device_type': instance.get('RootDeviceType'),
            'security_groups': security_groups,
            'subnet_id': instance.get('SubnetId'),
            'vpc_id': instance.get('VpcId'),
            'tags': tags,
            'monitoring_state': instance.get('Monitoring', {}).get('State'),
            'ebs_optimized': instance.get('EbsOptimized', False)
        }
  • main.py:12-12 (registration)
    Import of aws_provider module, which provides the underlying methods called by the tool handler.
    from providers.aws_provider import aws_provider

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/rainhan99/cloud_manage_mcp_server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server