In this tutorial, we will build an AI-powered weather assistant using the GitHub Copilot SDK and .NET. To keep the focus on the core concepts, we'll develop the application as a simple console app.
What is the weather in Vancouver?
- Create a .NET project
- Install and configure the GitHub Copilot SDK
- Build a custom tool
- Register the tool with the agent
- Create an AI agent
- Process user prompts and generate responses
By the end of this tutorial, you will have a working AI agent that can use tools to retrieve weather information and respond intelligently to user requests.
Agent workflow
The GitHub Copilot SDK supports .NET as one of its supported languages.
Step 1: Create a .NET console project
dotnet new console -n WeatherAgent
cd WeatherAgent
mkdir Helpers
Add the GitHub Copilot SDK packages:
dotnet add package GitHub.Copilot.SDK
dotnet add package Microsoft.Agents.AI.GitHub.Copilot
Step 2: Create the weather tool
Open the WeatherAgent folder in Visual Studio Code. In the project root folder, create a simple weather tools service file named WeatherTools.cs with this C# code:
using System.Globalization;
using System.Text.Json;
namespace WeatherAgent;
// Provides weather lookup functionality for AI tools.
public static class WeatherTools {
// Gets and formats the current weather for a city.
public static async Task<string> GetWeatherAsync(string city) {
return (await GetWeatherByCity(city)).ToString();
}
// Resolves the city's coordinates before requesting its current conditions.
static async Task<Weather> GetWeatherByCity(string city) {
using HttpClient client = new();
// The forecast API needs coordinates, so first resolve the city name.
// Escape the name to safely include spaces and special characters in the URL.
string encodedCity = Uri.EscapeDataString(city);
string geoUrl = $"https://geocoding-api.open-meteo.com/v1/search?name={encodedCity}&count=1";
string geoJson = await client.GetStringAsync(geoUrl);
using JsonDocument geoDoc = JsonDocument.Parse(geoJson);
// Stop here if geocoding did not find a city instead of requesting
// a forecast with invalid coordinates.
if (!geoDoc.RootElement.TryGetProperty("results", out JsonElement results) ||
results.GetArrayLength() == 0) {
throw new InvalidOperationException($"City '{city}' not found.");
}
// Read the first geocoding match and its timezone for the local-time display.
JsonElement firstResult = results[0];
double latitude = firstResult.GetProperty("latitude").GetDouble();
double longitude = firstResult.GetProperty("longitude").GetDouble();
string name = firstResult.GetProperty("name").GetString() ?? city;
string country = firstResult.GetProperty("country").GetString() ?? "";
string timeZoneId = firstResult.GetProperty("timezone").GetString() ?? "";
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTimeOffset cityTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone);
// Format coordinates with a period decimal separator so the URL
// is culture-independent.
string latStr = latitude.ToString(CultureInfo.InvariantCulture);
string lonStr = longitude.ToString(CultureInfo.InvariantCulture);
// Request only the current measurements used in the weather response.
string weatherUrl = $"https://api.open-meteo.com/v1/forecast";
weatherUrl += $"?latitude={latStr}&longitude={lonStr}";
weatherUrl += $"¤t=temperature_2m,weather_code,wind_speed_10m&timezone=auto";
string weatherJson = await client.GetStringAsync(weatherUrl);
using JsonDocument weatherDoc = JsonDocument.Parse(weatherJson);
// Convert the selected forecast fields into the app's weather result.
JsonElement current = weatherDoc.RootElement.GetProperty("current");
return new Weather {
Latitude = latitude,
Longitude = longitude,
Temperature = current.GetProperty("temperature_2m").GetDouble(),
WindSpeed = current.GetProperty("wind_speed_10m").GetDouble(),
City = name,
Country = country,
Condition = TranslateWeatherCode(current.GetProperty("weather_code").GetInt32()),
LocalTime = $"{cityTime:yyyy-MM-dd HH:mm:ss zzz}"
};
}
// Converts Open-Meteo weather codes into readable condition descriptions.
static string TranslateWeatherCode(int code) => code switch {
0 => "Clear sky",
1 => "Mainly clear",
2 => "Partly cloudy",
3 => "Overcast",
45 or 48 => "Fog",
51 or 53 or 55 => "Drizzle",
61 or 63 or 65 => "Rain",
71 or 73 or 75 => "Snow",
80 or 81 or 82 => "Rain showers",
95 => "Thunderstorm",
96 or 99 => "Thunderstorm with hail",
_ => "Unknown"
};
// Stores the weather fields used to build the tool's text response.
class Weather {
public double Latitude { get; set; }
public double Longitude { get; set; }
public double Temperature { get; set; }
public double WindSpeed { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
public string? Condition { get; set; }
public string? LocalTime { get; set; }
public override string ToString() {
string str = $"Weather in {City}/{Country}: {Temperature}°C, ";
str += $"{WindSpeed} km/h, ";
str += $"{Condition}, ";
str += $"Local Time: {LocalTime}";
return str;
}
}
}
What is a tool?
A tool is a function that the AI agent can call when it needs information or needs to perform an action.
Examples include:
- Get weather
- Read a file
- Query a database
- Call a REST API
In the above code, our weather tool fetches weather information for a given city by making an API call to a real weather service.
Step 3: Define the tool
Register a callable tool. Replace the code in Program.cs with the following:
using GitHub.Copilot;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using WeatherAgent;
// Expose the weather lookup to the agent without requiring tool-use approval.
AIFunction weatherTool = CopilotTool.DefineTool(
(string city) => WeatherTools.GetWeatherAsync(city),
toolOptions: new CopilotToolOptions {
SkipPermission = true,
},
factoryOptions: new AIFunctionFactoryOptions {
Name = "GetWeather",
Description = "Returns weather information and local time for a city.",
}
);
Why is the description important?
The AI uses the description to decide:
- When the tool should be used
- What problem it solves
- What input it expects
Good descriptions improve tool selection accuracy.
Step 4: Create the agent and register the tool
Configure the agent and register the tool with it:
await using var copilotClient = new CopilotClient();
await copilotClient.StartAsync();
// Limit the agent to GetWeather and instruct it to answer using only the tool's results.
AIAgent agent = copilotClient.AsAIAgent(
new SessionConfig {
Tools = [weatherTool],
SystemMessage = new SystemMessageConfig {
Mode = SystemMessageMode.Append,
Content = """
Always call GetWeather for weather and local time.
Use only its returned information in your answer.
If it fails, report the failure; do not guess.
"""
}
},
name: "Weather Assistant"
);
As additional tools are added, the agent can perform more complex tasks. For example:
- GetWindSpeed()
- GenerateReport()
- QueryDatabase()
Step 5: Send a prompt
User request:
// to choose Barcelona via command-line arguments: dotnet run Barcelona
string city = args.Length > 0 ? args[0] : "Vancouver";
string prompt = $"What is the weather in {city} and what time is it there?";
Execute the prompt:
// Run the agent asynchronously and print its response.
AgentResponse response = await agent.RunAsync(prompt);
Console.WriteLine(response.Text);
Run the application with dotnet run. You should get this output:
Vancouver is **overcast**, **8.1°C**, with winds at **15.2 km/h**. **Local time:** 16:05 -07:00.
Allow user to choose AI model
The SDK chooses a default AI model. The application can be extended to allow the user to choose another AI model.
Inside the Helpers folder, add a C# class named SelectionPrompt with this code:
namespace WeatherAgent.Helpers;
// Reads a numbered console selection and returns its zero-based index.
internal static class SelectionPrompt {
internal static int ReadIndex(string prompt, int optionCount, int defaultIndex) {
while (true) {
Console.Write(prompt);
var answer = Console.ReadLine()?.Trim();
// Use the default when input is blank or the input stream has ended.
if (string.IsNullOrEmpty(answer))
return defaultIndex;
// Displayed options are one-based; callers use zero-based indexes.
if (int.TryParse(answer, out var selection) && selection >= 1 && selection <= optionCount)
return selection - 1;
Console.WriteLine($"Enter a number from 1 to {optionCount}.");
}
}
}
Also in the Helpers folder, add a C# class named ModelSelector with this code:
using GitHub.Copilot;
namespace WeatherAgent.Helpers;
// Lists available Copilot models and prompts the user to select one.
internal static class ModelSelector {
internal static async Task<string> PickAsync(CopilotClient client, string preferredModel) {
// read all available models into a list
var models = (await client.ListModelsAsync()).ToList();
// Return an empty model ID when no models are available.
if (models.Count == 0)
return string.Empty;
// Match the preferred model without requiring a specific letter case.
var defaultIndex = models.FindIndex(model =>
string.Equals(model.Id, preferredModel, StringComparison.OrdinalIgnoreCase));
// Use the preferred model when available; otherwise default to the first listed model.
defaultIndex = defaultIndex >= 0 ? defaultIndex : 0;
Console.WriteLine("Choose a Copilot model:");
for (var index = 0; index < models.Count; index++) {
Console.WriteLine($" {index + 1}. {models[index].Id}");
}
// Accept a numbered selection or use the displayed default for blank input.
var selectedIndex=SelectionPrompt.ReadIndex( $"Model [{defaultIndex + 1}]: ",
models.Count,
defaultIndex);
return models[selectedIndex].Id;
}
}
The most important statement in the above code is the one that reads all available AI models into a list:
var models = (await client.ListModelsAsync()).ToList();
Let's use these helper methods in our app. In Program.cs, add this code right under the await copilotClient.StartAsync(); statement:
// the default model 'auto' will be used if no preference is specified
var model = await ModelSelector.PickAsync(copilotClient, "auto");
NOTE: Make sure you add this statement at the top of Program.cs:
using WeatherAgent.Helpers;
Also, in Program.cs, add this code inside the SessionConfig { . . . } block:
Model = model,
Run the app with dotnet run barcelona to see what it is like in Barcelona, Spain. You will be asked to choose a model. The number of displayed models depends on your subscription level with GitHub.
Choose a Copilot model: 1. auto 2. claude-sonnet-5.5 3. claude-sonnet-5 4. claude-fable-5.2 5. claude-fable-5.1 6. claude-fable-5 7. claude-opus-5.5 8. claude-opus-4.8-fast 9. claude-haiku-5.5 10. claude-haiku-4.5 11. gpt-6.1-sol 12. gpt-6.1-terra 13. gpt-6-sol Model [1]:
After entering 11 for gpt-6.1-sol, the result was:
Barcelona is **12°C and partly cloudy**, with winds of **5.8 km/h**. The reported local time is **12:24 AM on November 24, 2026**.
Understanding what happens internally
Runtime workflow
- User Prompt
- Agent Analysis
- Tool Selection
- Tool Execution
- Response Generation
Agent reasoning
- User Prompt
- Need City Weather
- Call GetWeather()
- Generate Answer
The Copilot SDK provides the orchestration layer that performs this workflow.
Conclusion
In this tutorial, we built a .NET weather assistant with the GitHub Copilot SDK, registered a tool the agent can call, and added a model-selection step. The example uses hard-coded weather data, but you can extend the same pattern to call a real weather API or connect other tools. As you do, handle API errors and credentials securely. With the SDK coordinating prompts and tool calls, you can focus on the capabilities your assistant provides.












