共用方式為


使用 C# 建立最小的 MCP 伺服器併發佈至 NuGet

在本快速入門中,您會使用 適用於 MCP 的 C# SDK 建立最小模型內容通訊協定 (MCP) 伺服器、使用 GitHub Copilot 連線到該伺服器,並將其發佈至 NuGet。 MCP 伺服器是透過模型內容通訊協定 (MCP) 向客戶端公開功能的服務。

備註

Microsoft.Extensions.AI.Templates 體驗目前為預覽版本。 此範本會使用 ModelContextProtocol 連結庫和 MCP 登錄 server.json 架構,這兩者都是處於預覽狀態。

先決條件

建立專案

  1. 在終端機視窗中,安裝 MCP 伺服器範本 (9.10.0-preview.3.25513.3 版或更新版本):

    dotnet new install Microsoft.Extensions.AI.Templates
    
  2. 使用 dotnet new mcpserver 指令建立新的 MCP 伺服器應用程式:

    dotnet new mcpserver -n SampleMcpServer
    

    根據預設,此命令會建立獨立的工具套件,以支援 .NET 的所有最常見平臺為目標。 若要查看更多選項,請使用 dotnet new mcpserver --help

  3. 瀏覽至 SampleMcpServer 目錄:

    cd SampleMcpServer
    
  4. 建置專案:

    dotnet build
    
  5. <PackageId> 更新為在 NuGet.org 上唯一的,例如位於 .csproj 檔案中的 <NuGet.org username>.SampleMcpServer

在 Visual Studio Code 中設定 MCP 伺服器

設定 GitHub Copilot for Visual Studio Code 以使用您的自定義 MCP 伺服器:

  1. 如果您尚未開啟,請在 Visual Studio Code 中開啟您的項目資料夾。

  2. .vscode 專案的根目錄建立資料夾。

  3. mcp.json 資料夾中新增一個.vscode檔案,包含以下內容:

    {
      "servers": {
        "SampleMcpServer": {
          "type": "stdio",
          "command": "dotnet",
          "args": [
            "run",
            "--project",
            "<relative-path-to-project-file>"
          ]
        }
      }
    }
    

    備註

    VS Code 會從工作區根目錄執行 MCP 伺服器。 預留位置 <relative-path-to-project-file> 應指向您的 .NET 專案檔案。 例如,此 SampleMcpServer 應用程式的值會是 SampleMcpServer.csproj

  4. 儲存檔案。

測試 MCP 伺服器

MCP 伺服器範本包含一個稱為 get_random_number 的工具,可用來進行測試,並作為開發的起點。

  1. 在 Visual Studio Code 中開啟 GitHub Copilot,然後切換至代理程式模式。

  2. 選取 [ 選取工具] 圖示,以確認 您的 SampleMcpServer 可使用列出的範例工具。

    顯示可用 MCP 工具的螢幕快照。

  3. 輸入提示以執行 get_random_number 工具:

    Give me a random number between 1 and 100.
    
  4. GitHub Copilot 會要求許可權,以執行提示 get_random_number 工具。 選取 [繼續 ] 或使用箭號來選取更特定的行為:

    • 目前的會話 一律會在目前的 GitHub Copilot 代理程式模式會話中執行作業。
    • 目前工作區 總是執行目前 Visual Studio Code 工作區的命令。
    • 一律允許 將作業設定為一律針對任何 GitHub Copilot 代理程式模式會話或任何 Visual Studio Code 工作區執行。
  5. 確認伺服器是否回應了一個隨機數字。

    Your random number is 42.
    

新增輸入和組態選項

在此範例中,您會增強 MCP 伺服器,以使用環境變數中設定的組態值。 這可能是 MCP 伺服器運作所需的設定,例如 API 金鑰、要連線的端點,或本機目錄路徑。

  1. GetRandomNumber中的Tools/RandomNumberTools.cs方法之後,新增另一個工具方法。 更新工具程式代碼以使用環境變數。

    [McpServerTool]
    [Description("Describes random weather in the provided city.")]
    public string GetCityWeather(
        [Description("Name of the city to return weather for")] string city)
    {
        // Read the environment variable during tool execution.
        // Alternatively, this could be read during startup and passed via IOptions dependency injection
        var weather = Environment.GetEnvironmentVariable("WEATHER_CHOICES");
        if (string.IsNullOrWhiteSpace(weather))
        {
            weather = "balmy,rainy,stormy";
        }
    
        var weatherChoices = weather.Split(",");
        var selectedWeatherIndex =  Random.Shared.Next(0, weatherChoices.Length);
    
        return $"The weather in {city} is {weatherChoices[selectedWeatherIndex]}.";
    }
    
  2. 更新.vscode/mcp.json以設定要測試的WEATHER_CHOICES環境變數。

    {
       "servers": {
         "SampleMcpServer": {
           "type": "stdio",
           "command": "dotnet",
           "args": [
             "run",
             "--project",
             "<relative-path-to-project-file>"
           ],
           "env": {
              "WEATHER_CHOICES": "sunny,humid,freezing"
           }
         }
       }
     }
    
  3. 在 VS Code 中使用 Copilot 嘗試另一個提示,例如:

    What is the weather in Redmond, Washington?
    

    VS Code 應該會傳回隨機天氣描述。

  4. .mcp/server.json更新為宣告您的環境變數輸入。 檔案 server.json 架構是由 MCP登錄專案 所定義,並由 NuGet.org 用來產生 VS Code MCP 組態。

    • environmentVariables使用 屬性來宣告應用程式所使用的環境變數,這些環境變數將由用戶端使用 MCP 伺服器設定(例如 VS Code)。

    • packageArguments使用屬性來定義將傳遞至應用程式的 CLI 自變數。 如需更多範例,請參閱 MCP登錄專案

    {
      "$schema": "https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json",
      "description": "<your description here>",
      "name": "io.github.<your GitHub username here>/<your repo name>",
      "version": "<your package version here>",
      "packages": [
        {
          "registryType": "nuget",
          "registryBaseUrl": "https://api.nuget.org",
          "identifier": "<your package ID here>",
          "version": "<your package version here>",
          "transport": {
            "type": "stdio"
          },
          "packageArguments": [],
          "environmentVariables": [
            {
              "name": "WEATHER_CHOICES",
              "value": "{weather_choices}",
              "variables": {
                "weather_choices": {
                  "description": "Comma separated list of weather descriptions to randomly select.",
                  "isRequired": true,
                  "isSecret": false
                }
              }
            }
          ]
        }
      ],
      "repository": {
        "url": "https://github.com/<your GitHub username here>/<your repo name>",
        "source": "github"
      }
    }
    

    NuGet.org 在 server.json 中唯一使用的資訊是第一個packages陣列專案,其registryType值符合nuget。 除了 packages 屬性之外,其他最上層屬性目前未使用,並且會用於即將推出的中央 MCP 登錄。 您可以保留佔位值,直到 MCP 註冊表上線並準備好接受 MCP 伺服器項目為止。

