1
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?

F#でMCPサーバーのサンプルを動かす

Posted at

はじめに

MCP(ModelContextProtocol)のC# SDKをF#で動かせるかを試してみました。

サンプルはMicrosoft Learnにある1~100まで数字をランダムに出力するMCPサーバーを作るところまでやってみました。

環境

実装

プロジェクト作成

  1. ターミナルでF#のプロジェクトを作成する
    dotnet new console -lang "F#" -n SampleMcpServer
    
  2. プロジェクトに移動する
    cd SampleMcpServer
    
  3. 使用するライブラリを追加する
    dotnet add package ModelContextProtocol --prerelease
    dotnet add package Microsoft.Extensions.Hosting
    
  4. VSCordeで開く
    code .
    

プログラム作成

  1. MCPの処理部分のTools/RandomNumberTools.fsを作成する
    Tools/RandomNumberTools.fs
    namespace Tools.RandomNumberTools
    
    open System
    open System.ComponentModel
    open System.Runtime.InteropServices
    open ModelContextProtocol.Server
    
    /// <summary>
    /// Sample MCP tools for demonstration purposes.
    /// These tools can be invoked by MCP clients to perform various operations.
    /// </summary>
    type internal RandomNumberTools() =
        [<McpServerTool>]
        [<Description("Generates a random number between the specified minimum and maximum values.")>]
        member _.GetRandomNumber(
            [<Description("Minimum value (inclusive)"); Optional; DefaultParameterValue(0)>] min:int,
            [<Description("Maximum value (exclusive)"); Optional; DefaultParameterValue(100)>] max:int) : int =
            Random.Shared.Next(min, max)
    
    
  2. 作成したTools/RandomNumberTools.fsをプロジェクトに設定する
    SampleMcpServer.fsproj
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net9.0</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <Compile Include="Tools\RandomNumberTools.fs" />
        <Compile Include="Program.fs" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.8" />
        <PackageReference Include="ModelContextProtocol" Version="0.3.0-preview.4" />
      </ItemGroup>
    
    </Project>
    
    
  3. Program.fsを以下に修正する
    Program.fs
    open Microsoft.Extensions.DependencyInjection
    open Microsoft.Extensions.Hosting
    open Microsoft.Extensions.Logging
    open Microsoft.Extensions.Logging.Console
    open Tools.RandomNumberTools
    
    [<EntryPoint>]
    let main argv =
        let builder = Host.CreateApplicationBuilder(argv)
    
        // Configure all logs to go to stderr (stdout is used for the MCP protocol messages).
        builder.Logging.AddConsole(fun (o: ConsoleLoggerOptions) -> o.LogToStandardErrorThreshold <- LogLevel.Trace) |> ignore
    
        // Add the MCP services: the transport to use (stdio) and the tools to register.
        builder.Services
            .AddMcpServer()
            .WithStdioServerTransport()
            .WithTools<RandomNumberTools>() |> ignore
    
        let app = builder.Build()
        app.RunAsync() |> Async.AwaitTask |> Async.RunSynchronously
    
        0 // Return
    
    
  4. VSCordeにMCPを設定するファイル.vscode\mcp.jsonを追加する。起動パスは作成したプロジェクトのパスをいれる
    .vscode\mcp.json
    {
      "servers": {
        "SampleMcpServer": {
          "type": "stdio",
          "command": "dotnet",
          "args": [
            "run",
            "--project",
            // ↓プロジェクトパスに書き換える
            "C:\\SampleMcpServer"
          ]
        }
      }
    }
    
    

MCPの起動

  1. .vscode\mcp.jsonで以下の画像のような"起動"ボタンが出るので、押して起動させる
    image.png
  2. GitHub Copilotのチャットを開く
  3. チャットのモードを"Agent"にする
  4. 以下の画像の更新ボタンを押す
    image.png
  5. "ツールの選択"からのツール一覧に作成したMCP(SampleMcpServer)があるのこを確認する
    image.png
    image.png
  6. 以下のプロンプトをチャットに入れて送信する
    プロンプト
    Give me a random number between 1 and 100.
    
  7. アクセス許可を要求されるので"継続"を選択する
    image.png
  8. MCPサーバーから返答が返ってくる
    image.png

以上

1
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
1
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?