# DotnetFastMCP

> A lightweight .NET framework for building Model Context Protocol (MCP) servers. Integrates seamlessly with Azure AD, AWS Cognito, Auth0, OpenAI and other providers

- **Type:** MCP server
- **Install:** `agentstack add mcp-tekspry-dotnetfastmcp`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [tekspry](https://agentstack.voostack.com/s/tekspry)
- **Installs:** 0
- **Category:** [Cloud & Infrastructure](https://agentstack.voostack.com/c/cloud-infrastructure)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [tekspry](https://github.com/tekspry)
- **Source:** https://github.com/tekspry/DotnetFastMCP
- **Website:** https://medium.com/applied-ai-for-app-devs/dotnetfastmcp-the-fast-lane-for-building-ai-tools-in-net-efbf6218206b?sk=0ae77b467044dcd1bcd11a559c798048

## Install

```sh
agentstack add mcp-tekspry-dotnetfastmcp
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# DotnetFastMCP - Enterprise-Grade Model Context Protocol Server Framework

[](https://dotnet.microsoft.com)
[](https://www.nuget.org/packages/DotnetFastMCP)
[](LICENSE)
[](https://github.com/tekspry/.NetFastMCP)

**A modern, production-ready C#/.NET framework for building secure, scalable, and observable Model Context Protocol (MCP) servers with enterprise-grade authentication.**

## 🎯 Overview

DotnetFastMCP provides a clean, attribute-based approach to building MCP servers that implement the JSON-RPC 2.0 protocol. It includes a **native .NET Client Library** client for consuming MCP servers, making it a complete solution for building both sides of the Model Context Protocol. Built on ASP.NET Core, it leverages modern .NET features for high performance, reliability, and **comprehensive OAuth 2.0 / OpenID Connect authentication** out of the box.

### ⭐ Key Features

#### Core Framework
- ✅ **Simple Attribute-Based API** - Declare tools and resources with `[McpTool]` and `[McpResource]` attributes
- ✅ **First-Class Prompts Support** - Define prompts with `[McpPrompt]` for LLM interaction templates
- ✅ **Automatic Component Discovery** - Reflection-based scanning of assemblies
- ✅ **JSON-RPC 2.0 Compliant** - Full protocol compliance with proper error handling
- ✅ **Flexible Parameter Binding** - Supports both array and named parameters
- ✅ **Built on ASP.NET Core** - Leverage the powerful ASP.NET Core hosting model
- ✅ **Production Ready** - Comprehensive error handling and logging
- ✅ **Type-Safe** - Full C# type system integration

#### 🔐 Enterprise Authentication
- ✅ **6 OAuth Providers Supported** - Azure AD, Google, GitHub, Auth0, Okta, AWS Cognito
- ✅ **OAuth Proxy Built-In** - Automatic Dynamic Client Registration (DCR) for non-DCR providers
- ✅ **JWT Token Verification** - Automatic token validation with JWKS caching
- ✅ **Zero Configuration** - Set environment variables and go
- ✅ **Sensible Defaults** - Pre-configured scopes for common use cases
- ✅ **Fine-Grained Authorization** - Protect tools with `[Authorize]` attribute
- ✅ **Claims-Based Access** - Access user information from authenticated requests
- ✅ **MFA Support** - Enforce Multi-Factor Authentication for sensitive tools

#### 🔌 Native Client Library
- ✅ **McpClient** - Type-safe .NET client for consuming any MCP server
- ✅ **Transport Agnostic** - Support for both Stdio and SSE connections
- ✅ **Notification Handling** - Events for real-time logs and progress
- ✅ **Tool Invocation** - Clean `CallToolAsync` API

#### 🤖 LLM Integration
- ✅ **8 LLM Providers** - Ollama, OpenAI, Azure OpenAI, Anthropic Claude, Google Gemini, Cohere, Hugging Face, Deepseek
- ✅ **Latest Models (Feb 2026)** - Claude Opus 4.6, Gemini 3 Pro/Flash, Command A, DeepSeek V3.2
- ✅ **Unified Interface** - Single `ILLMProvider` API for all providers
- ✅ **Streaming Support** - Real-time token streaming with `IAsyncEnumerable`
- ✅ **Production-Ready** - HttpClientFactory, Polly retry policies, connection pooling
- ✅ **Plug-and-Play** - Simple extension methods: `builder.AddAnthropicProvider()`

#### 📡 Observability (v1.14.0)
- ✅ **OpenTelemetry Integration** - First-class metrics and distributed tracing
- ✅ **5 Auto-Tracked Metrics** - Tool invocations, duration, errors, prompt requests, resource reads
- ✅ **One-Line Setup** - `builder.WithTelemetry()` — zero boilerplate
- ✅ **Exporter Agnostic** - Plug in Prometheus, Application Insights, Grafana, Jaeger, or any OTLP backend
- ✅ **OTel Semantic Conventions** - Standard tag names, exception events, span status
- ✅ **Zero Overhead When Disabled** - Fully opt-in, no performance cost if unused
- ✅ **Stdio + HTTP** - Metrics work across both transports

#### 🏥 Health Checks & Diagnostics (NEW! v1.15.0)
- ✅ **Built-In Health Endpoint** - `GET /mcp/health` exposed automatically
- ✅ **One-Line Setup** - `builder.WithHealthChecks()` — no configuration required
- ✅ **Plug-In Custom Checks** - Add any check as a simple lambda (no interfaces needed)
- ✅ **Parallel Execution** - All checks run concurrently with per-check timeout
- ✅ **Standard HTTP Status Codes** - 200 Healthy / 207 Degraded / 503 Unhealthy
- ✅ **Kubernetes & Docker Ready** - Drop-in for liveness/readiness probes
- ✅ **Auto Server Diagnostics** - Tool count, uptime, framework version included
- ✅ **Zero Overhead When Disabled** - Fully opt-in, endpoint not registered unless configured

## 🚀 Quick Start

### Installation

```bash
git clone https://github.com/tekspry/.NetFastMCP.git
cd DotnetFastMCP
dotnet build -c Release
```

### Create Your First MCP Server

#### 1. Define Your Tools

Create a static class with `[McpTool]`-decorated static methods:

```csharp
using FastMCP.Attributes;

public static class MyTools
{
    [McpTool(Description = "Adds two numbers")]
    public static int Add(int a, int b) => a + b;

    [McpTool(Description = "Returns an echo of the input")]
    public static string Echo(string message) => message;
}
```

#### 2. Create Program.cs

```csharp
using FastMCP.Hosting;
using FastMCP.Server;
using System.Reflection;

var server = new FastMCPServer("MyMcpServer");
var builder = McpServerBuilder.Create(server, args);
builder.WithComponentsFrom(Assembly.GetExecutingAssembly());

var app = builder.Build();
await app.RunMcpAsync(args);
```

### Running the Example Server

```bash
cd examples/BasicServer
dotnet run
```

The server will start on `http://localhost:5000`.

## 📚 Architecture

### Core Components

```
DotnetFastMCP/
├── src/
│   ├── FastMCP/
│   │   ├── Attributes/          # Component declaration attributes
│   │   ├── Client/              # 🔌 Client library implementation
│   │   ├── Hosting/             # Server hosting and middleware
│   │   ├── Protocol/            # JSON-RPC protocol implementation
│   │   ├── Server/              # FastMCPServer core class
│   │   └── FastMCP.csproj
│   └── FastMCP.CLI/             # Command-line utilities
├── examples/
│   └── BasicServer/             # Example MCP server implementation
├── tests/
│   └── McpIntegrationTest/      # Integration tests
├── LAUNCH_TESTS.ps1             # PowerShell test suite launcher
└── RUN_AND_TEST.ps1             # PowerShell integration test script
```

### Project Structure

| Project | Purpose |
|---------|---------|
| `FastMCP` | Core framework library |
| `FastMCP.CLI` | Command-line interface tools |
| `BasicServer` | Example MCP server implementation |
| `McpIntegrationTest` | Integration tests |
| `ClientDemo` | Example Client consuming BasicServer |

## 🔧 Creating an MCP Server

### 1. Define Components

For better organization, split your components into multiple files (e.g., `Tools.cs`, `Resources.cs`). The framework will discover them automatically.

**File: `Tools.cs`**
```csharp
using FastMCP.Attributes;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

public static class MyTools
{
    /// 
    /// Public tool - no authentication required
    /// 
    [McpTool]
    public static int Add(int a, int b) => a + b;

public static class Resources
{
    /// 
    /// Protected tool - requires authentication
    /// 
    [McpTool]
    [Authorize]
    public static object GetUserProfile(ClaimsPrincipal user)
    {
        return new
        {
            Name = user.Identity?.Name,
            Email = user.FindFirst("email")?.Value,
            IsAuthenticated = user.Identity?.IsAuthenticated
        };
    }
}
```

#### 2. Configure Server with Authentication

```csharp
using FastMCP.Hosting;
using FastMCP.Server;
using System.Reflection;

var mcpServer = new FastMCPServer(name: "My Secure MCP Server");
var builder = McpServerBuilder.Create(mcpServer, args);

// Add authentication (choose your provider)
builder.AddAzureAdTokenVerifier();  // or AddGoogleTokenVerifier(), AddGitHubTokenVerifier(), etc.

// Register tools
builder.WithComponentsFrom(Assembly.GetExecutingAssembly());

var app = builder.Build();
app.Urls.Add("http://localhost:5002");
await app.RunAsync();
```

#### 3. Set Environment Variables

```powershell
# Windows PowerShell
$env:FASTMCP_SERVER_AUTH_AZUREAD_TENANT_ID="your-tenant-id"
$env:FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_ID="your-client-id"
$env:FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_SECRET="your-client-secret"
```

```bash
# Linux/Mac
export FASTMCP_SERVER_AUTH_AZUREAD_TENANT_ID="your-tenant-id"
export FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_ID="your-client-id"
export FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_SECRET="your-client-secret"
```

#### 4. Run and Test

```bash
dotnet run
```

Your server is now running with **OAuth Proxy** endpoints:
- MCP endpoint: `http://localhost:5002/mcp`
- OAuth authorization: `http://localhost:5002/oauth/authorize`
- OAuth token: `http://localhost:5002/oauth/token`
- Discovery: `http://localhost:5002/.well-known/oauth-authorization-server`

#### Stdio Mode
You can also run the server in Stdio mode (for local LLM clients):
```bash
dotnet run -- --stdio
```

### Create an MCP Client

Connect to any MCP server using the C# Client Library:

```csharp
using FastMCP.Client;
using FastMCP.Client.Transports;

// 1. Connect (via Stdio or SSE)
var transport = new StdioClientTransport("dotnet", "run --project examples/BasicServer -- --stdio");
await using var client = new McpClient(transport);
await client.ConnectAsync();

// 2. List & Call Tools
var tools = await client.ListToolsAsync();
var result = await client.CallToolAsync("add_numbers", new { a = 10, b = 20 });
```

## 🔐 Authentication Providers

DotnetFastMCP supports **6 enterprise-grade OAuth providers** out of the box:

| Provider | Method | Use Case | Default Scopes |
|----------|--------|----------|----------------|
| **Azure AD** | `AddAzureAdTokenVerifier()` | Enterprise apps, Microsoft 365 | `openid`, `profile`, `email`, `offline_access` |
| **Google** | `AddGoogleTokenVerifier()` | Consumer apps, Google Workspace | `openid`, `profile`, `email`, `userinfo.profile` |
| **GitHub** | `AddGitHubTokenVerifier()` | Developer tools, repositories | `read:user`, `user:email` |
| **Auth0** | `AddAuth0TokenVerifier()` | Multi-tenant SaaS, custom identity | `openid`, `profile`, `email`, `offline_access` |
| **Okta** | `AddOktaTokenVerifier()` | Enterprise SSO, workforce identity | `openid`, `profile`, `email`, `offline_access` |
| **AWS Cognito** | `AddAwsCognitoTokenVerifier()` | AWS-native apps, user pools | `openid`, `profile`, `email` |

### Quick Setup Examples

Azure AD

```csharp
builder.AddAzureAdTokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_AZUREAD_TENANT_ID=your-tenant-id
FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_ID=your-client-id
FASTMCP_SERVER_AUTH_AZUREAD_CLIENT_SECRET=your-client-secret
```

**Example:** [`examples/Auth/AzureAdOAuth`](examples/Auth/AzureAdOAuth)

Google

```csharp
builder.AddGoogleTokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET=your-client-secret
```

**Example:** [`examples/Auth/GoogleOAuth`](examples/Auth/GoogleOAuth)

GitHub

```csharp
builder.AddGitHubTokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID=your-github-client-id
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET=your-github-client-secret
```

**Example:** [`examples/Auth/GitHubOAuth`](examples/Auth/GitHubOAuth)

### PowerShell Integration Test Suite

The project includes a comprehensive PowerShell-based integration test suite that validates a running server end-to-end.

1.  **Publish the server** (from the root of the `DotnetFastMCP` project):
    ```sh
    dotnet publish -c Release -o ..\publish examples\BasicServer
    ```

2.  **Run the tests**:
    Open a PowerShell terminal and run the launcher script from the project root:
    ```powershell
    .\LAUNCH_TESTS.ps1
    ```
This will open a new window, start the `BasicServer`, and run a series of tests covering all tools and resources, including error handling.

### Example Manual Test

Auth0

```csharp
builder.AddAuth0TokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_AUTH0_DOMAIN=your-tenant.auth0.com
FASTMCP_SERVER_AUTH_AUTH0_AUDIENCE=https://your-api-identifier
FASTMCP_SERVER_AUTH_AUTH0_CLIENT_ID=your-client-id
FASTMCP_SERVER_AUTH_AUTH0_CLIENT_SECRET=your-client-secret
```

**Example:** [`examples/Auth/Auth0OAuth`](examples/Auth/Auth0OAuth)

Okta

```csharp
builder.AddOktaTokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_OKTA_DOMAIN=dev-123456.okta.com
FASTMCP_SERVER_AUTH_OKTA_AUDIENCE=api://default
FASTMCP_SERVER_AUTH_OKTA_CLIENT_ID=your-client-id
FASTMCP_SERVER_AUTH_OKTA_CLIENT_SECRET=your-client-secret
```

**Example:** [`examples/Auth/OktaOAuth`](examples/Auth/OktaOAuth)

AWS Cognito

```csharp
builder.AddAwsCognitoTokenVerifier();
```

**Environment Variables:**
```bash
FASTMCP_SERVER_AUTH_AWSCOGNITO_USER_POOL_ID=us-east-1_XXXXXXXXX
FASTMCP_SERVER_AUTH_AWSCOGNITO_REGION=us-east-1
FASTMCP_SERVER_AUTH_AWSCOGNITO_CLIENT_ID=your-app-client-id
FASTMCP_SERVER_AUTH_AWSCOGNITO_CLIENT_SECRET=your-app-client-secret
FASTMCP_SERVER_AUTH_AWSCOGNITO_DOMAIN=myapp.auth.us-east-1.amazoncognito.com
```

**Example:** [`examples/Auth/AwsCognitoOAuth`](examples/Auth/AwsCognitoOAuth)

## 📚 Architecture

### Project Structure

```
DotnetFastMCP/
├── src/
│   └── FastMCP/
│       ├── Attributes/              # Component declaration attributes
│       ├── Authentication/          # 🔐 OAuth providers & token verification
│       │   ├── Providers/          # Azure AD, Google, GitHub, Auth0, Okta, AWS
│       │   ├── Proxy/              # OAuth Proxy for DCR
│       │   └── Verification/       # JWT token validation
│       ├── Hosting/                 # Server hosting and middleware
│       ├── Protocol/                # JSON-RPC protocol implementation
│       └── Server/                  # FastMCPServer core class
├── examples/
│   ├── BasicServer/                 # Simple MCP server
│   └── Auth/                        # 🔐 Authentication examples
│       ├── AzureAdOAuth/           # Azure AD example
│       ├── GoogleOAuth/            # Google OAuth example
│       ├── GitHubOAuth/            # GitHub OAuth example
│       ├── Auth0OAuth/             # Auth0 example
│       ├── OktaOAuth/              # Okta example
│       └── AwsCognitoOAuth/        # AWS Cognito example
└── tests/
    └── McpIntegrationTest/          # Integration tests
```

### Project Structure (Client)
The `FastMCP` framework now includes a complete client implementation in `src/FastMCP/Client`.

```mermaid
graph TD
    App[Your App] -->|Uses| Client[McpClient]
    Client -->|IClientTransport| Trans[Transport Layer]
    Trans -->|Stdio| Local[Local Process]
    Trans -->|SSE/HTTP| Remote[Remote Server]
```

### Authentication Flow

```mermaid
sequenceDiagram
    participant Client
    participant MCP Server
    participant OAuth Provider
    
    Client->>MCP Server: Request with Bearer Token
    MCP Server->>Token Verifier: Validate Token
    Token Verifier->>OAuth Provider: Fetch JWKS (if needed)
    OAuth Provider-->>Token Verifier: Public Keys
    Token Verifier-->>MCP Server: Validated Claims
    MCP Server-->>Client: Protected Resource
```

## 🔧 Creating an MCP Server

### Basic Server (No Authentication)

```csharp
using FastMCP.Hosting;
using FastMCP.Server;
using System.Reflection;

var mcpServer = new FastMCPServer(name: "My MCP Server");
var builder = McpServerBuilder.Create(mcpServer, args);

builder.WithComponentsFrom(Assembly.GetExecutingAssembly());

var app = builder.Build();
await app.RunAsync();
```

### Secure Server (With Authentication)

```csharp
using FastMCP.Hosting;
using FastMCP.Server;
using System.Reflection;

var mcpServer = new FastMCPServer(name: "My Secure MCP Server");
var builder = McpServerBuilder.Create(mcpServer, args);

// Add authentication - automatically configures OAuth Proxy
builder.AddAzureAdTokenVerifier();  // or any other provider

bu

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [tekspry](https://github.com/tekspry)
- **Source:** [tekspry/DotnetFastMCP](https://github.com/tekspry/DotnetFastMCP)
- **License:** MIT
- **Homepage:** https://medium.com/applied-ai-for-app-devs/dotnetfastmcp-the-fast-lane-for-building-ai-tools-in-net-efbf6218206b?sk=0ae77b467044dcd1bcd11a559c798048

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-tekspry-dotnetfastmcp
- Seller: https://agentstack.voostack.com/s/tekspry
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