您可以 再次測試 MCP 伺服器 ,再繼續進行。

封裝併發佈至 NuGet

  1. 封裝專案:

    dotnet pack -c Release
    

    此指令會根據 中的<RuntimeIdentifiers>清單產生SampleMcpServer.csproj一個工具套件和數個平台特定套件。

  2. 將套件發佈至 NuGet:

    dotnet nuget push bin/Release/*.nupkg --api-key <your-api-key> --source https://api.nuget.org/v3/index.json
    

    請務必發佈所有 .nupkg 檔案,以確保每個支援的平台都可以執行 MCP 伺服器。

    如果您想要在發佈至 NuGet.org 之前先測試發佈流程,您可以在 NuGet 資源庫整合環境中註冊帳戶: https://int.nugettest.org。命令 push 會修改為:

    dotnet nuget push bin/Release/*.nupkg --api-key <your-api-key> --source https://apiint.nugettest.org/v3/index.json
    

如需詳細資訊,請參閱 發佈套件

探索 NuGet.org 上的MCP伺服器

  1. NuGet.org 上搜尋 MCP 伺服器套件(或如果您發佈至整合環境 ,int.nugettest.org ),然後從清單中選取它。

    顯示 NuGet.org 上 MCP 伺服器的搜尋螢幕快照。

  2. 檢視套件詳細數據,並從 [MCP 伺服器] 索引標籤複製 JSON。

    在 NuGet.org 上顯示的特定 MCP 伺服器的螢幕快照。

  3. mcp.json 資料夾中的 .vscode 檔案中,新增複製的 JSON,如下所示:

    {
      "inputs": [
        {
          "type": "promptString",
          "id": "weather_choices",
          "description": "Comma separated list of weather descriptions to randomly select.",
          "password": false
        }
      ],
      "servers": {
        "Contoso.SampleMcpServer": {
          "type": "stdio",
          "command": "dnx",
          "args": ["Contoso.SampleMcpServer@0.0.1-beta", "--yes"],
          "env": {
            "WEATHER_CHOICES": "${input:weather_choices}"
          }
        }
      }
    }
    

    如果您發佈至 NuGet 畫廊整合環境,則必須在"--add-source", "https://apiint.nugettest.org/v3/index.json"陣列結尾新增"args"

  4. 儲存檔案。

  5. 在 GitHub Copilot 中,選取 [ 選取工具 ] 圖示,以確認 您的 SampleMcpServer 可供列出的工具使用。

  6. 輸入提示以執行新的 get_city_weather 工具:

    What is the weather in Redmond?
    
  7. 如果您已將輸入新增至 MCP 伺服器(例如 WEATHER_CHOICES),系統會提示您提供值。

  8. 確認伺服器回應隨機天氣:

    The weather in Redmond is balmy.
    

常見問題

找不到執行 SampleMcpServer 所需的命令「dnx」

如果 VS Code 在啟動 MCP 伺服器時顯示此錯誤,您需要安裝相容版本的 .NET SDK。

顯示 VS Code 中遺漏 dnx 命令的螢幕快照。

dnx 命令會隨附為 .NET SDK 的一部分,從第 10 版開始。 安裝 .NET 10 SDK 以解決此問題。

GitHub Copilot 不會使用您的工具 (會在不叫用您的工具的情況下提供答案)

一般來說,像 GitHub Copilot 的 AI 代理程式會由用戶端應用程式(例如 VS Code)告知其具備可用的工具。 某些工具,例如範例隨機數工具,可能無法由 AI 代理程式利用,因為它內建了類似的功能。

如果您的工具沒有被使用,請檢查以下項目:

  1. 確認您的工具出現在 VS Code 已啟用的工具清單中。 如需如何檢查此問題 ,請參閱測試 MCP 伺服器 中的螢幕快照。
  2. 請在您的指令中明確指出工具的名稱。 在 VS Code 中,您可以依名稱參考工具。 例如: Using #get_random_weather, what is the weather in Redmond?
  3. 確認您的 MCP 伺服器能夠啟動。 您可以按下 VS Code 使用者或工作區設定中 MCP 伺服器組態上方顯示的 [開始] 按鈕來檢查此情況。

螢幕快照,顯示 VS Code 設定中已啟動的 MCP 伺服器。