cd /news/ai-agents/give-your-ai-agent-an-ip-lookup-tool… · home › topics › ai-agents › article
[ARTICLE · art-174776] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Give Your AI Agent an IP Lookup Tool With Function Calling

A developer built a working IP lookup tool for LLM agents, wiring a single validated Python function into both OpenAI's Responses API and Anthropic's Messages API. The implementation adds strict JSON Schema validation, error results the model can read, a five-minute cache, and a trimmed response that cut output from 576 tokens to 84. The writeup stresses that the tool description, not the code, is what drives when the model decides to call the function.

recommendation

Write detailed tool descriptions covering purpose, parameters and output meaning, validate inputs, and return readable error objects with a retryable flag so the agent can recover.

more in playbook: Designing agent systems
by read16 min views5 publishedNov 23, 2026

LLM function calling guides love a fake tool. OpenAI's function calling guide demos a horoscope function that promises you'll "befriend a baby otter." Anthropic's tool use overview hardcodes "15 degrees Celsius, partly cloudy." Fine for showing the loop. Useless for learning what breaks when the function behind the tool calls a real, metered API.

This post builds an IP lookup tool an agent can call: a strict schema, input validation, error results the model can read, a response cut from 576 tokens to 84, a five-minute cache, and the same function wired into OpenAI's Responses API and Claude's Messages API. Python, about 250 lines across three files.

ipaddress catches private and reserved ranges, but is_global lets multicast through.requests error messages contain the key.parameters and function_call_output; Claude wants input_schema and tool_result. The model doesn't call anything. You send it a list of tools, each with a name, a description, and a JSON Schema for its arguments. When the model decides a tool would help, it stops and returns a structured call instead of text: lookup_ip with {"ip": "8.8.8.8"}. Your code runs the lookup, appends the result to the conversation, and calls the model again. That round trip repeats until the model answers in plain text.

How does it pick the moment? Mostly from the description. Anthropic's docs say Claude "determines when to call a tool based on the user's request and the tool's description," and OpenAI's best practices ask you to explain the function's purpose, each parameter, and what the output represents. The description is the real prompt. The code behind it is plumbing.

Function calling and LLM tool calling are the same mechanism. OpenAI's guide opens with "Function calling (also known as tool calling)"; "tool" is the broader word because models also get built-in tools like web search. I'll use both.

Python 3.10 or later (the code uses str | None hints) and three packages:

pip install openai anthropic requests

Set IPGEO_API_KEY, plus OPENAI_API_KEY or ANTHROPIC_API_KEY for whichever model you call.

Any IP data provider fits behind this function. IPinfo, IPGeolocation, MaxMind GeoIP2, ip-api, and IPLocate all return similar location fields. I'm using ipgeolocation.io because its free plan's 1,000 daily credits cover location, ASN, and time zone in one call, and its fields parameter lets the tool request only the paths it needs; the IP Geolocation API docs list every path. Switching providers later means changing one HTTP call and one mapping function.

Everything in this section and the next three lives in one file, ip_tool.py. The blocks are in file order.

"""lookup_ip: one IP lookup tool, shared by the OpenAI and Claude loops."""
import ipaddress
import logging
import os
import time

import requests

log = logging.getLogger("ip_tool")

DESCRIPTION = (
    "Look up the approximate network location of a public IPv4 or IPv6 address: "
    "country, region, city, coordinates, ASN and network owner, and IANA time zone. "
    "This is where the IP's network is located, not the position of a person or "
    "device, and city-level results can be wrong. Do not call it for private, "
    "loopback, or reserved addresses (10.x, 192.168.x, 127.0.0.1). If the result "
    "has an 'error' field, tell the user what went wrong; retry only when "
    "'retryable' is true."
)

PARAMETERS = {
    "type": "object",
    "properties": {
        "ip": {
            "type": "string",
            "description": "One public IPv4 or IPv6 address, e.g. 8.8.8.8",
        }
    },
    "required": ["ip"],
    "additionalProperties": False,
}

OPENAI_TOOL = {"type": "function", "name": "lookup_ip", "description": DESCRIPTION,
               "parameters": PARAMETERS, "strict": True}
CLAUDE_TOOL = {"name": "lookup_ip", "description": DESCRIPTION,
               "input_schema": PARAMETERS, "strict": True}

