Token导航 LogoToken导航TokenDH.com
Net Fast MCP logo
AI代理未说明官方级别未说明来源级核验

Net Fast MCP

MCP Server

DotnetFastMCP是一个用于构建安全、可扩展且可观测的企业级模型上下文协议(MCP)服务器的现代C#/.NET框架,支持JSON-RPC 2.0协议和多种OAuth 2.0/OpenID Connect认证提供程序。

工具数

0

提示词数

0

GitHub Stars

4

资源数

0
C#ClaudeAI代理ClaudeVS Code

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

tekspry

提供方

tekspry

最后核验

2026/5/17 20:23

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

DotnetFastMCP-企业级模型上下文协议服务器框架

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

一个现代化的、可用于生产的C#/。NET框架,用于构建具有企业级身份验证的安全、可扩展和可观察的模型上下文协议(MCP)服务器。

🎯 概述

DotnetFastMCP提供了一种干净的、基于属性的方法来构建实现JSON-RPC 2.0协议的MCP服务器。它包括a 本地人。NET客户端库 客户端用于消费MCP服务器,使其成为构建模型上下文协议双方的完整解决方案。基于ASP构建。NET Core,它利用了现代。NET的高性能、可靠性和 全面的OAuth 2.0/OpenID连接身份验证 开箱即用。

⭐ 主要特点

核心框架

  • 基于简单属性的API -使用声明工具和资源 [McpTool][McpResource] 属性
  • 一流的提示支持 -使用定义提示 [McpPrompt] 用于LLM交互模板
  • 自动部件发现 -基于反射的组件扫描
  • 符合JSON-RPC 2.0标准 -完全遵守协议,并进行适当的错误处理
  • 灵活的参数绑定 -同时支持数组和命名参数
  • 基于ASP构建。NET核心 -利用强大的ASP。NET核心托管模型
  • 生产就绪 -全面的错误处理和记录
  • 类型安全 -完全C#类型的系统集成

🔐 企业身份验证

  • 支持6个OAuth提供程序 -Azure AD、谷歌、GitHub、Auth0、Okta、AWS Cognito
  • 内置OAuth代理 -非DCR提供商的自动动态客户端注册(DCR)
  • JWT令牌验证 -使用JWKS缓存进行自动令牌验证
  • 零配置 -设置环境变量并开始
  • 合理违约 -常见用例的预配置范围
  • 细粒度授权 -保护工具 [Authorize] 属性
  • 基于索赔的访问 -从经过身份验证的请求中访问用户信息
  • MFA支持 -对敏感工具实施多因素身份验证

🔌 本地客户端库

  • McpClient -类型安全。NET客户端,用于使用任何MCP服务器
  • 运输不可知 -支持Stdio和SSE连接
  • 通知处理 -实时日志和进度事件
  • 工具调用 -清洁 CallToolAsync API

🤖 LLM集成

  • 8 LLM提供商 -Ollama、OpenAI、Azure OpenAI、拟人克劳德、谷歌双子座、科恩、拥抱脸、Deepseek
  • 最新型号(2026年2月) -Claude Opus 4.6,双子座3 Pro/Flash,命令A,DeepSeek V3.2
  • 统一接口 -单身 ILLMProvider API适用于所有提供商
  • 流媒体支持 -实时令牌流 IAsyncEnumerable
  • 生产就绪 -HttpClientFactory、Polly重试策略、连接池
  • 即插即用 -简单的扩展方法: builder.AddAnthropicProvider()

📡 可观察性(v1.14.0)

  • 开放遥测集成 -一流的指标和分布式跟踪
  • 5个自动跟踪指标 -工具调用、持续时间、错误、提示请求、资源读取
  • 单线设置 - builder.WithTelemetry() --零样板
  • 出口商不可知 -插入Prometheus、Application Insights、Grafana、Jaeger或任何OTLP后端
  • OTel语义约定 -标准标记名称、异常事件、跨度状态
  • 禁用时无开销 -完全选择加入,未使用时无性能成本
  • 标准+HTTP -度量在两种传输方式中都有效

