LOADING

加载过慢请开启缓存 浏览器默认开启

微软官方ModelContextProtocol工具使用指南

微软提供了一系列官方MCP工具,让.NET开发者能够轻松构建AI驱动的应用。本文介绍微软官方MCP工具的完整生态和使用方法。

微软MCP工具生态

微软围绕MCP协议提供了多个官方工具和服务:

工具 用途 NuGet包
MCP C# SDK 构建MCP服务器和客户端 ModelContextProtocol
Azure MCP Server 连接Azure服务 azure-mcp
GitHub MCP Server 连接GitHub API github-mcp-server
NuGet MCP Server 包管理和漏洞修复 内置VS 2026

1. MCP C# SDK

安装

# 完整包(推荐)
dotnet add package ModelContextProtocol

# 仅核心包
dotnet add package ModelContextProtocol.Core

# ASP.NET Core集成
dotnet add package ModelContextProtocol.AspNetCore

创建MCP服务器

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;
using System.ComponentModel;

// 定义工具类
[McpServerToolType]
public class MyTools
{
    [McpServerTool, Description("查询数据库")]
    public static async Task<string> QueryDatabase(string sql)
    {
        // 实现数据库查询
        return $"执行结果: {sql}";
    }

    [McpServerTool, Description("发送邮件")]
    public static async Task<string> SendEmail(string to, string subject, string body)
    {
        // 实现邮件发送
        return $"邮件已发送至 {to}";
    }
}

// 启动服务器
var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddMcpServer(options =>
{
    options.ServerInfo = new() 
    { 
        Name = "MyMcpServer", 
        Version = "1.0.0" 
    };
})
.WithStdioServerTransport()
.WithToolsFromAssembly();

await builder.Build().RunAsync();

创建MCP客户端

using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;

// 连接到MCP服务器
var clientTransport = new StdioClientTransport(new()
{
    Name = "MyMcpServer",
    Command = "dotnet",
    Arguments = ["run", "--project", "路径/MyMcpServer"]
});

var client = await McpClientFactory.CreateAsync(clientTransport);

// 列出可用工具
var tools = await client.ListToolsAsync();
foreach (var tool in tools)
{
    Console.WriteLine($"工具: {tool.Name} - {tool.Description}");
}

// 调用工具
var result = await client.CallToolAsync("QueryDatabase", new Dictionary<string, object?>
{
    ["sql"] = "SELECT * FROM Users"
});

Console.WriteLine(result.Content.First(c => c.Type == "text").Text);

2. Azure MCP Server

Azure MCP Server让AI助手能够直接操作Azure服务。

安装配置

// .vscode/mcp.json
{
  "servers": {
    "azure": {
      "command": "npx",
      "args": ["-y", "@azure/mcp@latest", "server"]
    }
  }
}

支持的Azure服务

  • Azure Storage - Blob、Queue、Table操作
  • Azure Key Vault - 密钥和密钥管理
  • Azure SQL - 数据库查询和管理
  • Azure Cosmos DB - NoSQL数据操作
  • Azure App Service - Web应用管理
  • Azure Monitor - 日志和指标查询

使用示例

在VS Code中使用GitHub Copilot Chat:

@azure 列出我的存储账户
@azure 查询Key Vault中的密钥
@azure 在SQL数据库中执行查询

3. GitHub MCP Server

GitHub MCP Server让AI助手能够直接操作GitHub仓库。

安装配置

// .vscode/mcp.json
{
  "servers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "your-token"
      }
    }
  }
}

支持的功能

  • 仓库浏览和搜索
  • Issue和PR管理
  • 代码搜索和查看
  • 文件操作

4. NuGet MCP Server

NuGet MCP Server集成在Visual Studio 2026中,帮助管理NuGet包。

启用方法

  1. 打开Visual Studio 2026
  2. 打开GitHub Copilot Chat窗口
  3. 点击工具栏底部的Tools图标
  4. 找到”nuget” MCP服务器并启用

