DEV Community

Cover image for MCP Server with .Net
Antonio Di Motta
Antonio Di Motta

Posted on

MCP Server with .Net

With the release 1.0 of the official ModelContextProtocol .Net SDK, we are ready to make a MCP Server fully compliant with MCP specs and entirely in C#.

As usually when I need to learn new stuffs I develop a simple demo around a real scenario. For the MCP Server I thought to build one for managing some data like customers, products and orders stored into a Postgres database.

The MCP server provides the data on behalf of user prompt like:

    give me the customer list
    tell me the most expensive order
    how many USB-C Hub has been ordered ?
    give me the customer list without orders
    suggest a new product for the customer Jane Smith
    add new order
    .....
Enter fullscreen mode Exit fullscreen mode

The most important feature of MCP Server is the tool as function able to do something. Below an example of tool:

[McpServerTool(Name = "GetCustomer"), Description("Retrieve a single customer from the database.")]
public static async Task<object> GetCustomer(AppDbContext db, CancellationToken ct, ILogger<MCPTool> logger, [Description("Full name of the customer to retrieve.")] string fullName ){
        logger.LogDebug( $"Executing GetCustomer tool with full name : {fullName }" );

  var query = db.Customers.AsNoTracking();
  var result = await query.Where(c => (c.FirstName + " " + c.LastName) == fullName)
                          .FirstOrDefaultAsync(ct);

  if (result == null)
     return $"Customer with full name {fullName} not found.";

  return result;
}
Enter fullscreen mode Exit fullscreen mode

The example shows how to help llm to recognize the right tool by using specific custom attributes [McpServerTool].

Another interesting feature is the prompt. I implemented one to create a model capable of handling requests that require more complex and detailed context for responses.

Here an example:

[McpServerPrompt, Description("Generate product suggestion for new order prompt")]
public static IEnumerable<ChatMessage> SuggestProductByCustomer(
        [Description("Full name of the customer")] string fullName )
{
        return [
            new(ChatRole.System, "You are an assistant for an e-commerce platform. You help customers find products based on their preferences and past purchases."),
            new(ChatRole.User, $"Please suggest products for the customer with full name: {fullName}"),
            new(ChatRole.Assistant, "To suggest products for the customer, I will need to look up their past purchases and preferences in the database. I will use the GetCustomer and GetOrders tools to retrieve this information and then analyze it to find suitable product suggestions.")
        ];
}
Enter fullscreen mode Exit fullscreen mode

The entire demo is available here. It contains a dev setup environment which able to spin up quickly the Postgres database with already some test data.

happy coding!

Top comments (0)