🏥 健康检查和诊断(新!v1.15.0)

  • 内置健康端点 - GET /mcp/health 自动曝光
  • 单线设置 - builder.WithHealthChecks() --无需配置
  • 插件自定义检查 -将任何检查添加为简单的lambda(不需要接口)
  • 并行执行 -所有检查都与每次检查超时同时运行
  • 标准HTTP状态代码 -200健康/207降级/503不健康
  • Kubernetes和Docker就绪 -插入活性/准备状态探针
  • 自动服务器诊断 -包括工具数量、正常运行时间、框架版本
  • 禁用时无开销 -完全选择加入,除非配置,否则不会注册端点

🚀 快速开始

安装

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

创建您的第一个MCP服务器

1.定义你的工具

创建一个静态类 [McpTool]-装饰静态方法:

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.创建程序.cs

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);

运行示例服务器

cd examples/BasicServer
dotnet run

服务器将于启动 http://localhost:5000.

📚 建筑

核心组件

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

项目结构

项目目的
FastMCP核心框架库
FastMCP.CLI命令行界面工具
BasicServerMCP服务器实现示例
McpIntegrationTest集成测试
ClientDemo使用BasicServer的客户端示例

🔧 创建MCP服务器

1.定义组件

为了更好地组织,将组件拆分为多个文件(例如。, Tools.cs, Resources.cs).框架将自动发现它们。

文件: Tools.cs

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.配置具有身份验证的服务器

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.设置环境变量

# 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.运行和测试

dotnet run

您的服务器现在正在运行 OAuth代理 端点:

  • MCP端点: http://localhost:5002/mcp
  • OAuth授权: http://localhost:5002/oauth/authorize
  • OAuth令牌: http://localhost:5002/oauth/token
  • 发现: http://localhost:5002/.well-known/oauth-authorization-server

标准模式

您还可以在Stdio模式下运行服务器(适用于本地LLM客户端):

dotnet run -- --stdio

创建MCP客户端

使用C#客户端库连接到任何MCP服务器:

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 });

🔐 身份验证提供者

DotnetFastMCP支持 6家企业级OAuth提供商 开箱即用:

提供者方法用例默认作用域
Azure ADAddAzureAdTokenVerifier()企业应用程序,微软365openid, profile, email, offline_access
谷歌AddGoogleTokenVerifier()消费者应用程序、谷歌工作区openid, profile, email, userinfo.profile
GitHubAddGitHubTokenVerifier()开发人员工具、存储库read:user, user:email
身份验证0AddAuth0TokenVerifier()多租户SaaS,自定义身份openid, profile, email, offline_access
八月AddOktaTokenVerifier()企业SSO、员工身份openid, profile, email, offline_access
AWS CognitoAddAwsCognitoTokenVerifier()AWS原生应用程序、用户池openid, profile, email

快速设置示例

Azure AD

builder.AddAzureAdTokenVerifier();

环境变量:

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

例子: examples/Auth/AzureAdOAuth

Google

builder.AddGoogleTokenVerifier();

环境变量:

FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID=your-client-id.apps.googleusercontent.com
FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET=your-client-secret

例子: examples/Auth/GoogleOAuth

GitHub

builder.AddGitHubTokenVerifier();

环境变量:

FASTMCP_SERVER_AUTH_GITHUB_CLIENT_ID=your-github-client-id
FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRET=your-github-client-secret

例子:

PowerShell Integration Test Suite

该项目包括一个全面的基于PowerShell的集成测试套件,用于端到端验证正在运行的服务器。

  1. 发布服务器 (从根 DotnetFastMCP 项目):
   dotnet publish -c Release -o ..\publish examples\BasicServer
  1. 运行测试:

打开PowerShell终端并从项目根运行启动器脚本:

   .\LAUNCH_TESTS.ps1

这将打开一个新窗口,启动 BasicServer,并运行一系列涵盖所有工具和资源的测试,包括错误处理。

手动测试示例

Auth0

builder.AddAuth0TokenVerifier();

环境变量:

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

例子: examples/Auth/Auth0OAuth

Okta

builder.AddOktaTokenVerifier();

环境变量:

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

例子: examples/Auth/OktaOAuth

AWS Cognito

builder.AddAwsCognitoTokenVerifier();

环境变量:

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

例子: examples/Auth/AwsCognitoOAuth

