Mirror of https://github.com/modelcontextprotocol/ruby-sdk — The official Ruby SDK for the Model Context Protocol servers and clients.
  • Ruby 99.8%
  • Shell 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Koichi ITO 088f4b99e4 Answer server-to-client pings in the client
## Motivation and Context

The ping utility says the receiver "MUST respond promptly with an empty response",
and a server may treat a missing answer as a stale connection and drop it. Both reference SDKs honor
that on the client side (the TypeScript protocol layer installs an automatic pong,
and the Python session answers `PingRequest` with an empty result), but this client answered
a server ping with Method not found over Streamable HTTP and ignored it entirely over stdio,
leaving long-lived legacy sessions vulnerable to a liveness-checking server.

Over HTTP, an unhandled `ping` is now answered with the empty result in `dispatch_server_request`.
The default deliberately does not live in `@server_request_handlers`: that registry's `any?` opens
the GET listening stream on connect, and a built-in pong must not change listener behavior -
a server can only ping on a stream that is already open. A handler registered via
`on_server_request("ping")` still wins.

Over stdio, the read loop now answers a ping frame inline and keeps waiting for its response.
Frames are told apart by shape rather than id: one carrying `method` is a request or notification,
never the awaited response, so a server-chosen ping id that collides with the awaited one is still answered -
and a request frame can no longer be returned to the caller as if it were the response.
Between requests nothing reads stdout, so a queued ping is answered when the next request starts reading,
which is inherent to the single-threaded stdio client. Other server-to-client requests over stdio stay
unsupported as documented.

The pong is best effort on both transports, in the ways the reference SDKs imply: a pong that cannot be written
over a broken stdin is dropped instead of failing the unrelated request whose response the loop is reading,
and a ping whose id is not a String or a Number - a shape the TypeScript and Python schemas reject outright -
is not answered with a pong: over stdio it is skipped entirely, and over HTTP it falls through to Method not found,
exactly as before this change.

The modern lifecycle removes `ping` altogether (SEP-2575), so this applies to handshake-lifecycle connections only.

## How Has This Been Tested?

New transport tests: over HTTP, a ping delivered on the SSE stream results in a POSTed empty-result response with
the ping's id, and a user-registered `"ping"` handler overrides the default; over stdio, a ping injected while
a response is awaited is answered on stdin and the original response still returns. Both fail without the change
(Method not found / no answer). Further tests cover the best-effort edges: a pong write failure over
a closed stdin leaves the awaited response intact, and a malformed-id ping is skipped over stdio
and answered with Method not found over HTTP. `bundle exec rake` (tests, RuboCop, and conformance baseline) passes.

## Breaking Changes

