Showing posts with label Agent. Show all posts
Showing posts with label Agent. Show all posts

Saturday, May 16, 2026

Squad with GitHub Copilot CLI: Human-led AI agent teams

What is Squad?

Squad is a team of agents that work on your behalf to conduct specializations like: DevOps, Testing, DB optimization, etc. Squad works with GitHub Copilot CLI. In this article, we will explore Squad by getting it to create ASP.NET Blazor application, then enhance it with more features.

ⓘ NOTE: 

  • This is an experimental project and may change over time.
  • Using Squad can result in the consumption of a sizable amount of AI tokens.

Pre-requisites

In order to proceed with this tutorial, you will need to have the following software installed on your computer:

  1. .NET 10.0 or later
  2. SQLite 
  3. GitHub Copilot CLI
  4. Node.js and npm (version 5.2.0 or higher) 

The GitHub repo for the Squad project is at https://github.com/bradygaster/squad

ⓘ NOTE the following about Squad:

  1. Squad works with GitHub Copilot
  2. You need to have Node.js and npm (version 5.2.0 or higher) installed on your computer in order to setup Squad.
  3. Using Squad can result in the consumption of a sizable amount of AI tokens.

Connect to a SQLite Database

Let's use GitHub Copilot CLI to connect to and explore the Chinook database (a sample database that represents a digital music store).

What is the Chinook Database?

The Chinook database models a digital media store, similar to an old iTunes store. It contains real music data and includes 11 tables:

Table Description
Artist Music artists
Album Albums released by artists
Track Individual songs, including price and duration
Genre Music genres (Rock, Jazz, Pop, etc.)
MediaType Format of the track (MP3, AAC, etc.)
Playlist Named playlists
PlaylistTrack Tracks belonging to each playlist
Customer Store customers
Employee Store employees and their reporting structure
Invoice Customer purchases
InvoiceLine Individual line items on each invoice

Connecting to the Database

  1. Download the Chinook.sqlite database file here 👉Click to download

  2. Create a folder named Chinook and place the downloaded Chinook.sqlite file inside it.

  3. Open your terminal, navigate to the Chinook folder, and launch GitHub Copilot CLI, by typing in:

copilot
        
  1. Wait for the Copilot CLI interface to load. You should see the prompt ready for input.

  2. Once inside Copilot CLI, type the following prompt and press ENTER to establish a connection to the Chinook database. This tells Copilot which database file to use and how to access it.

    Connect to the Chinook.sqlite database using the connection string DataSource=Chinook.sqlite;Cache=Shared;
            
  3. You should see Copilot confirm the connection. If you are asked to trust files in the current folder or asked to run commands, press ENTER to confirm Yes.

Exploring the Database

Once connected, try the following prompts one at a time. After each one, take a moment to look at the results before moving on.

List all tables in the database:

List all the tables in a table format
        

See what is inside a table:

Display data in the Genre table.
        

Ask for insights:

Analyse the data in the database and provide me with some interesting insights.
        

Use SQLite database with ASP.NET app

Let's use GitHub Copilot CLI to build a simple ASP.NET Razor Pages web application that reads and manages data from the Chinook database. You will do this step by step, one prompt at a time.

💡TIP: If you want GitHub Copilot to run commands without always asking for confirmation, enter the command /yolo, which stands for "You Only Live Once".1


Prompt 1 — Create the Project

Type the following prompt inside Copilot CLI and press ENTER:

Create a simple ASP.NET Razor Pages web application using .NET 10 in a folder named Chinook.Web. Do not add any database or authentication yet. 
💡TIP: Wait for Copilot to finish completely before moving on to the next prompt. Rushing to the next step before Copilot is done is the most common cause of errors in this tutorial.

Prompt 2 — Connect the Database

⚠️WARNING: The following prompt connects to your existing Chinook.sqlite database. Do not modify or delete the database file while Copilot is running, as this may cause your data to be lost.

Add Entity Framework Core SQLite to Chinook.Web. Connect it to the existing Chinook.sqlite in the parent folder using connection string "DataSource=../Chinook.sqlite;Cache=Shared;" in appsettings.Development.json. Do not overwrite or delete any existing data.

💡TIP: To verify the app is running correctly, open a new terminal window, navigate to the Chinook.Web folder, and run:

dotnet watch

Your browser should open automatically.


Prompt 3 — Scaffold CRUD Pages