📚 建筑

项目结构

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

项目结构(客户)

FastMCP 框架现在包括一个完整的客户端实现 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]

身份验证流程

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

🔧 创建MCP服务器

基本服务器(无身份验证)

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();

安全服务器(带身份验证)

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());

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

受保护的工具

using FastMCP.Attributes;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

public static class SecureTools
{
    /// 
    /// Public tool - anyone can call
    /// 
    [McpTool]
    public static string Echo(string message) => message;

    /// 
    /// Protected tool - requires valid OAuth token
    /// 
    [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()
        };
    }

    /// 
    /// Role-based authorization
    /// 
    [McpTool]
    [Authorize(Roles = "Admin")]
    public static string AdminOnly() => "Admin access granted";
}

📡 JSON-RPC协议

提示

提示允许服务器提供LLM可以使用的模板。

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

            {
                new PromptMessage 
                { 
                    Role = "user", 
                    Content = new { type = "text", text = $"Please analyze this code:\n{code}" } 
                }
            }
        };
    }
}

调用工具

公共工具(无身份验证):

POST /mcp
{
  "jsonrpc": "2.0",
  "method": "Echo",
  "params": ["Hello World"],
  "id": 1
}

受保护的工具(带身份验证):

POST /mcp
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGc...

{
  "jsonrpc": "2.0",
  "method": "GetUserInfo",
  "params": [],
  "id": 2
}

🧪 测试

运行所有测试

dotnet test

测试身份验证流程

每个身份验证示例都包括一个全面的 .rest 测试文件:

# Open in VS Code with REST Client extension
code examples/Auth/AzureAdOAuth/azure-ad-auth-tests.rest

测试文件包括:

  • ✅ 发现端点
  • ✅ 公共工具测试
  • ✅ 受保护的工具测试(未经身份验证应失败)
  • ✅ OAuth授权流程
  • ✅ 代币兑换
  • ✅ 特定于提供程序的API调用

📖 文档

完整的身份验证指南

MFA支持指南 用于在敏感工具上强制执行多因素身份验证,以及下的单个提供者README文件 examples/Auth/ 了解详细的OAuth设置说明。

示例项目

示例描述端口
基本服务器无身份验证的简单MCP服务器5000
HealthChecksDemo🏥 健康监测和诊断演示5000
遥测演示📡 OpenTetry指标和跟踪演示5000
AzureAdOAuthAzure AD身份验证示例5002
谷歌OAuth谷歌OAuth示例5000
GitHub OAuth示例5001
Auth0AuthoAuth0身份验证示例5005
OktaOAuthOkta身份验证示例5007
AwsCognitoOAuthAWS Cognito示例5006

🏗️ 高级功能

🏥 健康检查和诊断(新!v1.15.0)

FastMCP附带了一个内置的生产健康检查端点。只需一行即可启用,并将任何自定义检查作为简单的lambda插入。

using FastMCP.Health;

// Zero-config — exposes GET /mcp/health automatically
builder.WithHealthChecks();

// With custom checks (database, LLM provider, memory, etc.)
builder.WithHealthChecks(checks =>
{
    checks.AddCheck("memory", () =>
        GC.GetTotalMemory(false) 
        await dbContext.Database.CanConnectAsync(ct));

    checks.AddAsyncCheck("llm_provider", async ct =>
        await llmProvider.IsHealthyAsync(ct));
});

响应JSON(HTTP 200--正常):

{
  "status": "Healthy",
  "timestamp": "2026-04-19T20:00:00Z",
  "checks": [
    { "name": "mcp_server",   "status": "Healthy", "durationMs": 0 },
    { "name": "memory",       "status": "Healthy", "durationMs": 0.1 },
    { "name": "database",     "status": "Healthy", "durationMs": 4.9 },
    { "name": "llm_provider", "status": "Healthy", "durationMs": 22.3 }
  ],
  "diagnostics": {
    "serverName": "my-mcp-server",
    "frameworkVersion": "1.15.0.0",
    "toolCount": 12,
    "uptimeSeconds": 3721.4
  }
}

HTTP状态码映射:

状态HTTP代码含义
Healthy200所有检查均已通过
Degraded207服务器已启动,≥1次检查超时
Unhealthy503≥1次检查失败或被丢弃