strict: True with additionalProperties: False means both providers guarantee the arguments match the schema, so you never parse {"ipaddress": ...} or a missing field. It doesn't guarantee the string is a valid IP. That's the next section's job.

Read the description as a contract with the model. It says what comes back, what that data is not, when not to call, and what to do with an error. Every sentence is there because something goes wrong without it.

The middle sentence carries the most weight. Without it, nothing stops a model from telling someone "you're in Mountain View." For 8.8.8.8 that's especially wrong: it's Google's anycast DNS address, served from many places, and the lookup returns where the network is registered. IP location describes networks. Say so in the tool, not in a disclaimer the model never reads.

The error sentence matters because a model that sees a bare failure may just try again. With a metered API, every retry is a credit.

A common design splits this into separate tools for location, ASN, reputation, and "what's my IP." I'd start with one. Every tool's schema rides along on every request, and every extra tool is another wrong choice the model can make. OpenAI's best practices say the same thing in their own words: keep the initial set of functions small, and combine functions that are always called in sequence.

Split when permissions differ. If only admins should see VPN and threat data, that's a second tool you register for admin sessions and never send otherwise.

def _public_ip(raw: str) -> str | None:
    """Normalize the model's argument; None if it isn't a public address."""
    try:
        ip = ipaddress.ip_address(str(raw).strip())
    except ValueError:
        return None
    if not ip.is_global or ip.is_multicast:
        return None
    return str(ip)

ipaddress handles IPv4 and IPv6, normalizes formatting, and is_global rejects RFC 1918 ranges, loopback, link-local, the CGNAT block 100.64.0.0/10, and the documentation ranges. One surprise from testing: ipaddress.ip_address("224.0.0.1").is_global is True. You can't geolocate a multicast group, so it gets its own check.

The API would reject these anyway (a private address comes back as HTTP 423 with '10.0.0.1' is a bogon IP address.), but catching them locally skips a network round trip and gives the model a clear answer in microseconds.

The full free-plan response for 8.8.8.8, every field included:

{
  "ip": "8.8.8.8",
  "location": {
    "continent_code": "NA",
    "continent_name": "North America",
    "country_code2": "US",
    "country_code3": "USA",
    "country_name": "United States",
    "country_name_official": "United States of America",
    "country_capital": "Washington, D.C.",
    "state_prov": "California",
    "state_code": "US-CA",
    "district": "Santa Clara",
    "city": "Mountain View",
    "zipcode": "94043-1351",
    "latitude": "37.42240",
    "longitude": "-122.08421",
    "is_eu": false,
    "country_flag": "https://ipgeolocation.io/static/flags/us_64.png",
    "geoname_id": "6301403",
    "country_emoji": "\ud83c\uddfa\ud83c\uddf8"
  },
  "country_metadata": {
    "calling_code": "+1",
    "tld": ".us",
    "languages": ["en-US", "es-US", "haw", "fr"]
  },
  "currency": { "code": "USD", "name": "US Dollar", "symbol": "$" },
  "asn": { "as_number": "AS15169", "organization": "Google LLC", "country": "US" },
  "time_zone": {
    "name": "America/Los_Angeles",
    "offset": -8,
    "offset_with_dst": -8,
    "current_time": "2026-11-23 06:07:54.725-0800",
    "current_time_unix": 1795442874.725,
    "current_tz_abbreviation": "PST",
    "current_tz_full_name": "Pacific Standard Time",
    "standard_tz_abbreviation": "PST",
    "standard_tz_full_name": "Pacific Standard Time",
    "is_dst": false,
    "dst_savings": 0,
    "dst_exists": true,
    "dst_tz_abbreviation": "PDT",
    "dst_tz_full_name": "Pacific Daylight Time",
    "dst_start": {
      "utc_time": "2027-03-14 TIME 10:00",
      "duration": "+1.00H",
      "gap": true,
      "date_time_after": "2027-03-14 TIME 03:00",
      "date_time_before": "2027-03-14 TIME 02:00",
      "overlap": false
    },
    "dst_end": {
      "utc_time": "2027-11-07 TIME 09:00",
      "duration": "-1.00H",
      "gap": false,
      "date_time_after": "2027-11-07 TIME 01:00",
      "date_time_before": "2027-11-07 TIME 02:00",
      "overlap": true
    }
  }
}