使用示例

检查我的项目中的包漏洞
修复所有安全漏洞
更新到最新版本的Newtonsoft.Json

5. VS Code集成

配置MCP服务器

在VS Code中,可以通过以下方式配置MCP服务器:

  1. settings.json - 全局配置
  2. .vscode/mcp.json - 项目级配置
  3. mcp.json - 工作区配置

配置示例

{
  "servers": {
    "my-server": {
      "command": "dotnet",
      "args": ["run", "--project", "${workspaceFolder}/MyMcpServer"],
      "env": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "azure": {
      "command": "npx",
      "args": ["-y", "@azure/mcp@latest", "server"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "${env:GITHUB_TOKEN}"
      }
    }
  }
}

在Copilot Chat中使用

# 使用工具
@workspace 使用数据库工具查询用户表

# 查看可用工具
/mcp

# 测试工具
/my-server 调用QueryDatabase工具

6. 最佳实践

工具设计原则

[McpServerToolType]
public class BestPracticeTools
{
    // 1. 提供清晰的Description
    [McpServerTool, Description("从数据库查询用户信息,支持按ID或名称查询")]
    public static async Task<string> GetUser(
        [Description("用户ID")] int? userId = null,
        [Description("用户名")] string? userName = null)
    {
        // 2. 参数验证
        if (!userId.HasValue && string.IsNullOrEmpty(userName))
            return "错误:必须提供userId或userName";

        // 3. 返回结构化数据
        return JsonSerializer.Serialize(new
        {
            Id = userId,
            Name = userName,
            Email = "user@example.com"
        });
    }
}

错误处理

[McpServerTool, Description("安全的文件操作")]
public static async Task<string> SafeFileOperation(string path)
{
    try
    {
        // 实现文件操作
        return $"文件操作成功: {path}";
    }
    catch (UnauthorizedAccessException)
    {
        return "错误:没有访问权限";
    }
    catch (FileNotFoundException)
    {
        return "错误:文件不存在";
    }
    catch (Exception ex)
    {
        return $"错误:{ex.Message}";
    }
}

依赖注入

[McpServerToolType]
public class ServiceTools
{
    private readonly ILogger<ServiceTools> _logger;
    private readonly IConfiguration _config;

    public ServiceTools(ILogger<ServiceTools> logger, IConfiguration config)
    {
        _logger = logger;
        _config = config;
    }

    [McpServerTool, Description("使用DI服务的工具")]
    public async Task<string> ToolWithDI(string input)
    {
        _logger.LogInformation("执行工具: {Input}", input);
        var setting = _config["MySetting"];
        return $"配置值: {setting}";
    }
}

// 注册服务
builder.Services.AddScoped<ServiceTools>();
builder.Services.AddMcpServer()
    .WithTools<ServiceTools>();

7. 发布到NuGet

将你的MCP服务器发布到NuGet,让其他人使用:

<!-- MyMcpServer.csproj -->
<PropertyGroup>
    <PackageId>MyMcpServer</PackageId>
    <Version>1.0.0</Version>
    <Authors>Your Name</Authors>
    <Description>MCP服务器示例</Description>
    <PackAsTool>true</PackAsTool>
    <ToolCommandName>my-mcp-server</ToolCommandName>
</PropertyGroup>
dotnet pack
dotnet nuget push ./bin/Release/*.nupkg --api-key YOUR_API_KEY --source https://api.nuget.org/v3/index.json

总结

微软官方MCP工具生态为.NET开发者提供了完整的AI集成方案:

  • MCP C# SDK - 核心SDK,构建服务器和客户端
  • Azure MCP Server - 连接Azure云服务
  • GitHub MCP Server - 操作GitHub仓库
  • NuGet MCP Server - 包管理和安全检查
  • VS Code集成 - 无缝开发体验

通过这些工具,你可以让AI助手直接操作数据库、云服务、代码仓库,实现真正的AI驱动开发。

参考资料