mcp-rb で1ファイルで動く MCP サーバーを書く #Ruby

LLM の機能を拡張するプロトコルとして MCP がある。(LSP みたいな感じ)

Ruby だと mcp-rb を使うことで実装が簡単にできる。

以下のように簡単な DSL で MCP サーバーが作れる。

require 'mcp-rb'

name 'local-mcp'
version '0.1.0'

resource "file://how-to-calculate-square" do
  name "how-to-calculate-square"
  description "Show how to calculate the square of a number"
  call { "Use calculate-square tool" }
end

tool "calculate-square" do
  description "Calculate the square of a number"

  argument :number, Integer, required: true, description: "The number to be squared"

  call do |args|
    args[:number] * args[:number]
  end
end

Claude, Cline, Copilot Agent など、様々なクライアントで MCP の対応が行われている。

image.png

bundler/inline と併用するのがおすすめ

利用する際には bundler/inline と併用するのがおすすめ。
依存関係をファイル内に記述できるので、単体で実行しやすくなるのと、特定プロジェクト用の MCP サーバーを実装して、関係者に配るとかでは便利。

こんな感じで外部 API を叩くような MCP サーバーが簡単に書ける。

#!/usr/bin/env ruby

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'

  gem 'mcp-rb', require: 'mcp'
  gem 'octokit'
end

name 'twitter-from-github'
version '0.1.0'

tool "twitter-from-github" do
  description "Tell me about the twitter name of the user from GitHub status"

  argument :username, String, required: true, description: "The name of GitHub user that you want to know the twitter name"

  call do |args|
    client = Octokit::Client.new
    user = client.user(args[:username])
    user.twitter_username
  end
end

image.png



フラッグシティパートナーズ海外不動産投資セミナー 【DMM FX】入金

Source link