Paid plans add network, company, and extra asn fields on top. Useful data for a log pipeline. For an agent answering "where is this IP?", most of it is noise: a flag URL, four language codes, a currency symbol, and two DST transition objects. As compact JSON that's 576 tokens (o200k_base tokenizer), and tool results stay in the conversation, so they get re-sent with every later request.

IPGEO_URL = "https://api.ipgeolocation.io/v3/ipgeo"
FIELDS = ",".join([
    "location.country_name", "location.country_code2", "location.state_prov",
    "location.city", "location.latitude", "location.longitude",
    "asn.as_number", "asn.organization", "time_zone.name",
])

def _to_float(value) -> float | None:
    try:
        return float(value)
    except (TypeError, ValueError):
        return None

def _shape(data: dict) -> dict:
    """Map the vendor's response onto our own small, stable schema."""
    loc = data.get("location") or {}
    asn = data.get("asn") or {}
    tz = data.get("time_zone") or {}
    return {
        "ip": data.get("ip"),
        "country": loc.get("country_name"),
        "country_code": loc.get("country_code2"),
        "region": loc.get("state_prov"),
        "city": loc.get("city"),
        "latitude": _to_float(loc.get("latitude")),
        "longitude": _to_float(loc.get("longitude")),
        "asn": asn.get("as_number"),
        "network_owner": asn.get("organization"),
        "time_zone": tz.get("name"),
    }

Two things happen here. fields makes the API send only nine paths (plus ip, which always comes back), so less crosses the wire. _shape then maps the vendor's names onto yours: the model sees region, not state_prov, and if you swap providers next year, the shape the model has been reading doesn't change. What the model gets:

{"ip": "8.8.8.8", "country": "United States", "country_code": "US", "region": "California", "city": "Mountain View", "latitude": 37.4224, "longitude": -122.08421, "asn": "AS15169", "network_owner": "Google LLC", "time_zone": "America/Los_Angeles"}

84 tokens. Same answer, about a seventh of the context.

ipgeolocation.io takes the key as an apiKey query parameter. Plenty of REST APIs do. It interacts badly with the way agents report errors. Here's what requests puts in an exception when that call returns 401:

requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url:
https://api.ipgeolocation.io/v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8&fields=location.city

Connection failures do the same thing: a DNS error prints Max retries exceeded with url: /v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8. Now picture a common agent pattern, return f"Sorry, I encountered an error: {str(e)}", feeding the tool result. Your key is in the model's context, in your conversation logs, and one "what went wrong?" away from the user's screen.

HTTP_ERRORS = {
    401: ("rejected", "The IP data API rejected the key or this plan lacks the data.", False),
    403: ("forbidden", "This server's IP is not allowed to use the API key.", False),
    423: ("not_public", "That address is private or reserved and has no location.", False),
    429: ("out_of_credits", "The IP lookup quota is used up. Try again later.", False),
}

CACHE_TTL = 300  # seconds
_cache: dict[str, tuple[float, dict]] = {}

def tool_error(code: str, message: str, retryable: bool) -> dict:
    return {"error": code, "message": message, "retryable": retryable}

The fix is boring on purpose: map status codes to messages you wrote, add a retryable flag so the model knows whether trying again makes sense, and log exception types, never exception strings. Anthropic's guide to handling tool calls recommends error messages that say what went wrong and what to try next. These do, without echoing anything from upstream.

The backstop is outside the code. Lock the key to your servers' IPs: IP whitelisting is available on every plan, including free, and a request with that key from anywhere else gets a 403. A leaked key that only works from your NAT gateway is a much smaller problem.

The function the model actually calls is the longest block in the post, because every decision above meets in it.

