9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2025-04-07

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

9
3
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
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?