DotnetFastMCP 1.14.0
dotnet add package DotnetFastMCP --version 1.14.0
NuGet\Install-Package DotnetFastMCP -Version 1.14.0
<PackageReference Include="DotnetFastMCP" Version="1.14.0" />
<PackageVersion Include="DotnetFastMCP" Version="1.14.0" />
<PackageReference Include="DotnetFastMCP" />
paket add DotnetFastMCP --version 1.14.0
#r "nuget: DotnetFastMCP, 1.14.0"
#:package DotnetFastMCP@1.14.0
#addin nuget:?package=DotnetFastMCP&version=1.14.0
#tool nuget:?package=DotnetFastMCP&version=1.14.0
DotnetFastMCP - Enterprise-Grade Model Context Protocol Server Framework
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<T>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
ILLMProviderAPI for all providers - โ
Streaming Support - Real-time token streaming with
IAsyncEnumerable<string> - โ Production-Ready - HttpClientFactory, Polly retry policies, connection pooling
- โ
Plug-and-Play - Simple extension methods:
builder.AddAnthropicProvider()
๐ก Observability (NEW! 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
๐ Quick Start
Installation
git clone https://github.com/tekspry/.NetFastMCP.git
cd DotnetFastMCP
dotnet build -c Release
Create Your First MCP Server
1. Define Your Tools
Running the Example Server
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
using FastMCP.Attributes;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
public static class MyTools
{
/// <summary>
/// Public tool - no authentication required
/// </summary>
[McpTool]
public static int Add(int a, int b) => a + b;
public static class Resources
{
/// <summary>
/// Protected tool - requires authentication
/// </summary>
[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
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
# 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"
# 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
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):
dotnet run -- --stdio
Create an MCP Client
Connect to any MCP server using the C# Client Library:
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<int>("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 |
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
<details> <summary><b>Azure AD</b></summary>
builder.AddAzureAdTokenVerifier();
Environment Variables:
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
</details>
<details> <summary><b>Google</b></summary>
builder.AddGoogleTokenVerifier();
Environment Variables:
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
</details>
<details> <summary><b>GitHub</b></summary>
Run Unit & Integration Tests
builder.AddGitHubTokenVerifier();
Environment Variables:
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID=your-github-client-id
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET=your-github-client-secret
Example: examples/Auth/GitHubOAuth
</details>
PowerShell Integration Test Suite
The project includes a comprehensive PowerShell-based integration test suite that validates a running server end-to-end.
Publish the server (from the root of the
DotnetFastMCPproject):dotnet publish -c Release -o ..\publish examples\BasicServerRun the tests: Open a PowerShell terminal and run the launcher script from the project root:
.\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
<details> <summary><b>Auth0</b></summary>
builder.AddAuth0TokenVerifier();
Environment Variables:
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
</details>
<details> <summary><b>Okta</b></summary>
builder.AddOktaTokenVerifier();
Environment Variables:
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
</details>
<details> <summary><b>AWS Cognito</b></summary>
builder.AddAwsCognitoTokenVerifier();
Environment Variables:
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
</details>
๐ 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.
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
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)
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)
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
builder.WithComponentsFrom(Assembly.GetExecutingAssembly());
Returns server metadata. The example server returns:
var app = builder.Build();
app.Urls.Add("http://localhost:5002");
await app.RunAsync();
Protected Tools
using FastMCP.Attributes;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
public static class SecureTools
{
/// <summary>
/// Public tool - anyone can call
/// </summary>
[McpTool]
public static string Echo(string message) => message;
/// <summary>
/// Protected tool - requires valid OAuth token
/// </summary>
[McpTool]
[Authorize]
public static object GetUserInfo(ClaimsPrincipal user)
{
return new
{
Name = user.Identity?.Name ?? "Unknown",
Email = user.FindFirst("email")?.Value ?? "Not available",
IsAuthenticated = user.Identity?.IsAuthenticated ?? false,
Claims = user.Claims.Select(c => new { c.Type, c.Value }).ToList()
};
}
/// <summary>
/// Role-based authorization
/// </summary>
[McpTool]
[Authorize(Roles = "Admin")]
public static string AdminOnly() => "Admin access granted";
}
๐ก JSON-RPC Protocol
Prompts
Prompts allow servers to provide templates that LLMs can use.
using FastMCP.Attributes;
using FastMCP.Protocol;
public static class MyPrompts
{
[McpPrompt("analyze_code")]
public static GetPromptResult Analyze(string code)
{
return new GetPromptResult
{
Description = "Analyze the given code",
Messages = new List<PromptMessage>
{
new PromptMessage
{
Role = "user",
Content = new { type = "text", text = $"Please analyze this code:\n{code}" }
}
}
};
}
}
Calling Tools
Public Tool (No Auth):
POST /mcp
{
"jsonrpc": "2.0",
"method": "Echo",
"params": ["Hello World"],
"id": 1
}
Protected Tool (With Auth):
POST /mcp
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...
{
"jsonrpc": "2.0",
"method": "GetUserInfo",
"params": [],
"id": 2
}
๐งช Testing
Run All Tests
dotnet test
Test Authentication Flow
Each authentication example includes a comprehensive .rest file for testing:
# Open in VS Code with REST Client extension
code examples/Auth/AzureAdOAuth/azure-ad-auth-tests.rest
Test files include:
- โ Discovery endpoints
- โ Public tool tests
- โ Protected tool tests (should fail without auth)
- โ OAuth authorization flow
- โ Token exchange
- โ Provider-specific API calls
๐ Documentation
Complete Authentication Guide
See mcp-authentication-guide.md for:
- Detailed provider setup instructions
- OAuth flow walkthrough
- Troubleshooting guide
- Best practices
- Production deployment checklist
Example Projects
| Example | Description | Port |
|---|---|---|
| BasicServer | Simple MCP server without authentication | 5000 |
| TelemetryDemo | ๐ก OpenTelemetry metrics & tracing demo | 5000 |
| AzureAdOAuth | Azure AD authentication example | 5002 |
| GoogleOAuth | Google OAuth example | 5000 |
| GitHubOAuth | GitHub OAuth example | 5001 |
| Auth0OAuth | Auth0 authentication example | 5005 |
| OktaOAuth | Okta authentication example | 5007 |
| AwsCognitoOAuth | AWS Cognito example | 5006 |
๐๏ธ Advanced Features
๐ก Observability โ OpenTelemetry (NEW! v1.14.0)
FastMCP ships with built-in OpenTelemetry instrumentation. Enable with one line and connect to any backend.
using FastMCP.Telemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
// 1. Enable FastMCP telemetry (one line)
builder.WithTelemetry(t =>
{
t.ServiceName = "my-mcp-server";
t.EnableMetrics = true;
t.EnableTracing = true;
});
// 2. Configure your exporter of choice
builder.Services.AddOpenTelemetry()
.WithMetrics(m =>
{
m.AddMcpInstrumentation(); // FastMCP extension method
m.AddPrometheusExporter(); // or AddConsoleExporter(), AddOtlpExporter()
})
.WithTracing(t =>
{
t.AddMcpInstrumentation(); // FastMCP extension method
t.AddOtlpExporter(); // or AddJaeger(), AddZipkin()
});
Metrics automatically tracked:
| Metric | Type | Tag | Description |
|---|---|---|---|
mcp.tool.invocations |
Counter | tool.name |
Total tool calls |
mcp.tool.duration |
Histogram (ms) | tool.name |
Tool execution time |
mcp.tool.errors |
Counter | tool.name |
Failed tool calls |
mcp.prompt.requests |
Counter | โ | Prompt template requests |
mcp.resource.reads |
Counter | โ | Resource read requests |
Validate with dotnet-counters (no exporter needed):
dotnet-counters monitor -n YourAppName --counters FastMCP
See Observability Guide for full documentation, including production exporter setup, distributed tracing details, and real request/response validation examples.
Middleware Interception
Middleware allows you to intercept and modify JSON-RPC messages (requests and responses) flowing through the server pipeline. This is useful for logging, validation, modification, or custom monitoring.
- Define Middleware: Implement
IMcpMiddleware. - Register Middleware: Use
builder.AddMcpMiddleware<T>().
public class LoggingMiddleware : IMcpMiddleware
{
public async Task<JsonRpcResponse> InvokeAsync(McpMiddlewareContext context, McpMiddlewareDelegate next, CancellationToken ct)
{
Console.Error.WriteLine($"[LOG] Incoming: {context.Request.Method}");
// Pass to next handler
var response = await next(context, ct);
Console.Error.WriteLine($"[LOG] Completed. Error: {response.Error != null}");
return response;
}
}
// In Program.cs:
builder.AddMcpMiddleware<LoggingMiddleware>();
Server Composition (NEW!)
Mount other MCP servers into your main server instantiation. This supports a "Micro-MCP" architecture where you can compose a robust agent from smaller, focused modules.
// 1. Create Sub-Server (e.g. GitHub Tools)
var githubServer = new FastMCPServer("GitHub");
// ... register tools ...
// 2. Import into Main Server with "gh" prefix
builder.AddServer(githubServer, prefix: "gh");
// Result:
// The client sees tools named: "gh_create_issue", "gh_get_repo", etc.
MFA Support (NEW!)
Enforce Multi-Factor Authentication for sensitive tools.
[McpTool("transfer_funds")]
[AuthorizeMcpTool(RequireMfa = true)]
public static string TransferFunds()
{
return "Transferred!";
}
- MFA Check: Verifies
amrclaim containsmfa. - Security: Provides granular protection for critical operations.
Storage Abstraction (NEW!)
FastMCP now includes a built-in state persistence layer. Tools can request McpContext to access IMcpStorage.
[McpTool]
public static async Task<string> SetValue(string key, string value, McpContext context)
{
await context.Storage.SetAsync(key, value);
return "Saved!";
}
The default implementation is In-Memory, but you can swap it for Redis, SQL, or File storage:
builder.AddMcpStorage<MyRedisStorage>();
LLM Integration (NEW!)
FastMCP includes a powerful LLM integration system with 8 providers supporting the latest models (Feb 2026).
Quick Setup
using FastMCP.AI;
// Option 1: Local (Ollama)
builder.AddOllamaProvider(options =>
{
options.BaseUrl = "http://localhost:11434";
options.DefaultModel = "llama3.1:8b";
});
// Option 2: Cloud (Anthropic Claude Opus 4.6 - Latest)
builder.AddAnthropicProvider(options =>
{
options.ApiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")!;
options.DefaultModel = "claude-opus-4.6"; // 1M context, Feb 2026
});
// Option 3: Google Gemini 3
builder.AddGeminiProvider(options =>
{
options.ApiKey = Environment.GetEnvironmentVariable("GEMINI_API_KEY")!;
options.DefaultModel = "gemini-3-flash"; // Fast, cost-effective
});
Use in Tools
public class AITools
{
private readonly ILLMProvider _llm;
public AITools(ILLMProvider llm) => _llm = llm;
[McpTool("generate_story")]
public async Task<string> GenerateStory(string topic)
{
return await _llm.GenerateAsync(
$"Write a story about {topic}",
new LLMGenerationOptions
{
SystemPrompt = "You are a creative storyteller.",
Temperature = 0.8,
MaxTokens = 500
});
}
[McpTool("stream_response")]
public async IAsyncEnumerable<string> StreamResponse(string prompt)
{
await foreach (var token in _llm.StreamAsync(prompt))
{
yield return token;
}
}
}
Supported Providers (Feb 2026)
| Provider | Extension Method | Latest Model | Best For |
|---|---|---|---|
| Ollama | AddOllamaProvider() |
llama3.1:8b |
Local, privacy, offline |
| OpenAI | AddOpenAIProvider() |
gpt-4-turbo |
Production, function calling |
| Azure OpenAI | AddAzureOpenAIProvider() |
gpt-4 |
Enterprise, compliance |
| Anthropic | AddAnthropicProvider() |
claude-opus-4.6 |
Deep reasoning, 1M context |
| Google Gemini | AddGeminiProvider() |
gemini-3-flash |
Multimodal, high-volume |
| Cohere | AddCohereProvider() |
command-a |
Enterprise RAG, agents |
| Hugging Face | AddHuggingFaceProvider() |
Any model | Open-source, flexibility |
| Deepseek | AddDeepseekProvider() |
deepseek-v3.2 |
Cost-effective, reasoning |
See LLM Integration Guide for complete documentation.
Background Tasks (NEW!)
FastMCP allows tools to fire-and-forget long running operations using RunInBackground.
[McpTool]
public static async Task<string> ProcessFile(string file, McpContext context)
{
await context.RunInBackground(async (ct) =>
{
// This runs without blocking the client
await HeavyProcessing(file, ct);
});
return "Processing started!";
}
Icons Support (NEW!)
Enhance the user interface of clients by providing icons for your server and tools.
// Server Icon
server.Icon = "https://myserver.com/logo.png";
// Tool Icon
[McpTool(Icon = "https://myserver.com/tools/calc.png")]
public static int Add(int a, int b) => a + b;
Binary Content Support (NEW!)
Return rich content like Images from your tools and prompts.
[McpTool]
public static CallToolResult GetSnapshot()
{
return new CallToolResult
{
Content = new List<ContentItem>
{
new ImageContent { Data = "base64...", MimeType = "image/png" }
}
};
}
OAuth Proxy
DotnetFastMCP includes a built-in OAuth Proxy that provides:
- โ Dynamic Client Registration (DCR) - Automatic client registration for MCP clients
- โ Authorization Code Flow - Full OAuth 2.0 authorization code flow with PKCE
- โ Token Management - Automatic token exchange, refresh, and revocation
- โ Discovery Endpoints - RFC 8414 compliant OAuth discovery
Automatically Available Endpoints:
/.well-known/oauth-authorization-server- OAuth server metadata/oauth/authorize- Authorization endpoint/oauth/token- Token endpoint/oauth/register- Dynamic client registration/oauth/userinfo- User information endpoint
Custom Scopes
Override default scopes for any provider:
builder.AddAzureAdTokenVerifier(new AzureAdAuthOptions
{
RequiredScopes = new[] { "openid", "profile", "email", "User.Read", "Calendars.Read" }
});
Multiple Authentication Schemes
// Support multiple providers simultaneously
builder.AddAzureAdTokenVerifier();
builder.AddGoogleTokenVerifier();
builder.AddGitHubTokenVerifier();
๐ Security Best Practices
Development
- โ Use environment variables for secrets
- โ Never commit credentials to source control
- โ
Use
.envfiles for local development - โ Test with short-lived tokens
Production
- โ Use HTTPS for all communication
- โ Store secrets in Azure Key Vault / AWS Secrets Manager
- โ Enable MFA for OAuth providers
- โ Implement rate limiting
- โ Monitor authentication logs
- โ Use separate app registrations per environment
- โ Validate token scopes match required permissions
๐ฆ NuGet Package
Install from NuGet (when published):
dotnet add package DotnetFastMCP
๐ค Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Resources
Official Documentation
- Model Context Protocol Specification
- JSON-RPC 2.0 Specification
- OAuth 2.0 RFC 6749
- OpenID Connect Core 1.0
Framework Documentation
- Observability Guide ๐ v1.14.0
- LLM Integration Guide
- Protocol Discovery Guide
- Client Library Guide
- Context & Interaction Guide
- Middleware Interception Guide
- SSE Transport Guide
- Stdio Transport Guide
- ASP.NET Core Documentation
- .NET 8.0 Documentation
Provider Documentation
๐ Issues & Support
For bug reports and feature requests, please use GitHub Issues.
โจ What's New
v1.14.0 - OpenTelemetry Observability (Latest - Mar 2026)
- ๐ก OpenTelemetry Integration - First-class metrics and distributed tracing built in
- ๐ 5 Auto-Tracked Metrics - Tool invocations, duration, errors, prompt requests, resource reads
- โจ One-Line Setup -
builder.WithTelemetry()with zero boilerplate - ๐ Exporter Agnostic - Works with Prometheus, App Insights, Grafana, Jaeger, any OTLP backend
- ๐ Distributed Tracing - Full span support with OTel semantic convention tags
- ๐ก๏ธ PII Safe Defaults - Tool inputs never logged unless explicitly enabled
- ๐ฏ Zero Overhead - Fully opt-in, no cost when not used
- ๐ Comprehensive Docs - Full guide with validation examples and production checklist
v1.13.0 - LLM Integration (Feb 2026)
- ๐ค 8 LLM Providers - Ollama, OpenAI, Azure OpenAI, Anthropic Claude, Google Gemini, Cohere, Hugging Face, Deepseek
- โจ Latest Models - Claude Opus 4.6 (1M context), Gemini 3 Pro/Flash, Command A, DeepSeek V3.2
- ๐ Unified Interface - Single
ILLMProviderAPI for all providers - ๐ก Streaming Support - Real-time token streaming with
IAsyncEnumerable<string> - ๐๏ธ Production-Ready - HttpClientFactory, Polly retry policies, connection pooling
- ๐ฏ Plug-and-Play - Simple registration:
builder.AddAnthropicProvider() - ๐ Comprehensive Docs - Complete integration guide with examples
v1.12.0 - MFA Support
- ๐ก๏ธ MFA Enforcement - Require
mfaAMR claim for sensitive tools - โ
Granular Control - Enable per-tool using
[AuthorizeMcpTool(RequireMfa=true)] - ๐ Enhanced Security - Standards-based multi-factor authentication check
v1.11.0 - Binary Content Support (Latest)
- โ Polymorphic Content - Support for mixed Text and Image responses
- โ Image Support - Return Base64 encoded images from tools
- โ Multimodal Prompts - Embbed images in prompts for LLM context
v1.10.0 - Icons Support
- โ Server Icons - Define a brand icon for your MCP server
- โ Tool/Resource Icons - Visually distinguish capabilities
- โ UI/UX Enhancement - Enable richer client experiences
v1.9.0 - Background Tasks
- โ Fire-and-Forget - Offload long-running operations from tools
- โ Non-Blocking - Return immediate responses to clients
- โ Hosted Service - Built-in queuing mechanism using Channels
v1.8.0 - Storage Abstractions
- โ
State Persistence - Tools can now persist data via
McpContext.Storage - โ Pluggable Backends - Swap in Redis/SQL/File storage easily
- โ In-Memory Default - Zero-config built-in storage for development
v1.7.0 - Server Composition
- โ Server Composition - Mount other MCP servers as modules (Micro-MCPs)
- โ
Namespacing - Automatically prefix imported tools (e.g.,
github_createIssue) - โ Zero-Overhead - High-performance internal dictionary routing (O(1))
v1.6.0 - Middleware Interception
- โ Middleware Pipeline - Intercept and modify requests/responses
- โ Critical Fixes - Resolved Stdio transport initialization deadlocks
- โ
Builder API - Easy registration with
AddMcpMiddleware<T>
v1.5.0 - Native Client Library
- โ McpClient - Type-safe .NET client for consuming MCP servers
- โ Transport Agnostic - Support for both Stdio and SSE connections
- โ Notification Handling - Events for real-time logs and progress
v1.4.0 - Server-Sent Events (SSE)
- โ SSE Transport - Real-time server-to-client streaming transport
- โ Async Notifications - Push logs and progress updates to HTTP clients
v1.3.0 - Context & Interaction
- โ
Context System -
McpContextinjection for logging and progress - โ IMcpSession - Transport-agnostic interaction abstraction
v1.2.0 - Protocol Discovery
- โ Dynamic Discovery - Auto-discovery of Tools, Resources, and Prompts
- โ Prompts/List - Full support for prompt templates
v1.1.0 - Stdio Transport & Authentication
- โ Stdio Transport - Initial support for stdio communication
- ๐ 6 OAuth Providers - Azure AD, Google, GitHub, Auth0, Okta, AWS Cognito
- ๐ OAuth Proxy - Built-in DCR support
v1.0.0 - Core Framework
- โ Attribute-based API
- โ JSON-RPC 2.0 compliance
- โ ASP.NET Core integration
Made with โค๏ธ by the DotnetFastMCP team
โญ Star this repo if you find it useful!
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- AspNet.Security.OAuth.GitHub (>= 8.0.0)
- Microsoft.AspNetCore.Authentication.Google (>= 8.0.0)
- Microsoft.AspNetCore.Authentication.OpenIdConnect (>= 8.0.0)
- Microsoft.Extensions.Configuration.Binder (>= 8.0.0)
- Microsoft.Extensions.Http.Polly (>= 8.0.0)
- Microsoft.Identity.Web (>= 2.15.2)
- Microsoft.IdentityModel.Protocols.OpenIdConnect (>= 8.0.0)
- OpenTelemetry (>= 1.9.0)
- System.IdentityModel.Tokens.Jwt (>= 8.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.14.0 | 96 | 3/4/2026 |
| 1.13.0 | 101 | 2/17/2026 |
| 1.12.0 | 98 | 1/24/2026 |
| 1.11.0 | 100 | 1/23/2026 |
| 1.10.0 | 91 | 1/23/2026 |
| 1.9.0 | 100 | 1/18/2026 |
| 1.8.0 | 90 | 1/17/2026 |
| 1.7.0 | 98 | 1/17/2026 |
| 1.6.0 | 95 | 1/17/2026 |
| 1.5.0 | 96 | 1/17/2026 |
| 1.4.0 | 97 | 1/16/2026 |
| 1.3.0 | 99 | 1/11/2026 |
| 1.2.0 | 98 | 1/11/2026 |
| 1.1.0 | 95 | 1/10/2026 |
| 1.0.0 | 104 | 12/31/2025 |