Skip to main content
Glama
ip2location

IP2Location IP Geolocation MCP Server

Official

get_geolocation

Retrieve detailed geolocation data for any IPv4 or IPv6 address, including country, city, coordinates, ISP, and security information. Accepts multiple IPs in a single query for efficient batch lookups.

Instructions

Fetch geolocation for the given IP address(es).

CRITICAL INSTRUCTION FOR AI AGENT: If the user provides multiple IP addresses in their prompt, DO NOT call this tool multiple times sequentially. You MUST batch all IP addresses together into a single comma-separated string and make exactly ONE tool call.

It helps users to retrieve detailed information such as country, region, city, latitude, longitude, ZIP code, time zone, ASN, and proxy information for any IPv4 or IPv6 address.

Args: ip: The IP address to analyze (IPv4 or IPv6). For multiple IPs, you MUST combine them into a single string separated by commas (e.g., "1.1.1.1, 2.2.2.2").

Returns: A JSON string result includes:

Location & Geography:
Country, region, district, city, ZIP code, latitude & longitude, time zone.

Network & Connectivity
ASN (Autonomous System Number), ISP (Internet Service Provider), domain, net speed, IDD code, area code, address type, usage type.

Mobile Information
MNC (Mobile Network Code), MCC (Mobile Country Code), Mobile Brand.

Currency & Language
currency code, currency name, currency symbol, language code, language name.

Proxy & Security
proxy type, last seen, threat level/type, proxy provider, fraud score.

Others
IAB category, weather, elevation, population and more.

Note that some information may only available in paid plan. Learn more on this in https://www.ip2location.io/pricing.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ipYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function for the 'get_geolocation' tool. Fetches geolocation data for IP address(es) via IP2Location.io API. Supports single IP via standard API and multiple IPs via bulk API with fallback to individual requests.
    async def get_geolocation(ip: str) -> Dict[str, Any] | str:
        """
        Fetch geolocation for the given IP address(es).
        
        CRITICAL INSTRUCTION FOR AI AGENT: If the user provides multiple IP addresses in their prompt, 
        DO NOT call this tool multiple times sequentially. You MUST batch all IP addresses together 
        into a single comma-separated string and make exactly ONE tool call.
    
        It helps users to retrieve detailed information such as country, region, city, latitude, longitude, ZIP code, time zone, ASN, and proxy information for any IPv4 or IPv6 address.
    
        Args:
            ip: The IP address to analyze (IPv4 or IPv6). For multiple IPs, you MUST combine them into a single string separated by commas (e.g., "1.1.1.1, 2.2.2.2").
    
        Returns:
            A JSON string result includes:
            
            Location & Geography:
            Country, region, district, city, ZIP code, latitude & longitude, time zone.
            
            Network & Connectivity
            ASN (Autonomous System Number), ISP (Internet Service Provider), domain, net speed, IDD code, area code, address type, usage type.
            
            Mobile Information
            MNC (Mobile Network Code), MCC (Mobile Country Code), Mobile Brand.
            
            Currency & Language
            currency code, currency name, currency symbol, language code, language name.
            
            Proxy & Security
            proxy type, last seen, threat level/type, proxy provider, fraud score.
            
            Others
            IAB category, weather, elevation, population and more.
            
            Note that some information may only available in paid plan. Learn more on this in https://www.ip2location.io/pricing.
        """
        # Extract IPs from input (supports comma, space, or newline separation)
        ip_list = [i.strip() for i in re.split(r'[,\s]+', ip) if i.strip()]
        
        if not ip_list:
            return "No valid IP addresses provided."
        
        api_key = get_api_key()
        
        # Standard Flow for a Single IP Request
        if len(ip_list) == 1:
            single_ip = ip_list[0]
            params = {"ip": single_ip}
            if api_key:
                params["key"] = api_key
            else:
                return(f"An API key is needed to use the bulk API.")
    
            geolocation_result = await make_request(IPLIO_API_BASE, params)
    
            if not geolocation_result:
                return f"Unable to fetch geolocation for IP {single_ip}."
    
            return geolocation_result
    
        # Enhanced Flow for Multiple IP Addresses
        # 1. Try the bulk endpoint first
        bulk_result = await make_bulk_request(IPLIO_BULK_API_BASE, ip_list, api_key)
        
        if bulk_result:
            return bulk_result
        
        # 2. Fallback: If bulk fails, query one by one
        fallback_results = {}
        for single_ip in ip_list:
            params = {"ip": single_ip}
            if api_key:
                params["key"] = api_key
                
            res = await make_request(IPLIO_API_BASE, params)
            if res:
                fallback_results[single_ip] = res
            else:
                fallback_results[single_ip] = {"error": f"Unable to fetch geolocation for IP {single_ip}."}
                
        return fallback_results
    
        geolocation_result = await make_request(IPLIO_API_BASE, params)
    
        if not geolocation_result:
            return f"Unable to fetch geolocation for IP {ip}."
    
        return geolocation_result
  • src/server.py:53-53 (registration)
    Registration decorator @mcp.tool() that registers the get_geolocation function as an MCP tool.
    @mcp.tool()
  • Helper function that makes HTTP requests to the IP2Location.io API. Used by get_geolocation to fetch single IP geolocation data.
    async def make_request(url: str, params: dict[str, str]) -> dict[str, Any] | None:
        """Make a request to the IP2Location.io API with proper error handling."""
        headers = {
            "User-Agent": USER_AGENT,
            "Accept": "application/json"
        }
        async with httpx.AsyncClient() as client:
            try:
                response = await client.get(url, headers=headers, params=params, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except Exception:
                return None
  • Helper function for bulk IP geolocation requests. Sends a POST request to the bulk API endpoint with a list of IPs.
    async def make_bulk_request(url: str, ips: list[str], api_key: str | None) -> dict[str, Any] | None:
        """Make a POST request to the IP2Location.io Bulk API endpoint."""
        params = {"format": "json"}
        if api_key:
            params["key"] = api_key
        
        # Rectified: Dump list to string to match the `data = '["1.1.1.1", ...]'` requirement
        payload_data = json.dumps(ips)
            
        async with httpx.AsyncClient() as client:
            try:
                # We use `content=payload_data` in httpx to send the raw string exactly 
                # like `data=data` does in the requests library.
                response = await client.post(url, params=params, content=payload_data, timeout=30.0)
                response.raise_for_status()
                return response.json()
            except Exception:
                return None
  • Helper function that retrieves the API key from environment variable IP2LOCATION_API_KEY.
    def get_api_key() -> str | None:
        """Retrieve the API key from MCP server config."""
        return os.getenv("IP2LOCATION_API_KEY")
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Describes the return structure in detail and notes that some information may be limited to paid plans. No annotations exist, so the description carries the burden; it discloses the tool is a read operation but lacks info on error handling or rate limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with headings, critical instruction upfront, and detailed return breakdown. Slightly verbose but each section adds clear value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given one required parameter, no annotations, and presence of an output schema, the description provides extensive return field details and notes on plan limitations, making it complete for effective use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema provides no description for the 'ip' parameter (0% coverage), but the description compensates fully by explaining it accepts IPv4/IPv6 and can be comma-separated for multiple IPs.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Clearly states the tool fetches geolocation for IP addresses, specifying the range of detailed data returned. No sibling tools exist, but it distinguishes itself as a geolocation lookup tool.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Provides explicit critical instruction to batch multiple IPs into a single comma-separated string to avoid multiple calls. Does not mention when not to use or alternatives, but this is adequate given the single-purpose tool.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/ip2location/mcp-ip2location-io'

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