Create a Genre model that matches the existing Genre table in Chinook.sqlite. The SQLite database uses singular table names (e.g. Genre, not Genres), so the model must include a [Table("Genre")] attribute from System.ComponentModel.DataAnnotations.Schema to prevent Entity Framework Core from pluralizing the table name. Scaffold full CRUD Razor Pages for Genre. Add a Genre link to the main navigation menu. 
💡TIP: Go back to the terminal running dotnet watch. Your app should reload automatically. Navigate to the /Genres page in your browser. You should see a list of genres loaded from the Chinook database.

Prompt 4 — Apply the Theme

Replace the default Bootstrap CSS in _Layout.cshtml with the Bootswatch Sketchy theme CDN link from https://bootswatch.com/sketchy/

Your app should now look noticeably different (hand-drawn style buttons and a unique font). Refresh http://localhost:5000/Genres to see the new theme applied.


Prompt 5 — Run the app 

Run the app 

If everything is OK, you should see the Genre list page populated with data from the Chinook database. Try adding, editing, and deleting a genre to confirm that full CRUD functionality is working.

Let's use Squad

Install Squad globally on your computer by typing the follwoing terminal window command:

npm install -g @bradygaster/squad-cli
        

In the Chinook.Web folder created in tutorial number 2 (CRUD App), initialize Squad with:

squad init
        

Start a GitHub Copilot CLI session by typing the following terminal window command:

copilot
        

You must be logged into GitHub in order to use Squad. Type the following command in the input field to login into GitHub:

login

Select GitHub.com by hitting ENTER on 1.

GitHub.com

A message is displayed that a code will be placed in the clipboard and your browser will be used for authentication once you press any key.

authenticate

Your default browser will open to the Device Activation page.

device-activation

Choose your preferred GitHub account then click on Continue.

one-time-code

Enter the one-time code that was given to you in the GitHub Copilot CLI, then click on Continue. Note that it will be different from the code in the image above.

authorize

Click on Authorize github.

mfa

You might be required to go through the multi-function authentication process. Once you are fully authenticated, you should received the below message in your browser:

congrats

We will choose the Squad agent to help us improve the Chinook.Web app. In the input field, type the following command to select an agent:

Choose the Squad agent.

squad-agent

It would be exhausing for the developer to approve every action that agents will be attempting to make. Autopilot mode is a behavioral state where Copilot executes multi-step tasks autonomously until completion. We will set the CLI to work in autopilot mode. Cycle through all the various modes with SHIFT TAB and select autopilot.

autopilot

Enter this prompt:

I like the disney universe of cartoon characters and would like to assign a squad to work on the Chinook.Web project.  
        Review the current state, propose new features, and discuss next steps. 
        

Accept the request for elevated permissions.

permission

💡TIP: If you enter command /tasks, you can observe the individual agents at work.

A long process of autonomous work will commence. Sit back, relax, and watch what is happening. Once everything settles down, you will receive a message that looks like this:

Next steps you requested:
        
           - Review current state: Try "Mickey, review the current project 
          architecture"
           - Propose features: Try "Team, what should we build next?" or "Mickey, 
          propose features for the Chinook database"
           - Discuss next steps: Ask "What features would make the most impact?" or 
          have Mickey analyze the Chinook schema and suggest CRUD pages for other 
          entities (Artists, Albums, Tracks, etc.)
        
          Quick commands to try:
        
           - "Mickey, review the project" — architecture analysis
           - "Team, add CRUD pages for Artists" — parallel fan-out to build a feature
           - "What's in the Chinook database?" — I can answer directly (no spawn 
          needed)
           - "Ralph, status" — check for any work in progress
        
          The team is fully configured, state files are in place, and .gitattributes
          is set up for clean cross-branch merges. Ready to work!
        

Look at the source code, you will notice that much has happened.

  1. A number of skills were added to the .copilot/skills folder:

skills

  1. Workflows were added to the .github/workflows folder:

workflows

  1. Under the .squad folder, in addition to other folders and files, there is an agents folder with our Disney workers:

workers

Read the charter for each of these workers. For example, Mickey's charter in the charter.md file is:

# Mickey — Lead
        
        > Architecture, scope, and quality — the one who sees the whole picture
        
        ## Identity
        
        - **Name:** Mickey
        - **Role:** Lead & Architect
        - **Expertise:** System design, code review, architectural patterns, .NET best practices
        - **Style:** Direct and decisive. Thinks big picture first, details second.
        
        ## What I Own
        
        - Overall project architecture and design decisions
        - Code review and quality gates
        - Technical scope definition and feature planning
        - Cross-module integration and consistency
        
        ## How I Work
        
        - Start with the why, then the what, then the how
        - Push back on scope creep and unnecessary complexity
        - Review others' work with an architectural lens
        - Document key decisions in the team knowledge base
        
        ## Boundaries
        
        **I handle:** Architecture, design reviews, scope decisions, technical leadership
        
        **I don't handle:** Deep implementation details (that's for the specialists), day-to-day bug fixes
        
        **When I'm unsure:** I consult with the appropriate specialist (Donald for backend, Minnie for frontend, Goofy for testing strategy)
        
        **If I review others' work:** On rejection, I may require a different agent to revise (not the original author) or request a new specialist be spawned. The Coordinator enforces this.
        
        ## Model
        
        - **Preferred:** auto
        - **Rationale:** Coordinator selects the best model based on task type — cost first unless writing code
        - **Fallback:** Standard chain — the coordinator handles fallback automatically
        
        ## Collaboration
        
        Before starting work, use the `TEAM ROOT` provided in the spawn prompt. All `.squad/` paths must be resolved relative to this root.
        
        Before starting work, read `.squad/decisions.md` for team decisions that affect me.
        After making a decision others should know, write it to `.squad/decisions/inbox/mickey-{brief-slug}.md` — the Scribe will merge it.
        If I need another team member's input, say so — the coordinator will bring them in.
        
        ## Voice
        
        Opinionated about clean architecture. Will push back on technical debt. Prefers simplicity over cleverness. Thinks in systems, not just features. Not afraid to say "we shouldn't build that."
        

Go ahead and ask for more features. I asked for the following enhancements:

  1. add CRUD pages for Artists
  2. add Sales Dashboard & Reporting
  3. recruit a GitHub DevOps engineer to configure some github actions for CI
  4. add web designer to help make the UI of the entire web app more colorful and compelling
ⓘ NOTE that agents get to choose different models for theie assigned tasks. For example: Mickey is using claude-sonnet-4.6, and Daisy is using claude-opus-4.5, etc.

models

There are instances when one agent waits for other agents to complete their assigned tasks.

wait

The end result is that we now have a web app that is colorful, has artists crud, and a dashboard.

end-result

Here's what the dashboard looks like:

dashboard

To find out token usage, you can type the /usage command. I used 7.5 million tokens. Most were used in understanding the entireity of the code base.

usage

Squad is a very interesting tool and provides us with an insight into the future world of software development.

Wednesday, February 25, 2026

Explore A2A protocol with .NET and GitHub Models

Let's explore the Agent-to-Agent (A2A) protocol using .NET. The A2A protocol standardizes communication between agents. It allows agents built with different frameworks and technologies to seamlesssly communicate with one-another.

What's A2A?

A2A is a standardized protocol that supports:

  • Agent discovery through agent cards
  • Message-based communication between agents
  • Long-running agentic processes via tasks
  • Cross-platform interoperability between different agent frameworks

The A2A protocol was developed by Google and later donated to the Linux Foundation.For more information, visit A2A protocol specification.

Source Code: https://github.com/medhatelmasry/A2Aapi

Get Started

In the following example, we will learn how to expose an agent with A2A. The example uses an AI model hosted on GitHub. In addition, we will use Swagger to simplify testing.

In a working directory on your computer, create an ASP.NET Minimal API project named A2Aapi with the following terminal window command:

dotnet new webapi -o A2Aapi
cd A2Aapi
dotnet new gitignore

Install the following NuGet packages:

# Hosting.A2A.AspNetCore for A2A protocol integration
dotnet add package Microsoft.Agents.AI.Hosting.A2A.AspNetCore -v 1.0.0-preview.260219.1

# Libraries to connect to GitHub AI models
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.AI.OpenAI

# Swagger to test app
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Swashbuckle.AspNetCore


Configure connection to GitHub AI Models

You will need to get a Personal Access Token from GitHub. If this is the first time, follow this tutorial.

Add the following JSON to appsettings.Development.json file:

"GitHub": {
    "Token": "put-your-github-personal-access-token-here",
    "ApiEndpoint": "https://models.github.ai/inference",
    "Model": "openai/gpt-4o-mini"
}

NOTE: Replace put-your-github-personal-access-token-here with your GitHub Personal Access Token.

Edit the .gitignore file in the A2Aapi folder and add to it appsettings.Development.json so that your secrets do not find their way into source control by mistake.

Replace contents of Program.cs with the following code:

using OpenAI;
using Microsoft.Agents.AI.Hosting;
using Microsoft.Extensions.AI;
using Azure;
using OpenAI.Chat;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();
builder.Services.AddSwaggerGen();

string githubToken = builder.Configuration["GitHub:Token"]
    ?? throw new InvalidOperationException("GitHub:Token is not set.");
string apiEndpoint = builder.Configuration["GitHub:ApiEndpoint"]
    ?? throw new InvalidOperationException("GitHub:ApiEndpoint is not set.");
string model = builder.Configuration["GitHub:Model"]
    ?? throw new InvalidOperationException("GitHub:Model is not set.");

// Register the chat client
IChatClient chatClient = new ChatClient(
    model,
    new AzureKeyCredential(githubToken),
    new OpenAIClientOptions
    {
        Endpoint = new Uri(apiEndpoint)
    }
)
.AsIChatClient();

builder.Services.AddSingleton(chatClient);

// Register agents
var pirateAgent = builder.AddAIAgent("pirate", instructions: "You are a pirate. Speak like a pirate.");

var app = builder.Build();

app.MapOpenApi();
app.UseSwagger();
app.UseSwaggerUI();

// Expose the agent via A2A protocol. You can also customize the agentCard
app.MapA2A(pirateAgent, path: "/a2a/pirate", agentCard: new()
{
    Name = "Pirate Agent",
    Description = "An agent that speaks like a pirate.",
    Version = "1.0"
});

app.Run();


Test Agent

Run the web app with:

dotnet run

We have two options to test our agent: we can either use Swagger by pointing our browser to the /swagger endpoint, or we can use the A2Aapi.http REST Client that is built into the ASP.NET Minimal API template.

Option 1 - using Swagger

Point your browser to the URL displayed the the terminal window with /swagger. In my case it would be http://localhost:5112/swagger. You will see an interface similar to this:

Cloose the POST /a2a/pirate/v1/message:stream endpoint.

Click on the "Try it out" 

Enter the following JSON request then click on the Execute button:
{
  "message": {
    "kind": "message",
    "role": "user",
    "parts": [
      {
        "kind": "text",
        "text": "Hey pirate! Tell me where have you been",
        "metadata": {}
      }
    ],
    "messageId": null,
    "contextId": "foo"
  }
}

The server response looks like this:

This is the prompt we sent to the agent:

Hey pirate! Tell me where have you been

This is the response from the agent:

Ahoy, matey! I've been sailin' the seven seas, searchin' fer treasure and chasin' down the fiercest storms!

From the shores of Tortuga to the depths of Davy Jones' locker, me heart be filled with tales of adventure. And where be ye anchorin" yer ship, eh?

The response includes the contextId (conversation identifier), messageId (message identifier), and the actual content from the pirate agent.

Option 2 - using .http REST Client

If you are using VS Code, install the following VS Code extension:


Edit the A2Aapi.http in your project and add this request:
###
# Send A2A request to the pirate agent
POST {{A2Aapi_HostAddress}}/a2a/pirate/v1/message:stream
Accept: application/json
Content-Type: application/json

{
  "message": {
    "kind": "message",
    "role": "user",
    "parts": [
      {
        "kind": "text",
        "text": "Hey pirate! Tell me where have you been",
        "metadata": {}
      }
    ],
    "messageId": null,
    "contextId": "foo"
  }
}

Click on the "Send Request" link as shown below:

The response will show in a separate panel like this:

AgentCard Configuration

The AgentCard provides metadata about your agent for discovery and integration:

app.MapA2A(agent, "/a2a/my-agent", agentCard: new() {
   Name = "My Agent",
   Description = "A helpful agent that assists with tasks.",
   Version = "1.0",
});

The agent card can be accessed by sending this request:

# Send A2A request to the pirate agent
GET {{baseAddress}}/a2a/pirate/v1/card


Properties of the Agent Card

NameDisplay name of the agent
DescriptionBrief description of the agent
VersionVersion string for the agent
UrlEndpoint URL (automatically assigned if not specified)
CapabilitiesOptional metadata about streaming, push notifications, and other features


Exposing More Agents

You can expose multiple agents in a single application, as long as their endpoints don't collide. Here's an example:

Add the following code to Program.cs right under the "// Register agents" comment line:

var mathAgent = builder.AddAIAgent("math", instructions: "You are a math expert.");
var scienceAgent = builder.AddAIAgent("science", instructions: "You are a science expert.");