None. A server ping that previously received Method not found (or nothing) now receives the empty result
the specification requires.
2026-09-03 16:55:06 +09:00
.github Group the conformance Rake tasks under a conformance namespace 2026-08-30 02:24:52 +09:00
bin Add API documentation with GitHub Pages deployment 2025-11-21 12:21:38 -06:00
conformance Group the conformance Rake tasks under a conformance namespace 2026-08-30 02:24:52 +09:00
docs Answer server-to-client pings in the client 2026-09-03 16:55:06 +09:00
examples Update examples for the 2026-07-28 era 2026-08-28 12:03:52 +09:00
lib Answer server-to-client pings in the client 2026-09-03 16:55:06 +09:00
test Answer server-to-client pings in the client 2026-09-03 16:55:06 +09:00
.gitattributes Internal Release v0.1.1 2025-05-08 17:37:27 -04:00
.gitignore Add a rake docs:preview task serving the docs site locally 2026-08-25 12:36:54 +09:00
.rubocop.yml Suppress RuboCop extension suggestions (#484) 2026-08-07 18:46:46 -04:00
AGENTS.md Group the conformance Rake tasks under a conformance namespace 2026-08-30 02:24:52 +09:00
CHANGELOG.md Release 1.4.0 2026-08-28 03:54:46 +09:00
CLAUDE.md Add CLAUDE.md referencing AGENTS.md 2026-04-01 01:03:43 +09:00
CODE_OF_CONDUCT.md Internal Release v0.1.1 2025-05-08 17:37:27 -04:00
dev.yml fix dev style (#208) 2026-01-06 01:00:31 -05:00
Gemfile Fix a build error in the Ruby 3.1 CI matrix 2026-06-18 09:20:59 +09:00
LICENSE chore: update licensing to Apache 2.0 for new contributions 2026-01-12 22:49:19 +00:00
mcp.gemspec Speed Up Tool::Schema Validation by 5x to 100x 2026-06-01 21:47:30 +09:00
Rakefile Group the conformance Rake tasks under a conformance namespace 2026-08-30 02:24:52 +09:00
README.md [Doc] Align the Docs Page Names With the MCP Specification 2026-08-22 18:07:38 +09:00
RELEASE.md [Docs] Extract release documentation to RELEASE.md 2025-11-04 11:13:39 +09:00
ROADMAP.md [Doc] Align the ROADMAP deprecation wording with the shipped behavior 2026-08-23 01:15:20 +09:00
SECURITY.md Add SECURITY.md with GitHub Security Advisories guidance (#232) 2026-02-18 20:49:17 -05:00
VERSIONING.md Add VERSIONING.md documenting the versioning and breaking-change policy 2026-07-21 11:33:20 +09:00

MCP Ruby SDK Gem Version Apache 2.0 licensed CI

The official Ruby SDK for Model Context Protocol servers and clients.

Detailed guides are available at https://ruby.sdk.modelcontextprotocol.io.

Features

  • Build MCP servers that expose tools, prompts, and resources to any MCP host
  • Build MCP clients that connect to any MCP server, with automatic lifecycle negotiation and OAuth 2.1 authorization
  • Speak every standard transport: stdio and Streamable HTTP (including SSE), with a Rails integration
  • Cover the full protocol surface: server-to-client requests, multi round-trip requests, notifications, progress, logging, cancellation, completions, and pagination

Installation

Add this line to your application's Gemfile:

gem "mcp"

And then execute:

$ bundle install

Or install it yourself as:

$ gem install mcp

You may need to add additional dependencies depending on which features you wish to access.

Quick Start

The following minimal programs show both sides of the protocol: a server that exposes a single tool, and a client that spawns such a server and drives it over stdio.

MCP Server

A minimal server defines a tool and serves it over the stdio transport:

require "mcp"

# Create a simple tool
class ExampleTool < MCP::Tool
  description "A simple example tool that echoes back its arguments"
  input_schema(
    properties: {
      message: { type: "string" },
    },
    required: ["message"]
  )

  class << self
    def call(message:, server_context:)
      MCP::Tool::Response.new([{
        type: "text",
        text: "Hello from example tool! Message: #{message}",
      }])
    end
  end
end

# Set up the server
server = MCP::Server.new(
  name: "example_server",
  tools: [ExampleTool],
)

# Create and start the transport
transport = MCP::Server::Transports::StdioTransport.new(server)
transport.open

Save the script as server.rb, run it, and send JSON-RPC requests via stdin:

$ ruby server.rb
{"jsonrpc":"2.0","id":"1","method":"ping"}
{"jsonrpc":"2.0","id":"2","method":"tools/list"}
{"jsonrpc":"2.0","id":"3","method":"tools/call","params":{"name":"example_tool","arguments":{"message":"Hello"}}}

The same server can also run over Streamable HTTP, including mounted inside a Rails application; see Server Transports.

MCP Client

A minimal client spawns a stdio server as a subprocess, connects, and lists and calls its tools:

stdio_transport = MCP::Client::Stdio.new(
  command: "bundle",
  args: ["exec", "ruby", "path/to/server.rb"],
  env: { "API_KEY" => "my_secret_key" },
  read_timeout: 30
)
client = MCP::Client.new(transport: stdio_transport)

# Perform the MCP initialization handshake before sending any requests.
client.connect

# List available tools.
tools = client.tools
tools.each do |tool|
  puts "Tool: #{tool.name} - #{tool.description}"
end

# Call a specific tool.
response = client.call_tool(
  tool: tools.first,
  arguments: { message: "Hello, world!" }
)

# Close the transport when done.
stdio_transport.close

The same client can connect to Streamable HTTP servers with MCP::Client::HTTP; see Client Transports.

Examples

Runnable examples are available in examples/, including a complete Rails application in examples/rails.

Documentation

License

This project is licensed under the Apache License 2.0 for new contributions, with existing code under MIT. See the LICENSE file for details.