Kubernetes活性/就绪性探测:

livenessProbe:
  httpGet:
    path: /mcp/health
    port: 5000
  initialDelaySeconds: 15
  periodSeconds: 30
readinessProbe:
  httpGet:
    path: /mcp/health
    port: 5000
  periodSeconds: 10

健康检查指南 获取完整文档,包括Docker Compose、Azure容器应用程序、每次检查超时配置、单元测试模式和完整的验证示例。

______________________________________________________________________

📡 可观测性——开放遥测(v1.14.0)

FastMCP附带内置的OpenTetry仪器。只需一行即可启用并连接到任何后端。

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()
    });

自动跟踪的指标:

度量类型标签描述
mcp.tool.invocations柜台tool.name工具调用总数
mcp.tool.duration直方图(ms)tool.name工具执行时间
mcp.tool.errors柜台tool.name工具调用失败
mcp.prompt.requests计数器--提示模板请求
mcp.resource.reads计数器--资源读取请求

使用.NET计数器进行验证(无需导出器):

dotnet-counters monitor -n YourAppName --counters FastMCP

观察性指南 获取完整文档,包括生产导出器设置、分布式跟踪细节和真实的请求/响应验证示例。

______________________________________________________________________

中间件拦截

中间件允许您拦截和修改流经服务器管道的JSON-RPC消息(请求和响应)。这对于日志记录、验证、修改或自定义监控非常有用。

  1. 定义中间件: 实施 IMcpMiddleware.
  2. 注册中间件: 使用 builder.AddMcpMiddleware().
public class LoggingMiddleware : IMcpMiddleware
{
    public async Task 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();

服务器组合(新增!)

将其他MCP服务器安装到主服务器实例化中。这支持“Micro-MCP”架构,在该架构中,您可以从较小的、专注的模块中组成一个强大的代理。

// 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支持(新增!)

对敏感工具实施多重身份验证。

[McpTool("transfer_funds")]
[AuthorizeMcpTool(RequireMfa = true)]
public static string TransferFunds()
{
    return "Transferred!";
}
  • MFA检查:验证 amr 索赔包含 mfa.
  • 安全:为关键操作提供精细保护。

存储抽象(新增!)

FastMCP现在包括一个内置的状态持久层。工具可以请求 McpContext 访问 IMcpStorage.

[McpTool]
public static async Task SetValue(string key, string value, McpContext context)
{
    await context.Storage.SetAsync(key, value);
    return "Saved!";
}

默认实现为 内存中,但您可以将其替换为Redis、SQL或文件存储:

builder.AddMcpStorage();

LLM集成(新!)

FastMCP包括一个强大的LLM集成系统 8供应商 支持最新型号(2026年2月)。

快速设置

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
});

在工具中使用

public class AITools
{
    private readonly ILLMProvider _llm;

    public AITools(ILLMProvider llm) => _llm = llm;

    [McpTool("generate_story")]
    public async Task 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 StreamResponse(string prompt)
    {
        await foreach (var token in _llm.StreamAsync(prompt))
        {
            yield return token;
        }
    }
}

支持的提供商(2026年2月)

提供者扩展方法最新型号最适合
奥拉玛AddOllamaProvider()llama3.1:8b本地、隐私、离线
开放人工智能AddOpenAIProvider()gpt-4-turbo生产、功能调用
Azure OpenAIAddAzureOpenAIProvider()gpt-4企业、合规
AnthropicAddAnthropicProvider()claude-opus-4.6深度推理,1M上下文
谷歌双子座AddGeminiProvider()gemini-3-flash多模式、大批量
凝聚AddCohereProvider()command-a企业RAG、代理商
拥抱脸AddHuggingFaceProvider()任何型号开源,灵活
深度求索AddDeepseekProvider()deepseek-v3.2成本效益高,推理能力强

LLM集成指南 以获取完整的文档。

后台任务(新增!)

FastMCP允许工具使用 RunInBackground.

[McpTool]
public static async Task ProcessFile(string file, McpContext context)
{
    await context.RunInBackground(async (ct) => 
    {
        // This runs without blocking the client
        await HeavyProcessing(file, ct);
    });

    return "Processing started!";
}

