Building a Complete Model Context Protocol (MCP) Implementation with .NET and Microsoft Graph API

Introduction:

The Model Context Protocol (MCP) represents a standardized approach for AI systems to interact with external data sources and services. In enterprise environments, where AI applications need to access organizational data from various sources like Microsoft Graph, SharePoint, or custom APIs, MCP provides a structured framework for these interactions.

This article provides a comprehensive implementation of the Model Context Protocol (MCP) using .NET technologies. It demonstrates how to build a full-stack enterprise application that seamlessly integrates AI capabilities with the Microsoft Graph API. The solution showcases a modern architecture combining Blazor Server for the client interface, Azure OpenAI for intelligent interactions, and a custom MCP server for Microsoft Graph data access.

This is a series of my articles on MCP. Please find below the links to go through my other articles on MCP.

This MCP is an extension, and it could potentially replace the interface developed in my last article using Microsoft Fluent UI for the Azure AD B2C Application role management.

Implementation

  • Real-time AI chat interface with ChatGPT-style interactions
  • Seamless Microsoft Graph integration for accessing Azure AD B2C organizational data
  • Robust fallback mechanisms ensuring reliability
  • Enterprise-grade security with Microsoft Entra ID authentication
  • Scalable architecture ready for production deployment

Projects Breakdown:

ComponentTechnologyPurposeKey Features
MCP.ADB2C. ClientBlazor Server (.NET 8)User interface with AI chat capabilitiesReal-time chat, Azure OpenAI integration, responsive design
MCP.ADB2CASP.NET Core (.NET 8)MCP protocol implementation and Microsoft Graph integrationTool registration, Graph API calls, and authentication management
ServiceDefaults.NET 8Shared configurations and service defaultsCommon logging, configuration, and service registration

Technology Stack:

Frontend Technologies:

  • Blazor Server: Provides interactive UI with server-side rendering
  • SignalR: Enables real-time communication for chat functionality
  • Bootstrap 5: Ensures responsive and modern UI design
  • CSS Grid/Flexbox: Advanced layout management

Backend Technologies:

  • ASP.NET Core: High-performance web framework
  • MCP.NET.Server: Official .NET implementation of MCP protocol
  • Microsoft Graph SDK: Access to Microsoft 365 data
  • Azure OpenAI: GPT-4 integration for intelligent responses

Authentication & Security:

  • Microsoft Entra ID: Enterprise identity management
  • Microsoft Identity Web: Simplified authentication integration
  • JWT Tokens: Secure API communication

Implementation:

MCP Server

The MCP server serves as a bridge between the AI client and the Microsoft Graph API. Here’s how it’s structured:

MCPServerService.cs – Core server management

public class MCPServerService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        var serverInfo = new ServerInfo { Name = "MCP Graph Server", Version = "1.0.0" };
        _mcpServer = new McpServer(serverInfo);
        
        // Register available tools
        await toolsService.RegisterToolsAsync(_mcpServer);
        
        // Keep server running
        while (!stoppingToken.IsCancellationRequested)
        {
            await Task.Delay(1000, stoppingToken);
        }
    }
} 

MCPToolsService.cs – Tool registration and execution

public async Task RegisterToolsAsync(McpServer server)
{
    // Register user profile tool
    server.RegisterTool("get_user_profile", async (arguments) =>
    {
        var email = arguments.Value.GetProperty("email").GetString();
        var profileData = await _graphService.GetUserProfileAsync(email);
        
        return new ToolCallResult
        {
            Content = new ContentBase[]
            {
                new TextContent { Text = $"User Profile for {email}:\n\n{profileData}" }
            }
        };
    });
} 

Blazor Client Implementation

The Blazor client provides an intuitive chat interface powered by Azure OpenAI:

MCPClientService.cs – AI integration and MCP communication

public class MCPClientService
{
    private readonly AzureOpenAIClient _client;
    private readonly List<ChatMessage> _conversationHistory;

    public async Task<string> GetChatCompletionAsync(string userMessage)
    {
        // Add user message to conversation
        _conversationHistory.Add(new UserChatMessage(userMessage));
        
        // Check if MCP tool should be called
        if (await ShouldCallMCPToolAsync(userMessage))
        {
            var mcpResult = await CallMCPToolAsync(userMessage);
            _conversationHistory.Add(new SystemChatMessage($"MCP Tool Result: {mcpResult}"));
        }
        
        // Get AI response
        var response = await _client.GetChatCompletionsAsync(_deploymentName, 
            new ChatCompletionsOptions(_conversationHistory));
            
        var assistantMessage = response.Value.Choices[0].Message.Content;
        _conversationHistory.Add(new AssistantChatMessage(assistantMessage));
        
        return assistantMessage;
    }
}

Security and Authentication:

Microsoft Entra ID Integration

The application implements enterprise-grade security using Microsoft Entra ID:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        options.ClientSecret = builder.Configuration["AzureAd:ClientSecret"];
        options.SaveTokens = true;
        options.Prompt = "consent";
    }).EnableTokenAcquisitionToCallDownstreamApi(new string[] { builder.Configuration["DownstreamApi:Scopes"] }).AddInMemoryTokenCaches();

Chat window

MCP Client Chatbot

This is how the chat interface looks in a Blazor application. You can also configure the MCP server for other MCP Client like Claude or VS Code.

Read more about the step-by-step implementation and fork the source code from my GitHub Repository

Summary:

This article gives you a complete end-to-end implementation of the Model Context Protocol (MCP) using .NET, Microsoft Graph, and Azure OpenAI to build an internal enterprise application for managing Azure AD B2C users, applications, and roles. It walks through the architecture and technologies involved, including a Blazor Server client with real-time AI chat capabilities, a custom MCP server that bridges to Microsoft Graph, and enterprise-grade authentication with Microsoft Entra ID. The solution demonstrates how MCP can unify AI-driven interactions with organizational data, offering developers a standardized and secure way to integrate intelligent services with business-critical APIs.

This application shows how MCP can grow beyond just managing Azure AD B2C. It can become a central tool for many areas like HR, IT, security, and customer systems. By using MCP with .NET and Azure OpenAI, companies can build smart, scalable apps that create new ways of working.

Gowtham K

Gowtham K has been awarded as MVP(Most Valuable Professional) for 9 times by Microsoft for his exceptional contribution in Microsoft technologies under the category “Developer Technologies & Security” . He has more than 12 years of experience on Microsoft technologies such as C#, ASP.NET MVC, ASP.NET WEB API, ASP.NET Core, MS SQL Server, Azure, Microsoft Entra ID, Azure AD B2C and other technologies such as JavaScript, jQuery, HTML and CSS .He is also a blogger and author of articles on various technologies. He is also a speaker and delivered talk on various technologies like ASP.NET MVC, Azure and Azure DevOps in the public events.

Leave a Reply

Your email address will not be published. Required fields are marked *