Similarly, add these endpoint mappings to Program.cs right above the last "app.Run();" statement:

app.MapA2A(mathAgent, "/a2a/math");
app.MapA2A(scienceAgent, "/a2a/science");

You can test the math agent and science agents with these respective requests:

Test math agent

###
# Send A2A request to the math agent
POST {{A2Aapi_HostAddress}}/a2a/math/v1/message:stream
Accept: application/json
Content-Type: application/json

{
  "message": {
    "kind": "message",
    "role": "user",
    "parts": [
      {
        "kind": "text",
        "text": "add 2 and 7",
        "metadata": {}
      }
    ],
    "messageId": null,
    "contextId": null
  }
}


Test science agent

###
# Send A2A request to the science agent
POST {{A2Aapi_HostAddress}}/a2a/science/v1/message:stream
Accept: application/json
Content-Type: application/json

{
  "message": {
    "kind": "message",
    "role": "user",
    "parts": [
      {
        "kind": "text",
        "text": "how far is saturn from earth?",
        "metadata": {}
      }
    ],
    "messageId": null,
    "contextId": null
  }
}


Conclusion

Therea re many emerging protocols that are giving us an insight into the future landscapte of the Agentic AI world o the future. This is one amone others. I trust that is article gives you in insight into the significance of the A2A protocol.

References

A2A Integration

Agent2Agent (A2A) Protocol

Monday, October 6, 2025

Explore Docker MCP Toolkit and VS Code

To explore Docker MCP Toolkit, we will use two MCP server in the toolkit, namely PostgreSQL and Playwright.

Companion Video: https://youtu.be/43oJi_gAucU

What is Docker MCP Toolkit?

The Docker MCP Toolkit enables hosting and managing MCP servers. These servers expose APIs for specific development tasks, such as retrieving GitHub issue data or querying databases using natural language.

Prerequisites

You will need the following before you can continue:

  • Docker Desktop (latest version)
  • Visual Studio Code (latest version)
  • GitHub Copilot extension for VS Code
  • GitHub Copilot with Chat and Agent Mode enabled

1) Explore PostgreSQL MCP Server

We will use natural language to query a PostgreSQL database that is already pre-loaded with the sample Northwind database. To run the PostgreSQL server in a docker container on your computer, execute the following command from any terminal window:


docker run --name psqlnw -e POSTGRES_PASSWORD=VerySecret -p 5433:5432 -d melmasry/nw-psql:1.0.0

Start “Docker Desktop” on your computer and go to the Containers tab on the left navigation. You will see that the psqlnw container is running.


Next, let us use the Docker MCP Toolkit. In Docker Desktop, click on “MCP Toolkit” in the left navigation.

Click on the Catalog tab. This will show you a list of MCP Servers that are ready for you to explore. 

We will start with PostgreSQL. Find the PostgreSQL MCP Server by entering ‘postgr’ in the filter field. Then click on + to add it to your list.

You will be asked to enter a secret. This is nothing but the connection string and it is based on this format:

postgresql://readonly_user:readonly_password@host:port/database_name

In our case, this would be:

postgresql://postgres:VerySecret@host.docker.internal:5433/northwind

Click on the "My Servers" tab to see the MCP servers that you have chosen.

Connect Docker MCP Toolkit to Visual Studio Code

Let us query our northwind database in PostgreSQL from VS Code. Go to a working directory and execute these commands to create an empty folder on your computer:

mkdir mcp-server
cd mcp-server

In the same terminal window, logout and login into docker with:

docker logout  
docker login

Start VS Code in the folder with

code .

In VS Code, open the Command Palette by pressing Ctrl + Shift + P (or Cmd + Shift + P on macOS).

Select “Add MCP Server”.

Select “Command (stdio) Run a local command that implements the MCP protocol Manual Install”.

Enter the gateway command:

docker mcp gateway run

Give the server an ID named: 

my-mcp-server

Choose “Workspace Available in this workspace, runs locally”.


Click Trust.

A file named mcp.json is created in a .vscode folder with this content:

Note that the server is running. 

Inside the Github Copilot Chat window, choose Agent and any Claude model. Click on the tools icon to see active MCP servers.

You will find MCP servers that are configured in VS Code. Among them will be the one we enabled in the Docker MCP Toolkit.

You will notice that it only has one tool: “query Run a read-only SQL query”. This is all that is needed to query the northwind database.

Click ok the Ok button to close the tools popup.

Enter this prompt in the GitHub Copilot window:

What are the tables in the PostgreSQL northwind database?

You will be asked to click on the Allow button.

Thereafter, it displays a list of database tables in the northwind database.

Try this other prompt:

What are the products supplied by "Exotic Liquids"?

You will get a similar response to this:

2) Explore Playwright MCP Server

Back in Docker Desktop >> MCP Toolkit, add Playwright.

You now have two MCP servers in our list: Playwright and PostgreSQL.

Back in VS Code, restart the MCP Server in the .vscode/mcp.json file.

In the VS Code GitHub Copilot Chat window, enter this prompt:

Using the tools provided from the Docker MCP Server, navigate to https://www.bbc.com/, find the two most important business stories.

I got the following response at the time of writing this article:

Conclusion

I hope you found this article useful. These are early days of MCP servers. I am sure things will evolve much more in this very important space.

Saturday, September 20, 2025

Build web-based MCP server and client with ASP.NET & GitHub Models

Overview

This article demonstrates how to build a basic MCP server and client using ASP.NET and Server Sent Events (SSE). The MCP server exposes tools that can be discovered and used by LLMs, while the client application connects these tools to an AI service. GitHub AI models are used on the client application.

Server Sent Events (SSE)

SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication. This approach facilitates communication between frontend microservices and backend business contexts through the MCP server. 

Companion Video: https://youtu.be/vTBtPU7AnT4

Source Code: https://github.com/medhatelmasry/AspMCP

Prerequisites

  • GitHub account
  • Visual Studio Code
  • .NET 9.0 (or later)

Setup

We will create an .NET solution comprising of an ASP.NET web server project; a WebAPI client project; and add the required packages with these terminal window commands:

mkdir AspMCP
cd AspMCP
dotnet new sln
dotnet new web -n ServerMCP
dotnet sln add ./ServerMCP/ServerMCP.csproj
cd ServerMCP
dotnet add package Azure.AI.OpenAI
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
dotnet add package ModelContextProtocol --prerelease
dotnet add package ModelContextProtocol.AspNetCore --prerelease
cd ..
dotnet new webapi --use-controllers -n ClientMCP
dotnet sln add ./ClientMCP/ClientMCP.csproj
cd ClientMCP
dotnet add package Azure.AI.OpenAI
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
dotnet add package ModelContextProtocol --prerelease
dotnet add package Swashbuckle.AspNetCore
cd ..

Open the solution in VS Code. To do that, you can enter this command in a terminal a terminal window:

code .

Build ASP.NET Server

In the ServerMCP project, add this service to Program.cs before “var app = builder.Build();”:

builder.Services.AddMcpServer()
.WithHttpTransport()
.WithToolsFromAssembly();

In the same server Program.cs file, add this code just before “app.Run();”:

// Add MCP middleware
app.MapMcp();

Delete (or comment out) this code in the Program.cs file:

app.MapGet("/", () => "Hello World!");

In the server project create a folder named McpTools folder and add to it a GreetingTool class with this code:

[McpServerToolType]
public sealed class GreetingTool {
  public GreetingTool() { }
  
  [McpServerTool, Description("Says Hello to a user")]
  public static string Echo(string username) {
    return "Hello " + username;
  }
}

Test Server

In a terminal window inside the server project, run this command to start the server:

dotnet watch

Point your browser to https://localhost:????/sse. 

Note : replace ???? with your port number. 

This is what you will see:


Build Client

In the client project......

1) Add these settings to the appsettings.json file.

"AI": {
  "ModelName": "gpt-4o-mini",
  "Endpoint": "https://models.inference.ai.azure.com",
  "ApiKey": "PUT-GITHUB-TOKEN-HERE",
  "MCPServiceUri": "http://localhost:5053/sse"
}

NOTE: adjust values for ApiKey and MCPServiceUri accordingly.

2) Register Services via Dependency Injection. Add the following to your client Program.cs:
var endpoint = builder.Configuration["AI:Endpoint"];
var apiKey = builder.Configuration["AI:ApiKey"];
var model = builder.Configuration["AI:ModelName"];

builder.Services.AddChatClient(services =>
  new ChatClientBuilder(
    (
      !string.IsNullOrEmpty(apiKey)
        ? new AzureOpenAIClient(new Uri(endpoint!), new AzureKeyCredential(apiKey))
        : new AzureOpenAIClient(new Uri(endpoint!), new DefaultAzureCredential())
    ).GetChatClient(model).AsIChatClient()
  )
  .UseFunctionInvocation()
  .Build());
 

3) To view the swagger UI, add this code right below “app.MapOpenApi();”:
app.UseSwaggerUI(options => {
  options.SwaggerEndpoint("/openapi/v1.json", "MCP Server");
  options.RoutePrefix = "";
});
 

4) Edit Properties/launchSettings.json, change launchBrowser to true under http and https. This is so that the app automatically launches in a browser when you run the project with “dotnet watch”.

In the Controllers folder, create a ChatController class with the following code:

[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase {
  private readonly ILogger<ChatController> _logger;
  private readonly IChatClient _chatClient;

  private readonly IConfiguration? _configuration;
  public ChatController(
    ILogger<ChatController> logger,
    IChatClient chatClient,
    IConfiguration configuration
  ) {
    _logger = logger;
    _chatClient = chatClient;
    _configuration = configuration;
  }

  [HttpPost(Name = "Chat")]
  public async Task<string> Chat([FromBody] string message) {
    // Create MCP client connecting to our MCP server
    var mcpClient = await McpClientFactory.CreateAsync(
      new SseClientTransport(
          new SseClientTransportOptions {
              Endpoint = new Uri(_configuration?["AI:MCPServiceUri"] ?? throw new InvalidOperationException("MCPServiceUri is not configured"))
          }
      )
    );
    // Get available tools from the MCP server
    var tools = await mcpClient.ListToolsAsync();

    // Set up the chat messages
    var messages = new List<ChatMessage> {
      new ChatMessage(ChatRole.System, "You are a helpful assistant.")
    };
    messages.Add(new(ChatRole.User, message));

    // Get streaming response and collect updates
    List<ChatResponseUpdate> updates = [];
    StringBuilder result = new StringBuilder();

    await foreach (var update in _chatClient.GetStreamingResponseAsync(
      messages,
      new() { Tools = [.. tools] }
    )) {
      result.Append(update);
      updates.Add(update);
    }
    
    // Add the assistant's responses to the message history
    messages.AddMessages(updates);
    return result.ToString();
  }
}

Test server and client

1) Start the server in a terminal window with: dotnet watch

2) Start the client in another terminal window also with: dotnet watch

The following swagger page will load in your browser. Click on POST, then “Try it out”.


3)  string with your name, then click on Execute.


4) You will receive a response like below.


A more realistic solution

To develop a more realistic solution, we will add a database to the server project. Thereafter, our MCP client can query the database using natural language. This is very compelling for line-of-business applications.

In the server project, make these changes.

1) Add these packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.SQLite.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package CsvHelper
 

2) Add this to appsettings.json:

"ConnectionStrings": {
  "DefaultConnection": "DataSource=beverages.sqlite;Cache=Shared"
}

3) Copy CSV data from this link. Then, save the content is a file named beverages.csv and put that file in a wwwroot folder in tour project.

4) In a Models folder, add a class named Beverage with this code:
public class Beverage {
  [Required]
  public int BeverageId { get; set; }

  public string? Name { get; set; }

  public string? Type { get; set; }

  public string? MainIngredient { get; set; }

  public string? Origin { get; set; }

  public int? CaloriesPerServing { get; set; }

  public void DisplayInfo() {
    Console.WriteLine($"{Name} is a {Type} from {Origin} made with {MainIngredient}. It has {CaloriesPerServing} calories per serving.");
  }
}

5) In a Data folder, add this ApplicationDbContext class:
public class ApplicationDbContext : DbContext {
  public DbSet<Beverage> Beverages => Set<Beverage>();

  public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options) { }

  protected override void OnModelCreating(ModelBuilder modelBuilder) {
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Beverage>().HasData(GetBeverages());
  }

  private static IEnumerable<Beverage> GetBeverages() {
    string[] p = { Directory.GetCurrentDirectory(), "wwwroot", "beverages.csv" };
    var csvFilePath = Path.Combine(p);

    var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
      Encoding = Encoding.UTF8,
      PrepareHeaderForMatch = args => args.Header.ToLower(),
    };

    var data = new List<Beverage>().AsEnumerable();
    using (var reader = new StreamReader(csvFilePath)) {
      using (var csvReader = new CsvReader(reader, config)) {
        data = csvReader.GetRecords<Beverage>().ToList();
      }
    }

    return data;
  }
}

6) Add this service to Program.cs:
var connStr = builder.Configuration.GetConnectionString("DefaultConnection") 
    ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    
builder.Services.AddDbContext<ApplicationDbContext>(
	option => option.UseSqlite(connStr)
);

 7) In the same Program.cs file, add this code right before “app.Run();”:
// Apply database migrations on startup
using (var scope = app.Services.CreateScope()) {
    var services = scope.ServiceProvider;

    var context = services.GetRequiredService<ApplicationDbContext>();    
    context.Database.Migrate();
}

8) Now, we can add and apply database migrations with:
dotnet ef migrations add M1 -o Data/Migrations
dotnet ef database update

At this stage, the beverages.sqlite database is populated with real data:


9) Let us add a class that queries the SQLite database. Inside of a Services folder, add a class named BeverageService with this content:

public class BeverageService(ApplicationDbContext db) {
  public async Task<string> GetBeveragesJson() {
    var beverages = await db.Beverages.ToListAsync();
    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }

  public async Task<string> GetBeverageByIdJson(int id) {
    var beverage = await db.Beverages.FindAsync(id);
    return System.Text.Json.JsonSerializer.Serialize(beverage);
  }

  public async Task<string> GetBeveragesContainingNameJson(string name) {
    var beverages = await db.Beverages
      .Where(b => b.Name!.Contains(name))
      .ToListAsync();

    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }


  public async Task<string> GetBeveragesContainingTypeJson(string type) {
    var beverages = await db.Beverages
      .Where(b => b.Type!.Contains(type))
      .ToListAsync();

    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }

  public async Task<string> GetBeveragesByIngredientJson(string ingredient) {
    var beverages = await db.Beverages
      .Where(b => b.MainIngredient!.Contains(ingredient))
      .ToListAsync();

    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }

  public async Task<string> GetBeveragesByCaloriesLessThanOrEqualJson(int calories) {
    var beverages = await db.Beverages
      .Where(b => b.CaloriesPerServing <= calories)
      .ToListAsync();

    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }

  public async Task<string> GetBeveragesByOriginJson(string origin) {
    var beverages = await db.Beverages
      .Where(b => b.Origin!.Contains(origin))
      .ToListAsync();

    return System.Text.Json.JsonSerializer.Serialize(beverages);
  }
}

10) Next, expose MCP tooling that interacts with the SQLite data. In the McpTools folder, add a class named BeverageTools with this code:

[McpServerToolType]
public class BeverageTool
{
    private readonly BeverageService _beverageService;
    private readonly ApplicationDbContext _db;

    public BeverageTool(ApplicationDbContext db)
    {
        _db = db;
        _beverageService = new BeverageService(_db);
    }

    [McpServerTool, Description("Get a list of beverages and return as JSON array")]
    public string GetBeveragesJson()
    {
        var task = _beverageService.GetBeveragesJson();
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get a beverage by ID and return as JSON")]
    public string GetBeverageByIdJson([Description("The ID of the beverage to get details for")] int id)
    {
        var task = _beverageService.GetBeverageByIdJson(id);
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get beverages by name and return as JSON")]
    public string GetBeveragesByNameJson([Description("The name of the beverage to filter by")] string name)
    {
        var task = _beverageService.GetBeveragesContainingNameJson(name);
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get beverages by type and return as JSON")]
    public string GetBeveragesByTypeJson([Description("The type of the beverage to filter by")] string type)
    {
        var task = _beverageService.GetBeveragesContainingTypeJson(type);
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get beverages by ingredient and return as JSON")]
    public string GetBeveragesByIngredientJson([Description("The ingredient of the beverage to filter by")] string ingredient)
    {
        var task = _beverageService.GetBeveragesByIngredientJson(ingredient);
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get beverages by calories less than or equal to and return as JSON")]
    public string GetBeveragesByCaloriesLessThanOrEqualJson([Description("The maximum calories per serving to filter by")] int calories)
    {
        var task = _beverageService.GetBeveragesByCaloriesLessThanOrEqualJson(calories);
        return task.GetAwaiter().GetResult();
    }

    [McpServerTool, Description("Get beverages by origin and return as JSON")]
    public string GetBeveragesByOriginJson([Description("The origin of the beverage to filter by")] string origin)
    {
        var task = _beverageService.GetBeveragesByOriginJson(origin);
        return task.GetAwaiter().GetResult();
    }
}

You can now test the Student MCP service. Start the server project followed by the client project. In the client app, enter prompt: beverages high in calories.

Here is the output:


Conclusion

You are now able to create your own MCP server using .NET. Of course, you can deploy the server to the cloud and use it from a variety of client applications and devices. Go ahead and create MCP servers that do wonderful things.