图标支持(新增!)

通过为服务器和工具提供图标来增强客户端的用户界面。

// 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;

二进制内容支持(新增!)

从工具和提示中返回丰富的内容,如图像。

[McpTool]
public static CallToolResult GetSnapshot()
{
    return new CallToolResult 
    {
        Content = new List 
        {
            new ImageContent { Data = "base64...", MimeType = "image/png" }
        }
    };
}

OAuth代理

DotnetFastMCP包括一个内置 OAuth代理 它提供:

  • 动态客户端注册(DCR) -MCP客户端的自动客户端注册
  • 授权码流 -使用PKCE的完整OAuth 2.0授权代码流
  • 许可证管理 -自动令牌交换、刷新和撤销
  • 发现端点 -符合RFC 8414的OAuth发现

自动可用端点:

  • /.well-known/oauth-authorization-server -OAuth服务器元数据
  • /oauth/authorize -授权端点
  • /oauth/token -令牌端点
  • /oauth/register -动态客户端注册
  • /oauth/userinfo -用户信息端点

自定义范围

覆盖任何提供程序的默认范围:

builder.AddAzureAdTokenVerifier(new AzureAdAuthOptions
{
    RequiredScopes = new[] { "openid", "profile", "email", "User.Read", "Calendars.Read" }
});

多种身份验证方案

// Support multiple providers simultaneously
builder.AddAzureAdTokenVerifier();
builder.AddGoogleTokenVerifier();
builder.AddGitHubTokenVerifier();

🔐 安全最佳实践

发展

  • ✅ 使用环境变量作为机密
  • ✅ 从不将凭据提交到源代码管理
  • ✅ 使用 .env 本地开发文件
  • ✅ 使用短期令牌进行测试

生产

  • ✅ 使用HTTPS进行所有通信
  • ✅ 将机密存储在Azure密钥库/AWS机密管理器中
  • ✅ 为OAuth提供者启用MFA
  • ✅ 实施速率限制
  • ✅ 监控身份验证日志
  • ✅ 每个环境使用单独的应用程序注册
  • ✅ 验证令牌范围是否与所需权限匹配

📦 NuGet包

从NuGet安装(发布时):

dotnet add package DotnetFastMCP

🤝 贡献

欢迎投稿!拜托:

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

🔗 资源

官方文件

框架文档

供应商文件

🐛 问题与支持

对于错误报告和功能请求,请使用 .

✨ 新增功能

v1.15.0-健康检查和诊断(最新版本-2026年4月)

  • 🏥 内置健康端点 - GET /mcp/health 暴露在一个单一 builder.WithHealthChecks() 呼叫
  • 🔌 基于Lambda的自定义检查 -添加任何复选框(database, llm, memory,外部API)作为一个简单的lambda,没有要实现的接口
  • 并行执行 -所有检查同时进行;慢支票决不会耽误快支票
  • ⏱️ 每次检查超时 -可配置 MaxResponseTimeMs;悬挂支票报告为 Degraded,不左挡
  • 🌐 标准HTTP状态代码 -200健康/207降级/503不健康;Kubernetes、负载均衡器和APM工具本机理解
  • 📊 自动服务器诊断 -自动包括服务器名称、框架版本、工具/资源/提示计数和正常运行时间
  • 🛡️ 始终可达 -端点已标记 AllowAnonymous() 因此,基础设施探测绕过了身份验证
  • 🎯 零开销 -完全选择加入;除非满足以下条件,否则不会注册终结点 WithHealthChecks() 被称为
  • 📚 综合文档 -涵盖Kubernetes、Docker、ACA探针、验证演练和单元测试的完整指南

v1.14.0-开放遥测可观测性(2026年3月)

  • 📡 开放遥测集成 -内置一流的指标和分布式跟踪
  • 📊 5个自动跟踪指标 -工具调用、持续时间、错误、提示请求、资源读取
  • 单线设置 - builder.WithTelemetry() 零样板
  • 🔌 出口商不可知 -适用于Prometheus、App Insights、Grafana、Jaeger以及任何OTLP后端
  • 🔍 分布式跟踪 -OTel语义约定标签的全范围支持
  • 🛡️ PII安全默认值 -除非明确启用,否则从不记录工具输入
  • 🎯 零开销 -完全选择加入,不使用时无需付费
  • 📚 综合文档 -包含验证示例和生产清单的完整指南

