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?

C#でMCPサーバーを自作してClaude Codeのツールに追加してみた

0
Posted at

この記事は tk3.biz のブログ からの転載です。

はじめに

Claude Code などのAIコーディングアシスタントは、MCP(Model Context Protocol) というプロトコルを通じてカスタムツールを追加できます。

「自作ツールを繋げる」と聞くと難しそうですが、公式のC# SDKを使うと驚くほどシンプルに実装できます。今回は天気取得ツールを例に、ゼロからMCPサーバーを作ってClaude Codeに接続するまでを試してみました。

MCPとは?

MCP(Model Context Protocol)はAnthropicが2024年に公開したオープンプロトコルです。AIと外部ツール・データソースが標準インターフェースで通信できるようにする仕組みです。

Claude Code ←→ MCPプロトコル ←→ 自作MCPサーバー ←→ 外部API・DBなど

MCPサーバーを自作することで「社内APIを叩くツール」「プロジェクト固有の操作」などをAIに追加できます。

用意するもの

  • .NET 9 SDK
  • Claude Code(設定ファイルを編集できる状態)

プロジェクト作成

コンソールアプリとして作成します。

dotnet new console -n WeatherMcp
cd WeatherMcp

NuGetパッケージを追加します。

dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting

ModelContextProtocolとは?
Microsoftが管理するC#公式MCP SDK。Toolの定義を属性ベースで書けるため実装がシンプルです。

実装

Program.cs

Program.cs をまるごと以下に置き換えます。

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

var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddMcpServer()
    .WithStdioServerTransport()
    .WithTools<WeatherTools>();

await builder.Build().RunAsync();

WeatherTools.cs

プロジェクトに WeatherTools.cs を新規作成します。

using ModelContextProtocol.Server;
using System.ComponentModel;

[McpServerToolType]
public class WeatherTools
{
    private static readonly HttpClient _http = new();

    [McpServerTool]
    [Description("指定した都市の現在の天気(天候・気温・湿度)を取得します")]
    public static async Task<string> GetWeather(
        [Description("都市名(英語)例: Tokyo, Osaka, New York")] string city)
    {
        var url = $"https://wttr.in/{Uri.EscapeDataString(city)}?format=%C+%t+%h";
        var result = await _http.GetStringAsync(url);
        return $"{city}の天気: {result.Trim()}";
    }
}

ポイント:

属性 役割
[McpServerToolType] このクラスにToolが含まれることを宣言
[McpServerTool] このメソッドをToolとして公開
[Description] AIへの説明文。AIがToolの使い方を理解するために重要

天気データは wttr.in を使います。APIキー不要で使える便利なサービスです。フォーマット文字列の意味:

記号 内容
%C 天候の説明(Sunny、Cloudy など)
%t 気温
%h 湿度

単体動作確認

Claude Codeに繋ぐ前に単体で確認します。

dotnet run

起動したら標準入力に以下をペーストしてEnterを押します。

{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {} }

GetWeather ツールの情報が返ってきたら成功です。Ctrl+C で終了します。

Claude Codeに登録する

Claude Codeの設定ファイルに追記します。

  • プロジェクト単位: .claude/settings.json
  • グローバル: ~/.claude/settings.json
{
  "mcpServers": {
    "weather": {
      "command": "dotnet",
      "args": ["run", "--project", "C:/path/to/WeatherMcp"]
    }
  }
}

C:/path/to/WeatherMcp は実際のパスに変えてください。

起動を速くするには
dotnet run は毎回ビルドが走るため起動が遅めです。dotnet publish でexeを生成して直接指定するのがおすすめです。

dotnet publish -c Release -r win-x64 --self-contained
{
  "mcpServers": {
    "weather": {
      "command": "C:/path/to/WeatherMcp/bin/Release/net9.0/win-x64/publish/WeatherMcp.exe",
      "args": []
    }
  }
}

実際に使ってみる

設定後にClaude Codeを再起動すると weather サーバーが接続されます。そのまま話しかけると:

> 東京と大阪の今日の天気を比較して

Claude Codeが GetWeather を2回呼び出し、wttr.inから取得した結果をまとめて返してくれます。

[Tool: GetWeather(city="Tokyo")]    → Overcast +18°C 72%
[Tool: GetWeather(city="Osaka")]    → Partly cloudy +20°C 65%

東京は曇り・18℃・湿度72%、大阪は晴れ時々曇り・20℃・湿度65%です。
大阪の方が2℃高く、湿度は低めです。

ツール呼び出しの様子が見えるのが面白いところです。

まとめ

C#でMCPサーバーを作る手順を振り返ります:

  1. ModelContextProtocol NuGetパッケージを追加
  2. [McpServerToolType] / [McpServerTool] でToolを定義
  3. AddMcpServer().WithStdioServerTransport().WithTools<T>() でサーバー起動
  4. settings.json に登録してClaude Codeから呼び出す

全体的に実装量は少なく、属性を付けるだけでToolとして認識されるのが快適でした。天気APIの代わりに社内REST APIやSQLクエリを呼ぶToolに差し替えるだけで、実務でも十分使えそうです。自分専用のAIツールキットを育てていく感覚で、今後も試していきたいと思います。

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?