def lookup_ip(ip: str) -> dict:
    """Run the tool. Always returns a dict; never raises into the agent loop."""
    clean = _public_ip(ip)
    if clean is None:
        return tool_error("not_public", f"{str(ip)[:45]!r} is not a public IP address.", False)

    hit = _cache.get(clean)
    if hit and time.monotonic() - hit[0] < CACHE_TTL:
        return hit[1]

    api_key = os.environ.get("IPGEO_API_KEY")
    if not api_key:
        return tool_error("not_configured", "The IP lookup tool has no API key.", False)

    try:
        resp = requests.get(
            IPGEO_URL,
            params={"apiKey": api_key, "ip": clean, "fields": FIELDS},
            timeout=(1.0, 3.0),  # connect, read
        )
    except requests.Timeout:
        log.warning("ipgeo timeout for %s", clean)
        return tool_error("timeout", "The IP lookup timed out.", True)
    except requests.RequestException as exc:
        log.warning("ipgeo request failed: %s", type(exc).__name__)
        return tool_error("network", "The IP lookup service could not be reached.", True)

    if resp.status_code != 200:
        code, message, retryable = HTTP_ERRORS.get(
            resp.status_code,
            ("upstream", f"The IP lookup failed with HTTP {resp.status_code}.",
             resp.status_code >= 500),
        )
        return tool_error(code, message, retryable)

    try:
        data = resp.json()
        if not isinstance(data, dict):
            raise ValueError("Unexpected response shape")

        if any(
            key in data and not isinstance(data[key], (dict, type(None)))
            for key in ("location", "asn", "time_zone")
        ):
            raise ValueError("Unexpected nested response shape")

        result = _shape(data)
    except (ValueError, TypeError, AttributeError):
        return tool_error(
            "upstream",
            "The IP lookup returned an unreadable response.",
            True,
        )

    if len(_cache) > 1000:  # crude bound; use Redis if you run several workers
        _cache.clear()
    _cache[clean] = (time.monotonic(), result)
    return result

The contract is in the docstring: it always returns a dict and never raises. An exception that escapes a tool kills the whole agent turn, and the user gets a stack trace instead of "that address is private." That makes the tool fail-open for the conversation: if the IP API is down, the agent says it couldn't look the address up and carries on, instead of the whole request failing.

import json
import os

import openai
from openai import OpenAI

from ip_tool import OPENAI_TOOL, lookup_ip, tool_error

MAX_ROUNDS = 4  # each round can cost a credit; a confused model can loop

def run_tool(name: str, raw_args: str) -> dict:
    if name != "lookup_ip":
        return tool_error("unknown_tool", f"No tool named {name}.", False)
    try:
        args = json.loads(raw_args or "{}")
    except json.JSONDecodeError:
        return tool_error("bad_arguments", "Arguments were not valid JSON.", False)
    return lookup_ip(args.get("ip", ""))

def ask(question: str) -> str:
    client = OpenAI(timeout=30.0)  # reads OPENAI_API_KEY; default read timeout is 600s
    model = os.environ.get("OPENAI_MODEL", "gpt-6.2-astra")  # names change; check the docs
    items: list = [{"role": "user", "content": question}]

    for _ in range(MAX_ROUNDS):
        try:
            response = client.responses.create(model=model, tools=[OPENAI_TOOL], input=items)
        except openai.APIError as exc:
            return f"Model request failed: {type(exc).__name__}"

        calls = [item for item in response.output if item.type == "function_call"]
        if not calls:
            return response.output_text

        items += response.output
        for call in calls:
            items.append({
                "type": "function_call_output",
                "call_id": call.call_id,
                "output": json.dumps(run_tool(call.name, call.arguments)),
            })

    return "Stopped after too many tool calls for one question."

if __name__ == "__main__":
    print(ask("Where is 8.8.8.8, and what time zone is it in?"))

items += response.output mirrors the OpenAI function calling example in the docs and keeps any reasoning items in the history next to the calls they produced. Every function_call gets a function_call_output with the matching call_id. "Compare 8.8.8.8 and 1.1.1.1" can produce two calls in one turn, so the loop handles all of them, not just the first. Even with strict mode on, run_tool still guards against unknown tool names and bad JSON; it costs four lines.

MAX_ROUNDS is cheap insurance. A model stuck retrying a failing lookup spends a credit every round, and four rounds is plenty for any sane question about IPs.

Claude's tool use differs in three places: the schema key is input_schema, results go back as tool_result blocks inside a user turn, and errors carry is_error: true.

import json
import os

import anthropic

from ip_tool import CLAUDE_TOOL, lookup_ip, tool_error

MAX_ROUNDS = 4

def ask(question: str) -> str:
    client = anthropic.Anthropic(timeout=30.0)  # reads ANTHROPIC_API_KEY
    model = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
    messages: list = [{"role": "user", "content": question}]

    for _ in range(MAX_ROUNDS):
        try:
            response = client.messages.create(
                model=model, max_tokens=1024, tools=[CLAUDE_TOOL], messages=messages
            )
        except anthropic.APIError as exc:
            return f"Model request failed: {type(exc).__name__}"

        if response.stop_reason != "tool_use":
            return "".join(b.text for b in response.content if b.type == "text")

        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            if block.name == "lookup_ip":
                result = lookup_ip((block.input or {}).get("ip", ""))
            else:
                result = tool_error("unknown_tool", f"No tool named {block.name}.", False)
            results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(result),
                "is_error": "error" in result,  # lets Claude explain instead of guess
            })
        messages.append({"role": "user", "content": results})

    return "Stopped after too many tool calls for one question."

if __name__ == "__main__":
    print(ask("Where is 8.8.8.8, and what time zone is it in?"))

ip_tool.py didn't change at all. That's the payoff of keeping the tool provider-neutral: the adapters are envelopes, and the logic you tested lives in one place. Anthropic's docs note that Claude may call the tool again after an error, so the round cap earns its keep here too.

Agents re-ask. A follow-up about the same address can trigger a second identical call, and a parallel turn can request the same IP twice. The dict cache inside lookup_ip keys on the normalized address, so " 8.8.8.8 " and 8.8.8.8 share an entry, and a hit costs nothing. Five minutes matches the default the official ipgeolocation.io MCP server uses for lookup results. It's per process, though. Once you run more than one worker, move it to Redis with the same TTL.

ASN organization names, hostnames, and WHOIS records are written by whoever registered the network. Nearly all of them are boring (Google LLC). They don't have to be, and you don't control them.

Keep tool output inside the tool result, never in the system prompt, and don't chain it straight into another tool call without a check. Anthropic's tool-handling guide says it plainly: "Keep untrusted content inside tool_result blocks rather than system prompts or plain user text blocks." This is one more reason _shape returns ten named fields instead of the raw response. The model sees keys you chose, not whatever the upstream decided to send this week.

IPinfo, IP2Location, ipstack, and IPGeolocation all ship MCP servers now; the official ipgeolocation.io server documents 16 tools covering geolocation, security, ASN, time zones, abuse contacts, and more. If your agent lives in Claude Desktop, Cursor, VS Code, Cline, or Codex CLI, install it and skip everything above:

{
  "mcpServers": {
    "ipgeolocation": {
      "command": "npx",
      "args": ["-y", "ipgeolocation-io-mcp@latest"],
      "env": { "IPGEOLOCATION_API_KEY": "<YOUR_API_KEY>" }
    }
  }
}

You get security, ASN, abuse contact, time zone, and bulk tools without writing them, and the server already caches results and returns error guidance. Keep the real key in your client's private config, not a committed file.

From your own code calling a model API, check the connector's authentication support. OpenAI's Responses API supports a headers field in its MCP tool configuration, so it can send the X-IPGeolocation-API-Key header required by https://mcp.ipgeolocation.io/mcp. Claude's MCP connector currently documents bearer authentication through authorization_token, without a custom-header option. Connecting that connector to this hosted server therefore requires an authentication bridge or an MCP client you control. For one narrow lookup, a function still gives you direct control over validation, caching, and the response shape.

My rule: one narrow tool in your own agent, write the function. Five tools, or the same tools in several clients, use the server.

Paid plans can add include=security to the request for VPN, proxy, Tor, and threat-score fields, at 2 extra credits per lookup. A free key that names the module gets HTTP 401, which HTTP_ERRORS already turns into a readable error. If you add it, make it a separate tool and register it only for sessions allowed to see that data.

IPv6 needs no changes. 2001:4860:4860::8888 goes through the same validation, request, and shape.

Enriching 10,000 log lines isn't an agent job. Use the bulk endpoint from a script and keep tool calls for questions a person actually asked.

Log the tool name, the normalized IP, the error code, and the latency. Not the URL.

Before you ship, give each conversation a lookup budget on top of MAX_ROUNDS, and watch which error codes show up in the first week of logs. A pile of not_public errors often means users are pasting their router's address, which is a prompt problem, not an API one.

── more in #ai-agents 4 stories · sorted by recency
── more on @openai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/give-your-ai-agent-a…] indexed:0 read:16min 2026-11-23 · —