0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ASP.NET Core で MCP Server を構築する RTA

Posted at

やりたいこと

  • Visual Studio を使って
  • ASP.NET Core で MCP Server を構築
  • 動作確認

背景

先人により C#/.NET で MCP Server を構築する方法が示されていますが、Visual Studio をつかって爆速で構築して完全に理解した気になりたいのです。
MCP についてや仕組みは先人の記事にお任せします。

環境

  • Microsoft Visual Studio Community 2022 (64 ビット)
    • Version 17.14.12

実装手順

ソリューション・プロジェクト作成

  • 自由に名前を付けてソリューション・プロジェクトを作成
  • ASP.NET Core で検索し、ASP.NET Core (空) のプロジェクトを追加

image.png

パッケージの追加

  • NuGet パッケージ マネージャー で ModelContextProtocol を検索して追加

「プレリリースを含める」にチェックを入れると出てきます。(2025/08/17 現在の最新バージョンは 0.3.0-preview.3 です。)

image.png

Program.cs の変更

  • Program.cs を以下のように変更
HostApplicationBuilder builder = Host.CreateEmptyApplicationBuilder(settings: null);

builder.Services.AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

IHost app = builder.Build();

app.Run();

CreateEmptyApplicationBuilder を使わないとコンソールに余計な出力がでてしまい後の動作確認がうまくいきません。

Tool を追加する

外部から呼び出される Tool を追加します。とりあえずリテラルの文字列を返す get_message というツールを追加します。

  1. プロジェクト直下に Tools フォルダーを追加する
  2. Tools フォルダーにクラスを追加する(かなり適当です)
DemoTool.cs
using ModelContextProtocol.Server;
using System.ComponentModel;

namespace HigeDaruma.DemoMcpServer.WebApplication2.Tools;

[McpServerToolType]
public sealed class DemoTool
{
    [McpServerTool]
    [Description("A simple demo tool for demonstration purposes.")]
    public async Task<string> GetMessage()
    {
        // Simulate some asynchronous operation
        await Task.Delay(1000);
        
        // Return a message
        return "Hello from DemoTool!";
    }
}

なんと、これで完成です。

動作確認

「MCP インスペクター」を使って動作確認をします。

  1. 開発者コマンドプロンプトを開き、プロジェクトのあるディレクトリに移動
  2. npx @modelcontextprotocol/inspector を実行
    1. 初回はインストールが走る
    2. 2025/08/17 時点の最新バージョンは v0.16.4
  3. サーバーが立ち上がり、ブラウザで表示される
    image.png
  4. Command を dotnet、Arguments を run に設定して Connect をクリック
  5. しばらく待つと接続される(はず)
    image.png
  6. List Tools をクリックすると 'get_message' が表示される
    image.png
  7. get_message を選択すると Description が右側に表示され、Run Tool をクリックすると...
    image.png
  8. 応答が表示される
    image.png

まとめ

Visual Studio から爆速で MCP Server が構築できました。今後はこれを Azure にデプロイし、ChatGPT などから呼び出せる形にしていきたいと思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?