v1.13.0-法学硕士集成(2026年2月)

  • 🤖 8 LLM提供商 -Ollama、OpenAI、Azure OpenAI、拟人克劳德、谷歌双子座、科恩、拥抱脸、Deepseek
  • 最新款式 -Claude Opus 4.6(1M上下文),Gemini 3 Pro/Flash,命令A,DeepSeek V3.2
  • 🔌 统一接口 -单身 ILLMProvider API适用于所有提供商
  • 📡 流媒体支持 -实时令牌流 IAsyncEnumerable
  • 🏗️ 生产就绪 -HttpClientFactory、Polly重试策略、连接池
  • 🎯 即插即用 -简单注册: builder.AddAnthropicProvider()
  • 📚 综合文档 -完整的集成指南,附示例

v1.12.0-MFA支持

  • 🛡️ MFA执法 -需要 mfa 敏感工具的AMR索赔
  • 精细控制 -使用每个工具启用 [AuthorizeMcpTool(RequireMfa=true)]
  • 🔒 增强安全性 -基于标准的多因素身份验证检查

v1.11.0-二进制内容支持

  • 多态性内容 -支持混合文本和图像响应
  • 图像支持 -从工具返回Base64编码的图像
  • 多模式提示 -在LLM上下文提示中添加图片

v1.10.0-图标支持

  • 服务器图标 -为您的MCP服务器定义一个品牌图标
  • 工具/资源图标 -直观地区分能力
  • UI/UX增强 -实现更丰富的客户体验

v1.9.0-后台任务

  • 即发即弃 -从工具中卸载长时间运行的操作
  • 非阻塞 -立即回复客户
  • 托管服务 -使用Channels的内置排队机制

v1.8.0-存储抽象

  • 状态持久性 -工具现在可以通过以下方式持久化数据 McpContext.Storage
  • 可插拔后端 -轻松交换Redis/SQL/文件存储
  • 内存默认值 -零配置内置存储用于开发

v1.7.0-服务器组成

  • 服务器组成 -将其他MCP服务器作为模块安装(微型MCP)
  • 命名空间 -自动为导入的工具添加前缀(例如。, github_createIssue)
  • 零开销 -高性能内部字典路由(O(1))

v1.6.0-中间件拦截

  • 中间件管道 -拦截和修改请求/响应
  • 关键修复 -解决了Stdio传输初始化死锁
  • 生成器API -轻松注册 AddMcpMiddleware

v1.5.0-本机客户端库

  • McpClient -类型安全。用于消费MCP服务器的NET客户端
  • 运输不可知 -支持Stdio和SSE连接
  • 通知处理 -实时日志和进度事件

v1.4.0-服务器发送事件(SSE)

  • 苏格兰和南方能源公司运输 -实时服务器到客户端流传输
  • 异步通知 -将日志和进度更新推送到HTTP客户端

v1.3.0-上下文与交互

  • 上下文系统 - McpContext 测井注入与进展
  • IMcp会议 -与传输无关的交互抽象

v1.2.0-协议发现

  • 动态发现 -自动发现工具、资源和提示
  • 提示/列表 -完全支持提示模板

v1.1.0-标准传输和身份验证

  • 标准运输 -对stdio通信的初步支持
  • 🔐 6个OAuth提供者 -Azure AD、谷歌、GitHub、Auth0、Okta、AWS Cognito
  • 🔐 OAuth代理 -内置DCR支持

v1.0.0-核心框架

  • ✅ 基于属性的API
  • ✅ JSON-RPC 2.0合规性
  • ✅ ASP。NET核心集成

制作❤️ DotnetFastMCP团队

⭐ 如果你觉得这个仓库有用,就把它标上!

目录标签

目录标签

C#ClaudeAI代理企业级认证本地部署JSON-RPCOAuth2.0ASP.NETCoreLLM集成

支持客户端

ClaudeVS Code

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

oauth

工具数量(toolCount,工具数)

0

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明oauth部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP