Originally published on dev.to with Python examples. This version is rewritten for .NET.
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, in C# on .NET 8: a strict schema, input validation, error results the model can read, a response cut from 475 tokens to 66, a five-minute cache, and the same class wired into OpenAI's Responses API and Claude's Messages API through their official .NET SDKs. About 400 lines across four files.
TL;DR
The model never calls your API. It returns a tool name and JSON arguments; your code runs the call and sends the result back.
Validate the IP before calling the API. IPAddress.TryParse accepts "8.8" and "134744072", so insist on the canonical form and check a bogon list with IPNetwork.
Never hand exception text to the model, and watch your logs: on Microsoft.Extensions.Http 8.x, IHttpClientFactory logs the full request URL, query-string API key included.
Trim the response. The full default response for 8.8.8.8 is 475 tokens; the fields an agent needs fit in 66.
Write one provider-neutral class and two thin adapters. OpenAI wants a ResponseTool and CreateFunctionCallOutputItem; Claude wants a Tool with an InputSchema and a ToolResultBlockParam.
If your agent runs inside an MCP client like Claude Desktop or Cursor, install an MCP server instead. From your own code calling a model API, one class is usually less work.
Treat the tool like an API handed to someone who repeats everything they read. Return small, stable JSON. Turn every failure into a fixed message. Keep secrets and raw upstream text out of anything the model sees, because whatever the model sees, the user can eventually see too.
How LLM function calling works
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.
Setup
You need .NET 8 or later, because the validation uses System.Net.IPNetwork, which arrived in .NET 8.
dotnet new console -n IpAgent -f net8.0
cd IpAgent
dotnet add package OpenAI --version 2.15.0
dotnet add package Anthropic --version 13.13.0
dotnet add package Microsoft.Extensions.Logging.Abstractions --version 10.0.10
Both model SDKs are the official ones; since version 10, the Anthropic package on NuGet is Anthropic's own SDK. Set IPGEO_API_KEY, plus OPENAI_API_KEY or ANTHROPIC_API_KEY for whichever model you call.
The examples call the ipgeolocation.io IP Geolocation API. IPinfo, MaxMind GeoIP2, ip-api, and IPLocate return similar location fields, so any of them fits behind this class; switching providers means changing one HTTP call and one mapping method. The code uses plain HttpClient so every decision about the URL, timeouts, and errors stays visible.
Write the schema the model reads
The next four code blocks are one file, IpLookupTool.cs, in file order.
using System.Collections.Concurrent;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace IpAgent;
/// <summary>What the agent loop sends back to the model.</summary>
public sealed record ToolResult(string Json, bool IsError);
/// <summary>lookup_ip: one IP lookup tool, shared by the OpenAI and Claude loops.</summary>
public sealed class IpLookupTool
{
public const string Name = "lookup_ip";
public const string 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.";
// One JSON Schema; each agent wraps it in its provider's envelope.
public const string ParametersJson = """
{
"type": "object",
"properties": {
"ip": { "type": "string", "description": "One public IPv4 or IPv6 address, e.g. 8.8.8.8" }
},
"required": ["ip"],
"additionalProperties": false
}
""";
ParametersJson is the single schema both providers receive. "additionalProperties": false plus strict mode (set in each agent below) means the arguments always match it, so you never parse {"ipaddress": ...} or a missing field. Strict mode doesn't guarantee the string is a valid IP. That's the next section's job.
The description is the prompt
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.
One tool, not four
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.
Validate before the network call
// Private, loopback, link-local, CGNAT, documentation, benchmarking,
// multicast, and reserved ranges. None of them has a public location.
private static readonly IPNetwork[] NonPublicRanges =
[
IPNetwork.Parse("0.0.0.0/8"), IPNetwork.Parse("10.0.0.0/8"),
IPNetwork.Parse("100.64.0.0/10"), IPNetwork.Parse("127.0.0.0/8"),
IPNetwork.Parse("169.254.0.0/16"), IPNetwork.Parse("172.16.0.0/12"),
IPNetwork.Parse("192.0.0.0/24"), IPNetwork.Parse("192.0.2.0/24"),
IPNetwork.Parse("192.168.0.0/16"), IPNetwork.Parse("198.18.0.0/15"),
IPNetwork.Parse("198.51.100.0/24"), IPNetwork.Parse("203.0.113.0/24"),
IPNetwork.Parse("224.0.0.0/4"), IPNetwork.Parse("240.0.0.0/4"),
IPNetwork.Parse("::/96"), IPNetwork.Parse("100::/64"),
IPNetwork.Parse("2001:10::/28"), IPNetwork.Parse("2001:db8::/32"),
IPNetwork.Parse("fc00::/7"), IPNetwork.Parse("fe80::/10"),
IPNetwork.Parse("fec0::/10"), IPNetwork.Parse("ff00::/8"),
];
public static string? PublicIp(string? raw)
{
string input = (raw ?? "").Trim();
if (!IPAddress.TryParse(input, out IPAddress? ip))
return null;
// TryParse also accepts "8.8" (8.0.0.8), "134744072" and "0x08080808" (8.8.8.8).
// Insist on the canonical dotted form so the model can't sneak in surprises.
if (ip.AddressFamily == AddressFamily.InterNetwork && ip.ToString() != input)
return null;
if (ip.IsIPv4MappedToIPv6)
ip = ip.MapToIPv4();
foreach (IPNetwork range in NonPublicRanges)
{
if (range.Contains(ip))
return null;
}
return ip.ToString();
}
.NET has no single "is this a public address" property, so the class carries the reserved ranges itself and checks them with IPNetwork.Contains. The list covers RFC 1918 private space, loopback, link-local, the CGNAT block 100.64.0.0/10, the documentation ranges, benchmarking, multicast, and the reserved space above 240.0.0.0, plus their IPv6 counterparts.
The surprise is IPAddress.TryParse. It happily accepts "8.8" (parsed as 8.0.0.8), and both "134744072" and "0x08080808" come back as 8.8.8.8, because it still supports legacy shorthand forms. Comparing the input with ip.ToString() rejects anything that isn't the canonical dotted form. IPv4-mapped IPv6 addresses such as ::ffff:10.0.0.1 get mapped back to IPv4 before the range check, so they can't slip past it.
The API would reject private addresses anyway (one 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.
Call the API and trim what comes back
The default response for 8.8.8.8 is much bigger than what the model needs: a location object with 18 fields (including a flag image URL and an emoji), country metadata with four language codes, a currency object, the ASN, and a time zone object that carries the next two daylight-saving transitions. Useful data for a log pipeline. For an agent answering "where is this IP?", most of it is noise. Minified, that's 475 tokens (o200k_base tokenizer), and tool results stay in the conversation, so they get re-sent with every later request.
private const string IpgeoUrl = "https://api.ipgeolocation.io/v3/ipgeo";
// Ask the API for these paths only; the server trims the rest.
private const string Fields =
"location.country_name,location.country_code2,location.state_prov," +
"location.city,location.latitude,location.longitude," +
"asn.as_number,asn.organization,time_zone.name";
// Relaxed escaping keeps "Zürich" readable for the model instead of "Z\u00FCrich".
private static readonly JsonSerializerOptions JsonOptions =
new() { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
private static string? Str(JsonElement obj, string name) =>
obj.ValueKind == JsonValueKind.Object
&& obj.TryGetProperty(name, out JsonElement value)
&& value.ValueKind == JsonValueKind.String
? value.GetString()
: null;
// Coordinates arrive as strings ("37.42240"). Parse with the invariant
// culture, or a server running in de-DE turns them into garbage.
private static double? Coordinate(JsonElement obj, string name) =>
double.TryParse(Str(obj, name), NumberStyles.Float, CultureInfo.InvariantCulture, out double v)
? v
: null;
/// <summary>Map the vendor's response onto our own small, stable schema.</summary>
private static string Shape(JsonElement root)
{
root.TryGetProperty("location", out JsonElement loc);
root.TryGetProperty("asn", out JsonElement asn);
root.TryGetProperty("time_zone", out JsonElement tz);
var result = new
{
ip = Str(root, "ip"),
country = Str(loc, "country_name"),
country_code = Str(loc, "country_code2"),
region = Str(loc, "state_prov"),
city = Str(loc, "city"),
latitude = Coordinate(loc, "latitude"),
longitude = Coordinate(loc, "longitude"),
asn = Str(asn, "as_number"),
network_owner = Str(asn, "organization"),
time_zone = Str(tz, "name"),
};
return JsonSerializer.Serialize(result, JsonOptions);
}
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. Two .NET details matter here. Coordinates arrive as strings, and double.TryParse without CultureInfo.InvariantCulture misreads "37.42240" on a server running a culture that uses a decimal comma, such as de-DE. And System.Text.Json escapes non-ASCII by default, so UnsafeRelaxedJsonEscaping keeps city and region names readable for the model; the "unsafe" part is about embedding JSON in HTML, which this output never touches. 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"}
66 tokens. Same answer, about a seventh of the context.
Where your API key leaks in .NET
This API takes the key as an apiKey query parameter, as plenty of REST APIs do. In Python's requests, that's dangerous because the exception message for a 401 includes the full URL, key and all.
.NET is kinder at the exception level. I checked EnsureSuccessStatusCode() on a 401, a DNS failure, and a timeout: none of the exception messages contains the URL. The leak in .NET is in the logs. Register the client with AddHttpClient on Microsoft.Extensions.Http 8.0.1, the latest 8.x release, and the default IHttpClientFactory logging writes the full request URI at Information level, twice per request:
info: System.Net.Http.HttpClient.ipgeo.LogicalHandler[100] Start processing HTTP request GET https://api.ipgeolocation.io/v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8
info: System.Net.Http.HttpClient.ipgeo.ClientHandler[100] Sending HTTP request GET https://api.ipgeolocation.io/v3/ipgeo?apiKey=SECRET123&ip=8.8.8.8
Version 9.0.0 and later redact the query string and log ipgeo?* instead. If you're on .NET 8 and use AddHttpClient, check your logs, or move to a newer Microsoft.Extensions.Http package. The class in this post uses its own HttpClient, so the factory's logging never sees the URL.
Even with clean exception messages, never forward ex.Message to the model. Other HTTP wrappers and your own logging make no such promise, and the model doesn't need it anyway:
public static ToolResult Error(string code, string message, bool retryable) =>
new(JsonSerializer.Serialize(new { error = code, message, retryable }, JsonOptions), IsError: true);
// Fixed messages only. Never forward exception text or anything that could
// contain the request URL, because this URL carries apiKey.
private static ToolResult ErrorFor(HttpStatusCode status) => status switch
{
HttpStatusCode.Unauthorized =>
Error("rejected", "The IP data API rejected the key or this plan lacks the data.", false),
HttpStatusCode.Forbidden =>
Error("forbidden", "This server's IP is not allowed to use the API key.", false),
HttpStatusCode.Locked =>
Error("not_public", "That address is private or reserved and has no location.", false),
HttpStatusCode.TooManyRequests =>
Error("out_of_credits", "The IP lookup quota is used up. Try again later.", false),
_ => Error("upstream", $"The IP lookup failed with HTTP {(int)status}.", (int)status >= 500),
};
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. If your provider can restrict a key to your servers' IP addresses, turn it on: a leaked key that only works from your NAT gateway is a much smaller problem.
The method the model actually calls is the longest block in the post, because every decision above meets in it.
// One shared HttpClient for the process. Creating one per call exhausts sockets.
private static readonly HttpClient SharedHttp = new(new SocketsHttpHandler
{
ConnectTimeout = TimeSpan.FromSeconds(1),
PooledConnectionLifetime = TimeSpan.FromMinutes(5), // pick up DNS changes
})
{
Timeout = TimeSpan.FromSeconds(4),
};
private static readonly TimeSpan CacheTtl = TimeSpan.FromMinutes(5);
private readonly ConcurrentDictionary<string, (DateTimeOffset Expires, ToolResult Result)> _cache = new();
private readonly HttpClient _http;
private readonly ILogger _log;
public IpLookupTool(HttpClient? http = null, ILogger<IpLookupTool>? logger = null)
{
_http = http ?? SharedHttp;
_log = logger ?? NullLogger<IpLookupTool>.Instance;
}
/// <summary>Run the tool. Always returns a result; never throws into the agent loop.</summary>
public async Task<ToolResult> LookupAsync(string? ip, CancellationToken ct = default)
{
string? clean = PublicIp(ip);
if (clean is null)
{
// Echo at most 45 chars (the longest IPv6 text form) back to the model.
string echo = (ip ?? "").Length > 45 ? ip![..45] : ip ?? "";
return Error("not_public", $"'{echo}' is not a public IP address.", false);
}
if (_cache.TryGetValue(clean, out var hit) && hit.Expires > DateTimeOffset.UtcNow)
return hit.Result;
string? apiKey = Environment.GetEnvironmentVariable("IPGEO_API_KEY");
if (string.IsNullOrEmpty(apiKey))
return Error("not_configured", "The IP lookup tool has no API key.", false);
string url = $"{IpgeoUrl}?apiKey={Uri.EscapeDataString(apiKey)}" +
$"&ip={Uri.EscapeDataString(clean)}&fields={Uri.EscapeDataString(Fields)}";
try
{
using HttpResponseMessage resp = await _http.GetAsync(url, ct);
if (resp.StatusCode != HttpStatusCode.OK)
return ErrorFor(resp.StatusCode);
using JsonDocument doc = JsonDocument.Parse(await resp.Content.ReadAsStringAsync(ct));
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
return Error("upstream", "The IP lookup returned an unreadable response.", true);
foreach (string key in new[] { "location", "asn", "time_zone" })
{
if (root.TryGetProperty(key, out JsonElement v)
&& v.ValueKind is not (JsonValueKind.Object or JsonValueKind.Null))
return Error("upstream", "The IP lookup returned an unreadable response.", true);
}
var result = new ToolResult(Shape(root), IsError: false);
if (_cache.Count > 1000) // crude bound; use a distributed cache across instances
_cache.Clear();
_cache[clean] = (DateTimeOffset.UtcNow + CacheTtl, result);
return result;
}
catch (TaskCanceledException) when (!ct.IsCancellationRequested)
{
_log.LogWarning("ipgeo timeout for {Ip}", clean);
return Error("timeout", "The IP lookup timed out.", true);
}
catch (HttpRequestException ex)
{
// Log the type and socket error only. Keep URLs out of logs and tool results.
_log.LogWarning("ipgeo request failed: {Type} {Error}", ex.GetType().Name, ex.HttpRequestError);
return Error("network", "The IP lookup service could not be reached.", true);
}
catch (JsonException)
{
return Error("upstream", "The IP lookup returned an unreadable response.", true);
}
}
}
The contract is in the doc comment: it always returns a result and never throws. 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.
A few HttpClient habits are baked in. One shared instance, because creating one per call exhausts sockets under load. A one-second ConnectTimeout and a four-second overall Timeout, so a slow IP API can't stall the model's turn. PooledConnectionLifetime so long-running services pick up DNS changes. And catch (TaskCanceledException) when (!ct.IsCancellationRequested) separates a timeout from a caller cancelling the request.
Wire it into OpenAI's Responses API
using System.ClientModel;
using System.Text.Json;
using OpenAI.Responses;
#pragma warning disable OPENAI001 // the SDK flags Responses API types "for evaluation purposes only"
namespace IpAgent;
public static class OpenAiAgent
{
private const int MaxRounds = 4; // each round can cost a credit; a confused model can loop
private static readonly ResponseTool Tool = ResponseTool.CreateFunctionTool(
IpLookupTool.Name,
BinaryData.FromString(IpLookupTool.ParametersJson),
strictModeEnabled: true,
functionDescription: IpLookupTool.Description);
// An explicit 30-second limit instead of relying on the SDK default.
public static ResponsesClient CreateClient() => new(
new ApiKeyCredential(Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? ""),
new ResponsesClientOptions { NetworkTimeout = TimeSpan.FromSeconds(30) });
public static async Task<string> AskAsync(
string question, IpLookupTool ipTool, ResponsesClient? client = null, CancellationToken ct = default)
{
client ??= CreateClient();
string model = Environment.GetEnvironmentVariable("OPENAI_MODEL") ?? "gpt-6.2-astra"; // names change
var options = new CreateResponseOptions(model, [ResponseItem.CreateUserMessageItem(question)]);
options.Tools.Add(Tool);
for (int round = 0; round < MaxRounds; round++)
{
ResponseResult response;
try
{
response = await client.CreateResponseAsync(options, ct);
}
catch (Exception ex)
when (ex is ClientResultException or HttpRequestException or TaskCanceledException)
{
return $"Model request failed: {ex.GetType().Name}";
}
var calls = response.OutputItems.OfType<FunctionCallResponseItem>().ToList();
if (calls.Count == 0)
return response.GetOutputText();
// Send back everything the model produced (reasoning items included),
// then one function call output per call. The model may call in parallel.
foreach (ResponseItem item in response.OutputItems)
options.InputItems.Add(item);
foreach (FunctionCallResponseItem call in calls)
{
ToolResult result = await RunToolAsync(call, ipTool, ct);
options.InputItems.Add(ResponseItem.CreateFunctionCallOutputItem(call.CallId, result.Json));
}
}
return "Stopped after too many tool calls for one question.";
}
private static async Task<ToolResult> RunToolAsync(
FunctionCallResponseItem call, IpLookupTool ipTool, CancellationToken ct)
{
if (call.FunctionName != IpLookupTool.Name)
return IpLookupTool.Error("unknown_tool", $"No tool named {call.FunctionName}.", false);
try
{
using JsonDocument args = JsonDocument.Parse(call.FunctionArguments);
string? ip = args.RootElement.TryGetProperty("ip", out JsonElement v)
&& v.ValueKind == JsonValueKind.String ? v.GetString() : null;
return await ipTool.LookupAsync(ip, ct);
}
catch (JsonException)
{
return IpLookupTool.Error("bad_arguments", "Arguments were not valid JSON.", false);
}
}
}
The flow mirrors the C# function calling example in OpenAI's docs: add everything the model produced to options.InputItems (reasoning items included), then one CreateFunctionCallOutputItem per call with the matching CallId. "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. The #pragma is required: the SDK flags the Responses API types "for evaluation purposes only" with diagnostic OPENAI001, and the build stops until you suppress it.
MaxRounds 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. NetworkTimeout sets an explicit 30-second limit instead of relying on the SDK default.
The same tool on Claude
Claude's tool use differs in three places: the schema goes into an InputSchema, results go back as ToolResultBlockParam blocks inside a user turn, and errors set IsError.
using System.Text.Json;
using Anthropic;
using Anthropic.Exceptions;
using Anthropic.Models.Messages;
namespace IpAgent;
public static class ClaudeAgent
{
private const int MaxRounds = 4;
private static readonly ToolUnion Tool = new(new Tool
{
Name = IpLookupTool.Name,
Description = IpLookupTool.Description,
Strict = true,
InputSchema = new InputSchema(
JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(IpLookupTool.ParametersJson)!),
});
// Reads ANTHROPIC_API_KEY. The SDK's default timeout is 10 minutes.
public static AnthropicClient CreateClient() => new() { Timeout = TimeSpan.FromSeconds(30) };
public static async Task<string> AskAsync(
string question, IpLookupTool ipTool, AnthropicClient? client = null, CancellationToken ct = default)
{
client ??= CreateClient();
string model = Environment.GetEnvironmentVariable("ANTHROPIC_MODEL") ?? "claude-sonnet-5-5";
List<MessageParam> messages = [new UserMessageParam { Content = question }];
for (int round = 0; round < MaxRounds; round++)
{
Message response;
try
{
response = await client.Messages.Create(new MessageCreateParams
{
Model = model,
MaxTokens = 1024,
Tools = [Tool],
Messages = messages,
}, ct);
}
catch (AnthropicException ex)
{
return $"Model request failed: {ex.GetType().Name}";
}
if (response.StopReason != StopReason.ToolUse)
return string.Concat(response.Content.Select(b => b.TryPickText(out var t) ? t.Text : ""));
// The assistant turn goes back unchanged; results follow in one user turn.
messages.Add(new AssistantMessageParam
{
Content = response.Content.Select(b => new ContentBlockParam(b.Json)).ToList(),
});
List<ContentBlockParam> results = [];
foreach (ContentBlock block in response.Content)
{
if (!block.TryPickToolUse(out var toolUse))
continue;
ToolResult result = toolUse.Name == IpLookupTool.Name
? await ipTool.LookupAsync(
toolUse.Input.TryGetValue("ip", out JsonElement v)
&& v.ValueKind == JsonValueKind.String ? v.GetString() : null, ct)
: IpLookupTool.Error("unknown_tool", $"No tool named {toolUse.Name}.", false);
results.Add(new ContentBlockParam(new ToolResultBlockParam
{
ToolUseID = toolUse.ID,
Content = result.Json,
IsError = result.IsError, // lets Claude explain instead of guess
}));
}
messages.Add(new UserMessageParam { Content = results });
}
return "Stopped after too many tool calls for one question.";
}
}
InputSchema is built from the raw schema dictionary because that's how the SDK carries additionalProperties: false, which strict mode needs; Anthropic's strict tool use docs use the same pattern in C#. The assistant turn goes back unchanged by wrapping each response block's Json in a ContentBlockParam. The SDK's own default timeout is 10 minutes and it retries some failures twice on its own, so set Timeout explicitly and remember that MaxRounds counts model turns, not HTTP attempts.
IpLookupTool didn't change at all. That's the payoff of keeping the tool provider-neutral: the agents are envelopes, and the logic you tested lives in one place. Both AskAsync methods also accept a client, so tests can point the SDK at a fake HttpMessageHandler and run the whole loop offline. A small Program.cs picks the provider:
using IpAgent;
// dotnet run -- "Where is 8.8.8.8, and what time zone is it in?"
// Set LLM_PROVIDER=claude to use Claude instead of OpenAI.
string question = args.Length > 0 ? string.Join(' ', args) : "Where is 8.8.8.8, and what time zone is it in?";
var ipTool = new IpLookupTool();
string answer = Environment.GetEnvironmentVariable("LLM_PROVIDER") == "claude"
? await ClaudeAgent.AskAsync(question, ipTool)
: await OpenAiAgent.AskAsync(question, ipTool);
Console.WriteLine(answer);
Cache lookups for five minutes
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 ConcurrentDictionary inside IpLookupTool 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 covers the repeat questions in a typical conversation. It's per instance, though. Once you run more than one, move it to IDistributedCache backed by Redis with the same TTL.
Treat tool output as data, not instructions
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.
MCP vs function calling: when the server wins
Several major IP data providers now ship MCP servers. If your agent lives in an MCP client such as Claude Desktop, Cursor, VS Code, or Cline, installing your provider's server typically gets you lookup tools for location, network, and security data without writing any of the code above. Keep the API key in the client's private configuration, not in a committed file.
From your own code calling a model API, check how the server authenticates. OpenAI's Responses API accepts a headers field in its MCP tool configuration, so it can reach servers that expect an API key in a custom header. Claude's MCP connector currently documents bearer authentication through authorization_token, without a custom-header option, so a server that needs a custom header requires an authentication bridge or an MCP client you control. In .NET, that client is the MCP C# SDK (ModelContextProtocol), which plugs into the IChatClient abstraction that the Anthropic SDK implements. For one narrow lookup, a class you own still gives you direct control over validation, caching, and the response shape.
My rule: one narrow tool in your own agent, write the class. Five tools, or the same tools in several clients, use the server.
A few extra notes
If your key has access to threat data such as VPN, proxy, and Tor flags, expose it as a separate tool and register that tool only for sessions allowed to see it. A key without access to that data gets HTTP 401, which ErrorFor already turns into a readable error.
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 background job 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.
Summary
A function-calling tool is only as reliable as the code behind it. In C#, that means validating the IP against a bogon list before the network call, asking the API for only the fields the model needs, parsing coordinates with the invariant culture, turning every failure into a fixed message, keeping the request URL out of logs, caching for a few minutes, and capping the number of tool rounds. Built that way, the same IpLookupTool runs unchanged behind OpenAI's Responses API and Claude's Messages API, and an MCP server becomes the better option once you need many tools across several clients.
Join the conversation! Your thoughts help the community grow.